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 | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/CSharpTest/ImplementInterface/ImplementImplicitlyTests.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.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.ImplementInterface;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface
{
public class ImplementImplicitlyTests : AbstractCSharpCodeActionTest
{
private const int SingleMember = 0;
private const int SameInterface = 1;
private const int AllInterfaces = 2;
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpImplementImplicitlyCodeRefactoringProvider();
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> FlattenActions(actions);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSingleMember()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
void IGoo.[||]Goo1() { }
void IGoo.Goo2() { }
void IBar.Bar() { }
}",
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
public void Goo1() { }
void IGoo.Goo2() { }
void IBar.Bar() { }
}", index: SingleMember);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSameInterface()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
void IGoo.[||]Goo1() { }
void IGoo.Goo2() { }
void IBar.Bar() { }
}",
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
public void Goo1() { }
public void Goo2() { }
void IBar.Bar() { }
}", index: SameInterface);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAllInterfaces()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
void IGoo.[||]Goo1() { }
void IGoo.Goo2() { }
void IBar.Bar() { }
}",
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
public void Goo1() { }
public void Goo2() { }
public void Bar() { }
}", index: AllInterfaces);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestProperty()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { int Goo1 { get; } }
class C : IGoo
{
int IGoo.[||]Goo1 { get { } }
}",
@"
interface IGoo { int Goo1 { get; } }
class C : IGoo
{
public int Goo1 { get { } }
}", index: SingleMember);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEvent()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { event Action E; }
class C : IGoo
{
event Action IGoo.[||]E { add { } remove { } }
}",
@"
interface IGoo { event Action E; }
class C : IGoo
{
public event Action E { add { } remove { } }
}", index: SingleMember);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNotOnImplicitMember()
{
await TestMissingAsync(
@"
interface IGoo { void Goo1(); }
class C : IGoo
{
public void [||]Goo1() { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNotOnUnboundExplicitImpl()
{
await TestMissingAsync(
@"
class C : IGoo
{
void IGoo.[||]Goo1() { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCollision()
{
// Currently we don't do anything special here. But we just test here to make sure we
// don't blow up here.
await TestInRegularAndScriptAsync(
@"
interface IGoo { void Goo1(); }
class C : IGoo
{
void IGoo.[||]Goo1() { }
private void Goo1() { }
}",
@"
interface IGoo { void Goo1(); }
class C : IGoo
{
public void Goo1() { }
private void Goo1() { }
}", index: SingleMember);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
[WorkItem(48027, "https://github.com/dotnet/roslyn/issues/48027")]
public async Task TestSingleMemberAndContainingTypeHasNoInterface()
{
await TestMissingAsync(
@"
using System;
using System.Collections;
class C
{
IEnumerator IEnumerable.[||]GetEnumerator()
{
throw new NotImplementedException();
}
}");
}
}
}
| // 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.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.ImplementInterface;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface
{
public class ImplementImplicitlyTests : AbstractCSharpCodeActionTest
{
private const int SingleMember = 0;
private const int SameInterface = 1;
private const int AllInterfaces = 2;
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpImplementImplicitlyCodeRefactoringProvider();
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> FlattenActions(actions);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSingleMember()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
void IGoo.[||]Goo1() { }
void IGoo.Goo2() { }
void IBar.Bar() { }
}",
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
public void Goo1() { }
void IGoo.Goo2() { }
void IBar.Bar() { }
}", index: SingleMember);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSameInterface()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
void IGoo.[||]Goo1() { }
void IGoo.Goo2() { }
void IBar.Bar() { }
}",
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
public void Goo1() { }
public void Goo2() { }
void IBar.Bar() { }
}", index: SameInterface);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAllInterfaces()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
void IGoo.[||]Goo1() { }
void IGoo.Goo2() { }
void IBar.Bar() { }
}",
@"
interface IGoo { void Goo1(); void Goo2(); }
interface IBar { void Bar(); }
class C : IGoo, IBar
{
public void Goo1() { }
public void Goo2() { }
public void Bar() { }
}", index: AllInterfaces);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestProperty()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { int Goo1 { get; } }
class C : IGoo
{
int IGoo.[||]Goo1 { get { } }
}",
@"
interface IGoo { int Goo1 { get; } }
class C : IGoo
{
public int Goo1 { get { } }
}", index: SingleMember);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEvent()
{
await TestInRegularAndScriptAsync(
@"
interface IGoo { event Action E; }
class C : IGoo
{
event Action IGoo.[||]E { add { } remove { } }
}",
@"
interface IGoo { event Action E; }
class C : IGoo
{
public event Action E { add { } remove { } }
}", index: SingleMember);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNotOnImplicitMember()
{
await TestMissingAsync(
@"
interface IGoo { void Goo1(); }
class C : IGoo
{
public void [||]Goo1() { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNotOnUnboundExplicitImpl()
{
await TestMissingAsync(
@"
class C : IGoo
{
void IGoo.[||]Goo1() { }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCollision()
{
// Currently we don't do anything special here. But we just test here to make sure we
// don't blow up here.
await TestInRegularAndScriptAsync(
@"
interface IGoo { void Goo1(); }
class C : IGoo
{
void IGoo.[||]Goo1() { }
private void Goo1() { }
}",
@"
interface IGoo { void Goo1(); }
class C : IGoo
{
public void Goo1() { }
private void Goo1() { }
}", index: SingleMember);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
[WorkItem(48027, "https://github.com/dotnet/roslyn/issues/48027")]
public async Task TestSingleMemberAndContainingTypeHasNoInterface()
{
await TestMissingAsync(
@"
using System;
using System.Collections;
class C
{
IEnumerator IEnumerable.[||]GetEnumerator()
{
throw new NotImplementedException();
}
}");
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.cs.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="cs" original="../VBCodeStyleFixesResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Odebrat tuto hodnotu, když se přidá jiná</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="cs" original="../VBCodeStyleFixesResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Odebrat tuto hodnotu, když se přidá jiná</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/Binder/Binder_Conversions.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.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
internal BoundExpression CreateConversion(
BoundExpression source,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var conversion = Conversions.ClassifyConversionFromExpression(source, destination, ref useSiteInfo);
diagnostics.Add(source.Syntax, useSiteInfo);
return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics);
}
internal BoundExpression CreateConversion(
BoundExpression source,
Conversion conversion,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics);
}
internal BoundExpression CreateConversion(
SyntaxNode syntax,
BoundExpression source,
Conversion conversion,
bool isCast,
ConversionGroup? conversionGroupOpt,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
return CreateConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, source.WasCompilerGenerated, destination, diagnostics);
}
protected BoundExpression CreateConversion(
SyntaxNode syntax,
BoundExpression source,
Conversion conversion,
bool isCast,
ConversionGroup? conversionGroupOpt,
bool wasCompilerGenerated,
TypeSymbol destination,
BindingDiagnosticBag diagnostics,
bool hasErrors = false)
{
RoslynDebug.Assert(source != null);
RoslynDebug.Assert((object)destination != null);
RoslynDebug.Assert(!isCast || conversionGroupOpt != null);
if (conversion.IsIdentity)
{
if (source is BoundTupleLiteral sourceTuple)
{
NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(destination, sourceTuple, diagnostics);
}
// identity tuple and switch conversions result in a converted expression
// to indicate that such conversions are no longer applicable.
source = BindToNaturalType(source, diagnostics);
RoslynDebug.Assert(source.Type is object);
// We need to preserve any conversion that changes the type (even identity conversions, like object->dynamic),
// or that was explicitly written in code (so that GetSemanticInfo can find the syntax in the bound tree).
if (!isCast && source.Type.Equals(destination, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
return source;
}
}
if (conversion.IsMethodGroup)
{
return CreateMethodGroupConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics);
}
// Obsolete diagnostics for method group are reported as part of creating the method group conversion.
ReportDiagnosticsIfObsolete(diagnostics, conversion, syntax, hasBaseReceiver: false);
CheckConstraintLanguageVersionAndRuntimeSupportForConversion(syntax, conversion, diagnostics);
if (conversion.IsAnonymousFunction && source.Kind == BoundKind.UnboundLambda)
{
return CreateAnonymousFunctionConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics);
}
if (conversion.IsStackAlloc)
{
return CreateStackAllocConversion(syntax, source, conversion, isCast, conversionGroupOpt, destination, diagnostics);
}
if (conversion.IsTupleLiteralConversion ||
(conversion.IsNullable && conversion.UnderlyingConversions[0].IsTupleLiteralConversion))
{
return CreateTupleLiteralConversion(syntax, (BoundTupleLiteral)source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics);
}
if (conversion.Kind == ConversionKind.SwitchExpression)
{
var convertedSwitch = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, destination, conversionIfTargetTyped: conversion, diagnostics);
return new BoundConversion(
syntax,
convertedSwitch,
conversion,
CheckOverflowAtRuntime,
explicitCastInCode: isCast && !wasCompilerGenerated,
conversionGroupOpt,
convertedSwitch.ConstantValue,
destination,
hasErrors);
}
if (conversion.Kind == ConversionKind.ConditionalExpression)
{
var convertedConditional = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, destination, conversionIfTargetTyped: conversion, diagnostics);
return new BoundConversion(
syntax,
convertedConditional,
conversion,
CheckOverflowAtRuntime,
explicitCastInCode: isCast && !wasCompilerGenerated,
conversionGroupOpt,
convertedConditional.ConstantValue,
destination,
hasErrors);
}
if (conversion.Kind == ConversionKind.InterpolatedString)
{
var unconvertedSource = (BoundUnconvertedInterpolatedString)source;
source = new BoundInterpolatedString(
unconvertedSource.Syntax,
interpolationData: null,
BindInterpolatedStringParts(unconvertedSource, diagnostics),
unconvertedSource.ConstantValue,
unconvertedSource.Type,
unconvertedSource.HasErrors);
}
if (conversion.Kind == ConversionKind.InterpolatedStringHandler)
{
return new BoundConversion(
syntax,
BindUnconvertedInterpolatedExpressionToHandlerType(source, (NamedTypeSymbol)destination, diagnostics),
conversion,
@checked: CheckOverflowAtRuntime,
explicitCastInCode: isCast && !wasCompilerGenerated,
conversionGroupOpt,
constantValueOpt: null,
destination);
}
if (source.Kind == BoundKind.UnconvertedSwitchExpression)
{
TypeSymbol? type = source.Type;
if (type is null)
{
Debug.Assert(!conversion.Exists);
type = CreateErrorType();
hasErrors = true;
}
source = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors);
if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated)
{
return source;
}
}
if (conversion.IsObjectCreation)
{
return ConvertObjectCreationExpression(syntax, (BoundUnconvertedObjectCreationExpression)source, isCast, destination, diagnostics);
}
if (source.Kind == BoundKind.UnconvertedConditionalOperator)
{
TypeSymbol? type = source.Type;
if (type is null)
{
Debug.Assert(!conversion.Exists);
type = CreateErrorType();
hasErrors = true;
}
source = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors);
if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated)
{
return source;
}
}
if (conversion.IsUserDefined)
{
// User-defined conversions are likely to be represented as multiple
// BoundConversion instances so a ConversionGroup is necessary.
return CreateUserDefinedConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt ?? new ConversionGroup(conversion), destination, diagnostics, hasErrors);
}
ConstantValue? constantValue = this.FoldConstantConversion(syntax, source, conversion, destination, diagnostics);
if (conversion.Kind == ConversionKind.DefaultLiteral)
{
source = new BoundDefaultExpression(source.Syntax, targetType: null, constantValue, type: destination)
.WithSuppression(source.IsSuppressed);
}
return new BoundConversion(
syntax,
BindToNaturalType(source, diagnostics),
conversion,
@checked: CheckOverflowAtRuntime,
explicitCastInCode: isCast && !wasCompilerGenerated,
conversionGroupOpt,
constantValueOpt: constantValue,
type: destination,
hasErrors: hasErrors)
{ WasCompilerGenerated = wasCompilerGenerated };
}
internal void CheckConstraintLanguageVersionAndRuntimeSupportForConversion(SyntaxNodeOrToken syntax, Conversion conversion, BindingDiagnosticBag diagnostics)
{
if (conversion.IsUserDefined && conversion.Method is MethodSymbol method && method.IsStatic && method.IsAbstract)
{
Debug.Assert(conversion.ConstrainedToTypeOpt is TypeParameterSymbol);
if (Compilation.SourceModule != method.ContainingModule)
{
Debug.Assert(syntax.SyntaxTree is object);
CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics, syntax.GetLocation()!);
if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces)
{
Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, syntax);
}
}
}
}
private BoundExpression ConvertObjectCreationExpression(SyntaxNode syntax, BoundUnconvertedObjectCreationExpression node, bool isCast, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt);
BoundExpression expr = BindObjectCreationExpression(node, destination.StrippedType(), arguments, diagnostics);
if (destination.IsNullableType())
{
// We manually create an ImplicitNullable conversion
// if the destination is nullable, in which case we
// target the underlying type e.g. `S? x = new();`
// is actually identical to `S? x = new S();`.
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var conversion = Conversions.ClassifyStandardConversion(null, expr.Type, destination, ref useSiteInfo);
expr = new BoundConversion(
node.Syntax,
operand: expr,
conversion: conversion,
@checked: false,
explicitCastInCode: isCast,
conversionGroupOpt: new ConversionGroup(conversion),
constantValueOpt: expr.ConstantValue,
type: destination);
diagnostics.Add(syntax, useSiteInfo);
}
arguments.Free();
return expr;
}
private BoundExpression BindObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, TypeSymbol type, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics)
{
var syntax = node.Syntax;
switch (type.TypeKind)
{
case TypeKind.Enum:
case TypeKind.Struct:
case TypeKind.Class when !type.IsAnonymousType: // We don't want to enable object creation with unspeakable types
return BindClassCreationExpression(syntax, type.Name, typeNode: syntax, (NamedTypeSymbol)type, arguments, diagnostics, node.InitializerOpt, wasTargetTyped: true);
case TypeKind.TypeParameter:
return BindTypeParameterCreationExpression(syntax, (TypeParameterSymbol)type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics);
case TypeKind.Delegate:
return BindDelegateCreationExpression(syntax, (NamedTypeSymbol)type, arguments, node.InitializerOpt, diagnostics);
case TypeKind.Interface:
return BindInterfaceCreationExpression(syntax, (NamedTypeSymbol)type, diagnostics, typeNode: syntax, arguments, node.InitializerOpt, wasTargetTyped: true);
case TypeKind.Array:
case TypeKind.Class:
case TypeKind.Dynamic:
Error(diagnostics, ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, syntax, type);
goto case TypeKind.Error;
case TypeKind.Pointer:
case TypeKind.FunctionPointer:
Error(diagnostics, ErrorCode.ERR_UnsafeTypeInObjectCreation, syntax, type);
goto case TypeKind.Error;
case TypeKind.Error:
return MakeBadExpressionForObjectCreation(syntax, type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics);
case var v:
throw ExceptionUtilities.UnexpectedValue(v);
}
}
/// <summary>
/// Rewrite the subexpressions in a conditional expression to convert the whole thing to the destination type.
/// </summary>
private BoundExpression ConvertConditionalExpression(
BoundUnconvertedConditionalOperator source,
TypeSymbol destination,
Conversion? conversionIfTargetTyped,
BindingDiagnosticBag diagnostics,
bool hasErrors = false)
{
bool targetTyped = conversionIfTargetTyped is { };
Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything));
ImmutableArray<Conversion> underlyingConversions = conversionIfTargetTyped.GetValueOrDefault().UnderlyingConversions;
var condition = source.Condition;
hasErrors |= source.HasErrors || destination.IsErrorType();
var trueExpr =
targetTyped
? CreateConversion(source.Consequence.Syntax, source.Consequence, underlyingConversions[0], isCast: false, conversionGroupOpt: null, destination, diagnostics)
: GenerateConversionForAssignment(destination, source.Consequence, diagnostics);
var falseExpr =
targetTyped
? CreateConversion(source.Alternative.Syntax, source.Alternative, underlyingConversions[1], isCast: false, conversionGroupOpt: null, destination, diagnostics)
: GenerateConversionForAssignment(destination, source.Alternative, diagnostics);
var constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr);
hasErrors |= constantValue?.IsBad == true;
if (targetTyped && !destination.IsErrorType() && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureTargetTypedConditional))
{
diagnostics.Add(
ErrorCode.ERR_NoImplicitConvTargetTypedConditional,
source.Syntax.Location,
Compilation.LanguageVersion.ToDisplayString(),
source.Consequence.Display,
source.Alternative.Display,
new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()));
}
return new BoundConditionalOperator(source.Syntax, isRef: false, condition, trueExpr, falseExpr, constantValue, source.Type, wasTargetTyped: targetTyped, destination, hasErrors)
.WithSuppression(source.IsSuppressed);
}
/// <summary>
/// Rewrite the expressions in the switch expression arms to add a conversion to the destination type.
/// </summary>
private BoundExpression ConvertSwitchExpression(BoundUnconvertedSwitchExpression source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false)
{
bool targetTyped = conversionIfTargetTyped is { };
Conversion conversion = conversionIfTargetTyped ?? Conversion.Identity;
Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything));
ImmutableArray<Conversion> underlyingConversions = conversion.UnderlyingConversions;
var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(source.SwitchArms.Length);
for (int i = 0, n = source.SwitchArms.Length; i < n; i++)
{
var oldCase = source.SwitchArms[i];
Debug.Assert(oldCase.Syntax is SwitchExpressionArmSyntax);
var binder = GetRequiredBinder(oldCase.Syntax);
var oldValue = oldCase.Value;
var newValue =
targetTyped
? binder.CreateConversion(oldValue.Syntax, oldValue, underlyingConversions[i], isCast: false, conversionGroupOpt: null, destination, diagnostics)
: binder.GenerateConversionForAssignment(destination, oldValue, diagnostics);
var newCase = (oldValue == newValue) ? oldCase :
new BoundSwitchExpressionArm(oldCase.Syntax, oldCase.Locals, oldCase.Pattern, oldCase.WhenClause, newValue, oldCase.Label, oldCase.HasErrors);
builder.Add(newCase);
}
var newSwitchArms = builder.ToImmutableAndFree();
return new BoundConvertedSwitchExpression(
source.Syntax, source.Type, targetTyped, conversion, source.Expression, newSwitchArms, source.DecisionDag,
source.DefaultLabel, source.ReportedNotExhaustive, destination, hasErrors || source.HasErrors);
}
private BoundExpression CreateUserDefinedConversion(
SyntaxNode syntax,
BoundExpression source,
Conversion conversion,
bool isCast,
ConversionGroup conversionGroup,
TypeSymbol destination,
BindingDiagnosticBag diagnostics,
bool hasErrors)
{
Debug.Assert(conversionGroup != null);
Debug.Assert(conversion.IsUserDefined);
if (!conversion.IsValid)
{
if (!hasErrors)
GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination);
return new BoundConversion(
syntax,
source,
conversion,
CheckOverflowAtRuntime,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: destination,
hasErrors: true)
{ WasCompilerGenerated = source.WasCompilerGenerated };
}
// Due to an oddity in the way we create a non-lifted user-defined conversion from A to D?
// (required backwards compatibility with the native compiler) we can end up in a situation
// where we have:
// a standard conversion from A to B?
// then a standard conversion from B? to B
// then a user-defined conversion from B to C
// then a standard conversion from C to C?
// then a standard conversion from C? to D?
//
// In that scenario, the "from type" of the conversion will be B? and the "from conversion" will be
// from A to B?. Similarly the "to type" of the conversion will be C? and the "to conversion"
// of the conversion will be from C? to D?.
//
// Therefore, we might need to introduce an extra conversion on the source side, from B? to B.
// Now, you might think we should also introduce an extra conversion on the destination side,
// from C to C?. But that then gives us the following bad situation: If we in fact bind this as
//
// (D?)(C?)(C)(B)(B?)(A)x
//
// then what we are in effect doing is saying "convert C? to D? by checking for null, unwrapping,
// converting C to D, and then wrapping". But we know that the C? will never be null. In this case
// we should actually generate
//
// (D?)(C)(B)(B?)(A)x
//
// And thereby skip the unnecessary nullable conversion.
Debug.Assert(conversion.BestUserDefinedConversionAnalysis is object); // All valid user-defined conversions have this populated
// Original expression --> conversion's "from" type
BoundExpression convertedOperand = CreateConversion(
syntax: source.Syntax,
source: source,
conversion: conversion.UserDefinedFromConversion,
isCast: false,
conversionGroupOpt: conversionGroup,
wasCompilerGenerated: false,
destination: conversion.BestUserDefinedConversionAnalysis.FromType,
diagnostics: diagnostics);
TypeSymbol conversionParameterType = conversion.BestUserDefinedConversionAnalysis.Operator.GetParameterType(0);
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm &&
!TypeSymbol.Equals(conversion.BestUserDefinedConversionAnalysis.FromType, conversionParameterType, TypeCompareKind.ConsiderEverything2))
{
// Conversion's "from" type --> conversion method's parameter type.
convertedOperand = CreateConversion(
syntax: syntax,
source: convertedOperand,
conversion: Conversions.ClassifyStandardConversion(null, convertedOperand.Type, conversionParameterType, ref useSiteInfo),
isCast: false,
conversionGroupOpt: conversionGroup,
wasCompilerGenerated: true,
destination: conversionParameterType,
diagnostics: diagnostics);
}
BoundExpression userDefinedConversion;
TypeSymbol conversionReturnType = conversion.BestUserDefinedConversionAnalysis.Operator.ReturnType;
TypeSymbol conversionToType = conversion.BestUserDefinedConversionAnalysis.ToType;
Conversion toConversion = conversion.UserDefinedToConversion;
if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm &&
!TypeSymbol.Equals(conversionToType, conversionReturnType, TypeCompareKind.ConsiderEverything2))
{
// Conversion method's parameter type --> conversion method's return type
// NB: not calling CreateConversion here because this is the recursive base case.
userDefinedConversion = new BoundConversion(
syntax,
convertedOperand,
conversion,
@checked: false, // There are no checked user-defined conversions, but the conversions on either side might be checked.
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: conversionReturnType)
{ WasCompilerGenerated = true };
if (conversionToType.IsNullableType() && TypeSymbol.Equals(conversionToType.GetNullableUnderlyingType(), conversionReturnType, TypeCompareKind.ConsiderEverything2))
{
// Skip introducing the conversion from C to C?. The "to" conversion is now wrong though,
// because it will still assume converting C? to D?.
toConversion = Conversions.ClassifyConversionFromType(conversionReturnType, destination, ref useSiteInfo);
Debug.Assert(toConversion.Exists);
}
else
{
// Conversion method's return type --> conversion's "to" type
userDefinedConversion = CreateConversion(
syntax: syntax,
source: userDefinedConversion,
conversion: Conversions.ClassifyStandardConversion(null, conversionReturnType, conversionToType, ref useSiteInfo),
isCast: false,
conversionGroupOpt: conversionGroup,
wasCompilerGenerated: true,
destination: conversionToType,
diagnostics: diagnostics);
}
}
else
{
// Conversion method's parameter type --> conversion method's "to" type
// NB: not calling CreateConversion here because this is the recursive base case.
userDefinedConversion = new BoundConversion(
syntax,
convertedOperand,
conversion,
@checked: false,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: conversionToType)
{ WasCompilerGenerated = true };
}
diagnostics.Add(syntax, useSiteInfo);
// Conversion's "to" type --> final type
BoundExpression finalConversion = CreateConversion(
syntax: syntax,
source: userDefinedConversion,
conversion: toConversion,
isCast: false,
conversionGroupOpt: conversionGroup,
wasCompilerGenerated: true, // NOTE: doesn't necessarily set flag on resulting bound expression.
destination: destination,
diagnostics: diagnostics);
finalConversion.ResetCompilerGenerated(source.WasCompilerGenerated);
return finalConversion;
}
private BoundExpression CreateAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
// We have a successful anonymous function conversion; rather than producing a node
// which is a conversion on top of an unbound lambda, replace it with the bound
// lambda.
// UNDONE: Figure out what to do about the error case, where a lambda
// UNDONE: is converted to a delegate that does not match. What to surface then?
var unboundLambda = (UnboundLambda)source;
if ((destination.SpecialType == SpecialType.System_Delegate || destination.IsNonGenericExpressionType()) &&
syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType))
{
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var delegateType = unboundLambda.InferDelegateType(ref useSiteInfo);
BoundLambda boundLambda;
if (delegateType is { })
{
bool isExpressionTree = destination.IsNonGenericExpressionType();
if (isExpressionTree)
{
delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType);
delegateType.AddUseSiteInfo(ref useSiteInfo);
}
boundLambda = unboundLambda.Bind(delegateType, isExpressionTree);
}
else
{
diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation());
delegateType = CreateErrorType();
boundLambda = unboundLambda.BindForErrorRecovery();
}
diagnostics.AddRange(boundLambda.Diagnostics);
var expr = createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, delegateType);
conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo);
diagnostics.Add(syntax, useSiteInfo);
return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics);
}
else
{
#if DEBUG
// Test inferring a delegate type for all callers.
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
_ = unboundLambda.InferDelegateType(ref discardedUseSiteInfo);
#endif
var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination, isExpressionTree: destination.IsGenericOrNonGenericExpressionType(out _));
diagnostics.AddRange(boundLambda.Diagnostics);
return createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, destination);
}
static BoundConversion createAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, BoundLambda boundLambda, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination)
{
return new BoundConversion(
syntax,
boundLambda,
conversion,
@checked: false,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: destination)
{ WasCompilerGenerated = source.WasCompilerGenerated };
}
}
private BoundExpression CreateMethodGroupConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
var (originalGroup, isAddressOf) = source switch
{
BoundMethodGroup m => (m, false),
BoundUnconvertedAddressOfOperator { Operand: { } m } => (m, true),
_ => throw ExceptionUtilities.UnexpectedValue(source),
};
BoundMethodGroup group = FixMethodGroupWithTypeOrValue(originalGroup, conversion, diagnostics);
bool hasErrors = false;
if (MethodGroupConversionHasErrors(syntax, conversion, group.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf, destination, diagnostics))
{
hasErrors = true;
}
if (destination.SpecialType == SpecialType.System_Delegate &&
syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType))
{
// https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion.
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var delegateType = GetMethodGroupDelegateType(group, ref useSiteInfo);
var expr = createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, delegateType!, hasErrors);
conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo);
diagnostics.Add(syntax, useSiteInfo);
return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics);
}
#if DEBUG
// Test inferring a delegate type for all callers.
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
_ = GetMethodGroupDelegateType(group, ref discardedUseSiteInfo);
#endif
return createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, destination, hasErrors);
static BoundConversion createMethodGroupConversion(SyntaxNode syntax, BoundMethodGroup group, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, bool hasErrors)
{
return new BoundConversion(syntax, group, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = group.WasCompilerGenerated };
}
}
private BoundExpression CreateStackAllocConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
Debug.Assert(conversion.IsStackAlloc);
var boundStackAlloc = (BoundStackAllocArrayCreation)source;
var elementType = boundStackAlloc.ElementType;
TypeSymbol stackAllocType;
switch (conversion.Kind)
{
case ConversionKind.StackAllocToPointerType:
ReportUnsafeIfNotAllowed(syntax.Location, diagnostics);
stackAllocType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType));
break;
case ConversionKind.StackAllocToSpanType:
CheckFeatureAvailability(syntax, MessageID.IDS_FeatureRefStructs, diagnostics);
stackAllocType = Compilation.GetWellKnownType(WellKnownType.System_Span_T).Construct(elementType);
break;
default:
throw ExceptionUtilities.UnexpectedValue(conversion.Kind);
}
var convertedNode = new BoundConvertedStackAllocExpression(syntax, elementType, boundStackAlloc.Count, boundStackAlloc.InitializerOpt, stackAllocType, boundStackAlloc.HasErrors);
var underlyingConversion = conversion.UnderlyingConversions.Single();
return CreateConversion(syntax, convertedNode, underlyingConversion, isCast: isCast, conversionGroup, destination, diagnostics);
}
private BoundExpression CreateTupleLiteralConversion(SyntaxNode syntax, BoundTupleLiteral sourceTuple, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
// We have a successful tuple conversion; rather than producing a separate conversion node
// which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments.
Debug.Assert(conversion.IsNullable == destination.IsNullableType());
var destinationWithoutNullable = destination;
var conversionWithoutNullable = conversion;
if (conversion.IsNullable)
{
destinationWithoutNullable = destination.GetNullableUnderlyingType();
conversionWithoutNullable = conversion.UnderlyingConversions[0];
}
Debug.Assert(conversionWithoutNullable.IsTupleLiteralConversion);
NamedTypeSymbol targetType = (NamedTypeSymbol)destinationWithoutNullable;
if (targetType.IsTupleType)
{
NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(targetType, sourceTuple, diagnostics);
// do not lose the original element names and locations in the literal if different from names in the target
//
// the tuple has changed the type of elements due to target-typing,
// but element names has not changed and locations of their declarations
// should not be confused with element locations on the target type.
if (sourceTuple.Type is NamedTypeSymbol { IsTupleType: true } sourceType)
{
targetType = targetType.WithTupleDataFrom(sourceType);
}
else
{
var tupleSyntax = (TupleExpressionSyntax)sourceTuple.Syntax;
var locationBuilder = ArrayBuilder<Location?>.GetInstance();
foreach (var argument in tupleSyntax.Arguments)
{
locationBuilder.Add(argument.NameColon?.Name.Location);
}
targetType = targetType.WithElementNames(sourceTuple.ArgumentNamesOpt!,
locationBuilder.ToImmutableAndFree(),
errorPositions: default,
ImmutableArray.Create(tupleSyntax.Location));
}
}
var arguments = sourceTuple.Arguments;
var convertedArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Length);
var targetElementTypes = targetType.TupleElementTypesWithAnnotations;
Debug.Assert(targetElementTypes.Length == arguments.Length, "converting a tuple literal to incompatible type?");
var underlyingConversions = conversionWithoutNullable.UnderlyingConversions;
for (int i = 0; i < arguments.Length; i++)
{
var argument = arguments[i];
var destType = targetElementTypes[i];
var elementConversion = underlyingConversions[i];
var elementConversionGroup = isCast ? new ConversionGroup(elementConversion, destType) : null;
convertedArguments.Add(CreateConversion(argument.Syntax, argument, elementConversion, isCast: isCast, elementConversionGroup, destType.Type, diagnostics));
}
BoundExpression result = new BoundConvertedTupleLiteral(
sourceTuple.Syntax,
sourceTuple,
wasTargetTyped: true,
convertedArguments.ToImmutableAndFree(),
sourceTuple.ArgumentNamesOpt,
sourceTuple.InferredNamesOpt,
targetType).WithSuppression(sourceTuple.IsSuppressed);
if (!TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything2))
{
// literal cast is applied to the literal
result = new BoundConversion(
sourceTuple.Syntax,
result,
conversion,
@checked: false,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: destination);
}
// If we had a cast in the code, keep conversion in the tree.
// even though the literal is already converted to the target type.
if (isCast)
{
result = new BoundConversion(
syntax,
result,
Conversion.Identity,
@checked: false,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: destination);
}
return result;
}
private static bool IsMethodGroupWithTypeOrValueReceiver(BoundNode node)
{
if (node.Kind != BoundKind.MethodGroup)
{
return false;
}
return Binder.IsTypeOrValueExpression(((BoundMethodGroup)node).ReceiverOpt);
}
private BoundMethodGroup FixMethodGroupWithTypeOrValue(BoundMethodGroup group, Conversion conversion, BindingDiagnosticBag diagnostics)
{
if (!IsMethodGroupWithTypeOrValueReceiver(group))
{
return group;
}
BoundExpression? receiverOpt = group.ReceiverOpt;
RoslynDebug.Assert(receiverOpt != null);
receiverOpt = ReplaceTypeOrValueReceiver(receiverOpt, useType: conversion.Method?.RequiresInstanceReceiver == false && !conversion.IsExtensionMethod, diagnostics);
return group.Update(
group.TypeArgumentsOpt,
group.Name,
group.Methods,
group.LookupSymbolOpt,
group.LookupError,
group.Flags,
receiverOpt, //only change
group.ResultKind);
}
/// <summary>
/// This method implements the algorithm in spec section 7.6.5.1.
///
/// For method group conversions, there are situations in which the conversion is
/// considered to exist ("Otherwise the algorithm produces a single best method M having
/// the same number of parameters as D and the conversion is considered to exist"), but
/// application of the conversion fails. These are the "final validation" steps of
/// overload resolution.
/// </summary>
/// <returns>
/// True if there is any error, except lack of runtime support errors.
/// </returns>
private bool MemberGroupFinalValidation(BoundExpression? receiverOpt, MethodSymbol methodSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod)
{
if (!IsBadBaseAccess(node, receiverOpt, methodSymbol, diagnostics))
{
CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, methodSymbol, diagnostics);
}
if (MemberGroupFinalValidationAccessibilityChecks(receiverOpt, methodSymbol, node, diagnostics, invokedAsExtensionMethod))
{
return true;
}
// SPEC: If the best method is a generic method, the type arguments (supplied or inferred) are checked against the constraints
// SPEC: declared on the generic method. If any type argument does not satisfy the corresponding constraint(s) on
// SPEC: the type parameter, a binding-time error occurs.
// The portion of the overload resolution spec quoted above is subtle and somewhat
// controversial. The upshot of this is that overload resolution does not consider
// constraints to be a part of the signature. Overload resolution matches arguments to
// parameter lists; it does not consider things which are outside of the parameter list.
// If the best match from the arguments to the formal parameters is not viable then we
// give an error rather than falling back to a worse match.
//
// Consider the following:
//
// void M<T>(T t) where T : Reptile {}
// void M(object x) {}
// ...
// M(new Giraffe());
//
// The correct analysis is to determine that the applicable candidates are
// M<Giraffe>(Giraffe) and M(object). Overload resolution then chooses the former
// because it is an exact match, over the latter which is an inexact match. Only after
// the best method is determined do we check the constraints and discover that the
// constraint on T has been violated.
//
// Note that this is different from the rule that says that during type inference, if an
// inference violates a constraint then inference fails. For example:
//
// class C<T> where T : struct {}
// ...
// void M<U>(U u, C<U> c){}
// void M(object x, object y) {}
// ...
// M("hello", null);
//
// Type inference determines that U is string, but since C<string> is not a valid type
// because of the constraint, type inference fails. M<string> is never added to the
// applicable candidate set, so the applicable candidate set consists solely of
// M(object, object) and is therefore the best match.
return !methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, node.Location, diagnostics));
}
/// <summary>
/// Performs the following checks:
///
/// Spec 7.6.5: Invocation expressions (definition of Final Validation)
/// The method is validated in the context of the method group: If the best method is a static method,
/// the method group must have resulted from a simple-name or a member-access through a type. If the best
/// method is an instance method, the method group must have resulted from a simple-name, a member-access
/// through a variable or value, or a base-access. If neither of these requirements is true, a binding-time
/// error occurs.
/// (Note that the spec omits to mention, in the case of an instance method invoked through a simple name, that
/// the invocation must appear within the body of an instance method)
///
/// Spec 7.5.4: Compile-time checking of dynamic overload resolution
/// If F is a static method, the method group must have resulted from a simple-name, a member-access through a type,
/// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
/// If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value,
/// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
/// </summary>
/// <returns>
/// True if there is any error.
/// </returns>
private bool MemberGroupFinalValidationAccessibilityChecks(BoundExpression? receiverOpt, Symbol memberSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod)
{
// Perform final validation of the method to be invoked.
Debug.Assert(memberSymbol.Kind != SymbolKind.Method ||
memberSymbol.CanBeReferencedByName);
//note that the same assert does not hold for all properties. Some properties and (all indexers) are not referenceable by name, yet
//their binding brings them through here, perhaps needlessly.
if (IsTypeOrValueExpression(receiverOpt))
{
// TypeOrValue expression isn't replaced only if the invocation is late bound, in which case it can't be extension method.
// None of the checks below apply if the receiver can't be classified as a type or value.
Debug.Assert(!invokedAsExtensionMethod);
}
else if (!memberSymbol.RequiresInstanceReceiver())
{
Debug.Assert(!invokedAsExtensionMethod || (receiverOpt != null));
if (invokedAsExtensionMethod)
{
if (IsMemberAccessedThroughType(receiverOpt))
{
if (receiverOpt.Kind == BoundKind.QueryClause)
{
RoslynDebug.Assert(receiverOpt.Type is object);
// Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found.
diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, receiverOpt.Type, memberSymbol.Name);
}
else
{
// An object reference is required for the non-static field, method, or property '{0}'
diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol);
}
return true;
}
}
else if (!WasImplicitReceiver(receiverOpt) && IsMemberAccessedThroughVariableOrValue(receiverOpt))
{
if (this.Flags.Includes(BinderFlags.CollectionInitializerAddMethod))
{
diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, node.Location, memberSymbol);
}
else if (node.Kind() == SyntaxKind.AwaitExpression && memberSymbol.Name == WellKnownMemberNames.GetAwaiter)
{
RoslynDebug.Assert(receiverOpt.Type is object);
diagnostics.Add(ErrorCode.ERR_BadAwaitArg, node.Location, receiverOpt.Type);
}
else
{
diagnostics.Add(ErrorCode.ERR_ObjectProhibited, node.Location, memberSymbol);
}
return true;
}
}
else if (IsMemberAccessedThroughType(receiverOpt))
{
diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol);
return true;
}
else if (WasImplicitReceiver(receiverOpt))
{
if (InFieldInitializer && !ContainingType!.IsScriptClass || InConstructorInitializer || InAttributeArgument)
{
SyntaxNode errorNode = node;
if (node.Parent != null && node.Parent.Kind() == SyntaxKind.InvocationExpression)
{
errorNode = node.Parent;
}
ErrorCode code = InFieldInitializer ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired;
diagnostics.Add(code, errorNode.Location, memberSymbol);
return true;
}
// If we could access the member through implicit "this" the receiver would be a BoundThisReference.
// If it is null it means that the instance member is inaccessible.
if (receiverOpt == null || ContainingMember().IsStatic)
{
Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, memberSymbol);
return true;
}
}
var containingType = this.ContainingType;
if (containingType is object)
{
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
bool isAccessible = this.IsSymbolAccessibleConditional(memberSymbol.GetTypeOrReturnType().Type, containingType, ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
if (!isAccessible)
{
// In the presence of non-transitive [InternalsVisibleTo] in source, or obnoxious symbols from metadata, it is possible
// to select a method through overload resolution in which the type is not accessible. In this case a method cannot
// be called through normal IL, so we give an error. Neither [InternalsVisibleTo] nor the need for this diagnostic is
// described by the language specification.
//
// Dev11 perform different access checks. See bug #530360 and tests AccessCheckTests.InaccessibleReturnType.
Error(diagnostics, ErrorCode.ERR_BadAccess, node, memberSymbol);
return true;
}
}
return false;
}
private static bool IsMemberAccessedThroughVariableOrValue(BoundExpression? receiverOpt)
{
if (receiverOpt == null)
{
return false;
}
return !IsMemberAccessedThroughType(receiverOpt);
}
internal static bool IsMemberAccessedThroughType([NotNullWhen(true)] BoundExpression? receiverOpt)
{
if (receiverOpt == null)
{
return false;
}
while (receiverOpt.Kind == BoundKind.QueryClause)
{
receiverOpt = ((BoundQueryClause)receiverOpt).Value;
}
return receiverOpt.Kind == BoundKind.TypeExpression;
}
/// <summary>
/// Was the receiver expression compiler-generated?
/// </summary>
internal static bool WasImplicitReceiver([NotNullWhen(false)] BoundExpression? receiverOpt)
{
if (receiverOpt == null) return true;
if (!receiverOpt.WasCompilerGenerated) return false;
switch (receiverOpt.Kind)
{
case BoundKind.ThisReference:
case BoundKind.HostObjectMemberReference:
case BoundKind.PreviousSubmissionReference:
return true;
default:
return false;
}
}
/// <summary>
/// This method implements the checks in spec section 15.2.
/// </summary>
internal bool MethodIsCompatibleWithDelegateOrFunctionPointer(BoundExpression? receiverOpt, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, Location errorLocation, BindingDiagnosticBag diagnostics)
{
Debug.Assert(delegateType is NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { HasUseSiteError: false } }
|| delegateType.TypeKind == TypeKind.FunctionPointer,
"This method should only be called for valid delegate or function pointer types.");
MethodSymbol delegateOrFuncPtrMethod = delegateType switch
{
NamedTypeSymbol { DelegateInvokeMethod: { } invokeMethod } => invokeMethod,
FunctionPointerTypeSymbol { Signature: { } signature } => signature,
_ => throw ExceptionUtilities.UnexpectedValue(delegateType),
};
Debug.Assert(!isExtensionMethod || (receiverOpt != null));
// - Argument types "match", and
var delegateOrFuncPtrParameters = delegateOrFuncPtrMethod.Parameters;
var methodParameters = method.Parameters;
int numParams = delegateOrFuncPtrParameters.Length;
if (methodParameters.Length != numParams + (isExtensionMethod ? 1 : 0))
{
// This can happen if "method" has optional parameters.
Debug.Assert(methodParameters.Length > numParams + (isExtensionMethod ? 1 : 0));
Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType);
return false;
}
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
// If this is an extension method delegate, the caller should have verified the
// receiver is compatible with the "this" parameter of the extension method.
Debug.Assert(!isExtensionMethod ||
(Conversions.ConvertExtensionMethodThisArg(methodParameters[0].Type, receiverOpt!.Type, ref useSiteInfo).Exists && useSiteInfo.Diagnostics.IsNullOrEmpty()));
useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo);
for (int i = 0; i < numParams; i++)
{
var delegateParameter = delegateOrFuncPtrParameters[i];
var methodParameter = methodParameters[isExtensionMethod ? i + 1 : i];
// The delegate compatibility checks are stricter than the checks on applicable functions: it's possible
// to get here with a method that, while all the parameters are applicable, is not actually delegate
// compatible. This is because the Applicable function member spec requires that:
// * Every value parameter (non-ref or similar) from the delegate type has an implicit conversion to the corresponding
// target parameter
// * Every ref or similar parameter has an identity conversion to the corresponding target parameter
// However, the delegate compatibility requirements are stricter:
// * Every value parameter (non-ref or similar) from the delegate type has an implicit _reference_ conversion to the
// corresponding target parameter.
// * Every ref or similar parameter has an identity conversion to the corresponding target parameter
// Note the addition of the reference requirement: it means that for delegate type void D(int i), void M(long l) is
// _applicable_, but not _compatible_.
if (!hasConversion(delegateType.TypeKind, Conversions, delegateParameter.Type, methodParameter.Type, delegateParameter.RefKind, methodParameter.RefKind, ref useSiteInfo))
{
// No overload for '{0}' matches delegate '{1}'
Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
}
if (delegateOrFuncPtrMethod.RefKind != method.RefKind)
{
Error(diagnostics, getRefMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
var methodReturnType = method.ReturnType;
var delegateReturnType = delegateOrFuncPtrMethod.ReturnType;
bool returnsMatch = delegateOrFuncPtrMethod switch
{
{ RefKind: RefKind.None, ReturnsVoid: true } => method.ReturnsVoid,
{ RefKind: var destinationRefKind } => hasConversion(delegateType.TypeKind, Conversions, methodReturnType, delegateReturnType, method.RefKind, destinationRefKind, ref useSiteInfo),
};
if (!returnsMatch)
{
Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
if (delegateType.IsFunctionPointer())
{
if (isExtensionMethod)
{
Error(diagnostics, ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, errorLocation);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
if (!method.IsStatic)
{
// This check is here purely for completeness of implementing the spec. It should
// never be hit, as static methods should be eliminated as candidates in overload
// resolution and should never make it to this point.
Debug.Fail("This method should have been eliminated in overload resolution!");
Error(diagnostics, ErrorCode.ERR_FuncPtrMethMustBeStatic, errorLocation, method);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
}
diagnostics.Add(errorLocation, useSiteInfo);
return true;
static bool hasConversion(TypeKind targetKind, Conversions conversions, TypeSymbol source, TypeSymbol destination,
RefKind sourceRefKind, RefKind destinationRefKind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
if (sourceRefKind != destinationRefKind)
{
return false;
}
if (sourceRefKind != RefKind.None)
{
return ConversionsBase.HasIdentityConversion(source, destination);
}
if (conversions.HasIdentityOrImplicitReferenceConversion(source, destination, ref useSiteInfo))
{
return true;
}
return targetKind == TypeKind.FunctionPointer
&& (ConversionsBase.HasImplicitPointerToVoidConversion(source, destination)
|| conversions.HasImplicitPointerConversion(source, destination, ref useSiteInfo));
}
static ErrorCode getMethodMismatchErrorCode(TypeKind type)
=> type switch
{
TypeKind.Delegate => ErrorCode.ERR_MethDelegateMismatch,
TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch,
_ => throw ExceptionUtilities.UnexpectedValue(type)
};
static ErrorCode getRefMismatchErrorCode(TypeKind type)
=> type switch
{
TypeKind.Delegate => ErrorCode.ERR_DelegateRefMismatch,
TypeKind.FunctionPointer => ErrorCode.ERR_FuncPtrRefMismatch,
_ => throw ExceptionUtilities.UnexpectedValue(type)
};
}
/// <summary>
/// This method combines final validation (section 7.6.5.1) and delegate compatibility (section 15.2).
/// </summary>
/// <param name="syntax">CSharpSyntaxNode of the expression requiring method group conversion.</param>
/// <param name="conversion">Conversion to be performed.</param>
/// <param name="receiverOpt">Optional receiver.</param>
/// <param name="isExtensionMethod">Method invoked as extension method.</param>
/// <param name="delegateOrFuncPtrType">Target delegate type.</param>
/// <param name="diagnostics">Where diagnostics should be added.</param>
/// <returns>True if a diagnostic has been added.</returns>
private bool MethodGroupConversionHasErrors(
SyntaxNode syntax,
Conversion conversion,
BoundExpression? receiverOpt,
bool isExtensionMethod,
bool isAddressOf,
TypeSymbol delegateOrFuncPtrType,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(delegateOrFuncPtrType.SpecialType == SpecialType.System_Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer);
Debug.Assert(conversion.Method is object);
MethodSymbol selectedMethod = conversion.Method;
var location = syntax.Location;
if (delegateOrFuncPtrType.SpecialType != SpecialType.System_Delegate)
{
if (!MethodIsCompatibleWithDelegateOrFunctionPointer(receiverOpt, isExtensionMethod, selectedMethod, delegateOrFuncPtrType, location, diagnostics) ||
MemberGroupFinalValidation(receiverOpt, selectedMethod, syntax, diagnostics, isExtensionMethod))
{
return true;
}
}
if (selectedMethod.IsConditional)
{
// CS1618: Cannot create delegate with '{0}' because it has a Conditional attribute
Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, location, selectedMethod);
return true;
}
var sourceMethod = selectedMethod as SourceOrdinaryMethodSymbol;
if (sourceMethod is object && sourceMethod.IsPartialWithoutImplementation)
{
// CS0762: Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, location, selectedMethod);
return true;
}
if ((selectedMethod.HasUnsafeParameter() || selectedMethod.ReturnType.IsUnsafe()) && ReportUnsafeIfNotAllowed(syntax, diagnostics))
{
return true;
}
if (!isAddressOf)
{
ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, selectedMethod, location, isDelegateConversion: true);
}
ReportDiagnosticsIfObsolete(diagnostics, selectedMethod, syntax, hasBaseReceiver: false);
// No use site errors, but there could be use site warnings.
// If there are use site warnings, they were reported during the overload resolution process
// that chose selectedMethod.
Debug.Assert(!selectedMethod.HasUseSiteError, "Shouldn't have reached this point if there were use site errors.");
return false;
}
/// <summary>
/// This method is a wrapper around MethodGroupConversionHasErrors. As a preliminary step,
/// it checks whether a conversion exists.
/// </summary>
private bool MethodGroupConversionDoesNotExistOrHasErrors(
BoundMethodGroup boundMethodGroup,
NamedTypeSymbol delegateType,
Location delegateMismatchLocation,
BindingDiagnosticBag diagnostics,
out Conversion conversion)
{
if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation))
{
conversion = Conversion.NoConversion;
return true;
}
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
conversion = Conversions.GetMethodGroupDelegateConversion(boundMethodGroup, delegateType, ref useSiteInfo);
diagnostics.Add(delegateMismatchLocation, useSiteInfo);
if (!conversion.Exists)
{
if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, delegateType, diagnostics))
{
// No overload for '{0}' matches delegate '{1}'
diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType);
}
return true;
}
else
{
Debug.Assert(conversion.IsValid); // i.e. if it exists, then it is valid.
// Only cares about nullness and type of receiver, so no need to worry about BoundTypeOrValueExpression.
return this.MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf: false, delegateType, diagnostics);
}
}
public ConstantValue? FoldConstantConversion(
SyntaxNode syntax,
BoundExpression source,
Conversion conversion,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
RoslynDebug.Assert(source != null);
RoslynDebug.Assert((object)destination != null);
// The diagnostics bag can be null in cases where we know ahead of time that the
// conversion will succeed without error or warning. (For example, if we have a valid
// implicit numeric conversion on a constant of numeric type.)
// SPEC: A constant expression must be the null literal or a value with one of
// SPEC: the following types: sbyte, byte, short, ushort, int, uint, long,
// SPEC: ulong, char, float, double, decimal, bool, string, or any enumeration type.
// SPEC: The following conversions are permitted in constant expressions:
// SPEC: Identity conversions
// SPEC: Numeric conversions
// SPEC: Enumeration conversions
// SPEC: Constant expression conversions
// SPEC: Implicit and explicit reference conversions, provided that the source of the conversions
// SPEC: is a constant expression that evaluates to the null value.
// SPEC VIOLATION: C# has always allowed the following, even though this does violate the rule that
// SPEC VIOLATION: a constant expression must be either the null literal, or an expression of one
// SPEC VIOLATION: of the given types.
// SPEC VIOLATION: const C c = (C)null;
// TODO: Some conversions can produce errors or warnings depending on checked/unchecked.
// TODO: Fold conversions on enums and strings too.
var sourceConstantValue = source.ConstantValue;
if (sourceConstantValue == null)
{
if (conversion.Kind == ConversionKind.DefaultLiteral)
{
return destination.GetDefaultValue();
}
else
{
return sourceConstantValue;
}
}
else if (sourceConstantValue.IsBad)
{
return sourceConstantValue;
}
if (source.HasAnyErrors)
{
return null;
}
switch (conversion.Kind)
{
case ConversionKind.Identity:
// An identity conversion to a floating-point type (for example from a cast in
// source code) changes the internal representation of the constant value
// to precisely the required precision.
switch (destination.SpecialType)
{
case SpecialType.System_Single:
return ConstantValue.Create(sourceConstantValue.SingleValue);
case SpecialType.System_Double:
return ConstantValue.Create(sourceConstantValue.DoubleValue);
default:
return sourceConstantValue;
}
case ConversionKind.NullLiteral:
return sourceConstantValue;
case ConversionKind.ImplicitConstant:
return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics);
case ConversionKind.ExplicitNumeric:
case ConversionKind.ImplicitNumeric:
case ConversionKind.ExplicitEnumeration:
case ConversionKind.ImplicitEnumeration:
// The C# specification categorizes conversion from literal zero to nullable enum as
// an Implicit Enumeration Conversion. Such a thing should not be constant folded
// because nullable enums are never constants.
if (destination.IsNullableType())
{
return null;
}
return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics);
case ConversionKind.ExplicitReference:
case ConversionKind.ImplicitReference:
return sourceConstantValue.IsNull ? sourceConstantValue : null;
}
return null;
}
private ConstantValue? FoldConstantNumericConversion(
SyntaxNode syntax,
ConstantValue sourceValue,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
RoslynDebug.Assert(sourceValue != null);
Debug.Assert(!sourceValue.IsBad);
SpecialType destinationType;
if ((object)destination != null && destination.IsEnumType())
{
var underlyingType = ((NamedTypeSymbol)destination).EnumUnderlyingType;
RoslynDebug.Assert((object)underlyingType != null);
Debug.Assert(underlyingType.SpecialType != SpecialType.None);
destinationType = underlyingType.SpecialType;
}
else
{
destinationType = destination.GetSpecialTypeSafe();
}
// In an unchecked context we ignore overflowing conversions on conversions from any
// integral type, float and double to any integral type. "unchecked" actually does not
// affect conversions from decimal to any integral type; if those are out of bounds then
// we always give an error regardless.
if (sourceValue.IsDecimal)
{
if (!CheckConstantBounds(destinationType, sourceValue, out _))
{
// NOTE: Dev10 puts a suffix, "M", on the constant value.
Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value + "M", destination!);
return ConstantValue.Bad;
}
}
else if (destinationType == SpecialType.System_Decimal)
{
if (!CheckConstantBounds(destinationType, sourceValue, out _))
{
Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value!, destination!);
return ConstantValue.Bad;
}
}
else if (CheckOverflowAtCompileTime)
{
if (!CheckConstantBounds(destinationType, sourceValue, out bool maySucceedAtRuntime))
{
if (maySucceedAtRuntime)
{
// Can be calculated at runtime, but is not a compile-time constant.
Error(diagnostics, ErrorCode.WRN_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!);
return null;
}
else
{
Error(diagnostics, ErrorCode.ERR_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!);
return ConstantValue.Bad;
}
}
}
else if (destinationType == SpecialType.System_IntPtr || destinationType == SpecialType.System_UIntPtr)
{
if (!CheckConstantBounds(destinationType, sourceValue, out _))
{
// Can be calculated at runtime, but is not a compile-time constant.
return null;
}
}
return ConstantValue.Create(DoUncheckedConversion(destinationType, sourceValue), destinationType);
}
private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value)
{
// Note that we keep "single" floats as doubles internally to maintain higher precision. However,
// we do not do so in an entirely "lossless" manner. When *converting* to a float, we do lose
// the precision lost due to the conversion. But when doing arithmetic, we do the arithmetic on
// the double values.
//
// An example will help. Suppose we have:
//
// const float cf1 = 1.0f;
// const float cf2 = 1.0e-15f;
// const double cd3 = cf1 - cf2;
//
// We first take the double-precision values for 1.0 and 1.0e-15 and round them to floats,
// and then turn them back into doubles. Then when we do the subtraction, we do the subtraction
// in doubles, not in floats. Had we done the subtraction in floats, we'd get 1.0; but instead we
// do it in doubles and get 0.99999999999999.
//
// Similarly, if we have
//
// const int i4 = int.MaxValue; // 2147483647
// const float cf5 = int.MaxValue; // 2147483648.0
// const double cd6 = cf5; // 2147483648.0
//
// The int is converted to float and stored internally as the double 214783648, even though the
// fully precise int would fit into a double.
unchecked
{
switch (value.Discriminator)
{
case ConstantValueTypeDiscriminator.Byte:
byte byteValue = value.ByteValue;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)byteValue;
case SpecialType.System_Char: return (char)byteValue;
case SpecialType.System_UInt16: return (ushort)byteValue;
case SpecialType.System_UInt32: return (uint)byteValue;
case SpecialType.System_UInt64: return (ulong)byteValue;
case SpecialType.System_SByte: return (sbyte)byteValue;
case SpecialType.System_Int16: return (short)byteValue;
case SpecialType.System_Int32: return (int)byteValue;
case SpecialType.System_Int64: return (long)byteValue;
case SpecialType.System_IntPtr: return (int)byteValue;
case SpecialType.System_UIntPtr: return (uint)byteValue;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)byteValue;
case SpecialType.System_Decimal: return (decimal)byteValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Char:
char charValue = value.CharValue;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)charValue;
case SpecialType.System_Char: return (char)charValue;
case SpecialType.System_UInt16: return (ushort)charValue;
case SpecialType.System_UInt32: return (uint)charValue;
case SpecialType.System_UInt64: return (ulong)charValue;
case SpecialType.System_SByte: return (sbyte)charValue;
case SpecialType.System_Int16: return (short)charValue;
case SpecialType.System_Int32: return (int)charValue;
case SpecialType.System_Int64: return (long)charValue;
case SpecialType.System_IntPtr: return (int)charValue;
case SpecialType.System_UIntPtr: return (uint)charValue;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)charValue;
case SpecialType.System_Decimal: return (decimal)charValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.UInt16:
ushort uint16Value = value.UInt16Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)uint16Value;
case SpecialType.System_Char: return (char)uint16Value;
case SpecialType.System_UInt16: return (ushort)uint16Value;
case SpecialType.System_UInt32: return (uint)uint16Value;
case SpecialType.System_UInt64: return (ulong)uint16Value;
case SpecialType.System_SByte: return (sbyte)uint16Value;
case SpecialType.System_Int16: return (short)uint16Value;
case SpecialType.System_Int32: return (int)uint16Value;
case SpecialType.System_Int64: return (long)uint16Value;
case SpecialType.System_IntPtr: return (int)uint16Value;
case SpecialType.System_UIntPtr: return (uint)uint16Value;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)uint16Value;
case SpecialType.System_Decimal: return (decimal)uint16Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.UInt32:
uint uint32Value = value.UInt32Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)uint32Value;
case SpecialType.System_Char: return (char)uint32Value;
case SpecialType.System_UInt16: return (ushort)uint32Value;
case SpecialType.System_UInt32: return (uint)uint32Value;
case SpecialType.System_UInt64: return (ulong)uint32Value;
case SpecialType.System_SByte: return (sbyte)uint32Value;
case SpecialType.System_Int16: return (short)uint32Value;
case SpecialType.System_Int32: return (int)uint32Value;
case SpecialType.System_Int64: return (long)uint32Value;
case SpecialType.System_IntPtr: return (int)uint32Value;
case SpecialType.System_UIntPtr: return (uint)uint32Value;
case SpecialType.System_Single: return (double)(float)uint32Value;
case SpecialType.System_Double: return (double)uint32Value;
case SpecialType.System_Decimal: return (decimal)uint32Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.UInt64:
ulong uint64Value = value.UInt64Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)uint64Value;
case SpecialType.System_Char: return (char)uint64Value;
case SpecialType.System_UInt16: return (ushort)uint64Value;
case SpecialType.System_UInt32: return (uint)uint64Value;
case SpecialType.System_UInt64: return (ulong)uint64Value;
case SpecialType.System_SByte: return (sbyte)uint64Value;
case SpecialType.System_Int16: return (short)uint64Value;
case SpecialType.System_Int32: return (int)uint64Value;
case SpecialType.System_Int64: return (long)uint64Value;
case SpecialType.System_IntPtr: return (int)uint64Value;
case SpecialType.System_UIntPtr: return (uint)uint64Value;
case SpecialType.System_Single: return (double)(float)uint64Value;
case SpecialType.System_Double: return (double)uint64Value;
case SpecialType.System_Decimal: return (decimal)uint64Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.NUInt:
uint nuintValue = value.UInt32Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)nuintValue;
case SpecialType.System_Char: return (char)nuintValue;
case SpecialType.System_UInt16: return (ushort)nuintValue;
case SpecialType.System_UInt32: return (uint)nuintValue;
case SpecialType.System_UInt64: return (ulong)nuintValue;
case SpecialType.System_SByte: return (sbyte)nuintValue;
case SpecialType.System_Int16: return (short)nuintValue;
case SpecialType.System_Int32: return (int)nuintValue;
case SpecialType.System_Int64: return (long)nuintValue;
case SpecialType.System_IntPtr: return (int)nuintValue;
case SpecialType.System_Single: return (double)(float)nuintValue;
case SpecialType.System_Double: return (double)nuintValue;
case SpecialType.System_Decimal: return (decimal)nuintValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.SByte:
sbyte sbyteValue = value.SByteValue;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)sbyteValue;
case SpecialType.System_Char: return (char)sbyteValue;
case SpecialType.System_UInt16: return (ushort)sbyteValue;
case SpecialType.System_UInt32: return (uint)sbyteValue;
case SpecialType.System_UInt64: return (ulong)sbyteValue;
case SpecialType.System_SByte: return (sbyte)sbyteValue;
case SpecialType.System_Int16: return (short)sbyteValue;
case SpecialType.System_Int32: return (int)sbyteValue;
case SpecialType.System_Int64: return (long)sbyteValue;
case SpecialType.System_IntPtr: return (int)sbyteValue;
case SpecialType.System_UIntPtr: return (uint)sbyteValue;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)sbyteValue;
case SpecialType.System_Decimal: return (decimal)sbyteValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Int16:
short int16Value = value.Int16Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)int16Value;
case SpecialType.System_Char: return (char)int16Value;
case SpecialType.System_UInt16: return (ushort)int16Value;
case SpecialType.System_UInt32: return (uint)int16Value;
case SpecialType.System_UInt64: return (ulong)int16Value;
case SpecialType.System_SByte: return (sbyte)int16Value;
case SpecialType.System_Int16: return (short)int16Value;
case SpecialType.System_Int32: return (int)int16Value;
case SpecialType.System_Int64: return (long)int16Value;
case SpecialType.System_IntPtr: return (int)int16Value;
case SpecialType.System_UIntPtr: return (uint)int16Value;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)int16Value;
case SpecialType.System_Decimal: return (decimal)int16Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Int32:
int int32Value = value.Int32Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)int32Value;
case SpecialType.System_Char: return (char)int32Value;
case SpecialType.System_UInt16: return (ushort)int32Value;
case SpecialType.System_UInt32: return (uint)int32Value;
case SpecialType.System_UInt64: return (ulong)int32Value;
case SpecialType.System_SByte: return (sbyte)int32Value;
case SpecialType.System_Int16: return (short)int32Value;
case SpecialType.System_Int32: return (int)int32Value;
case SpecialType.System_Int64: return (long)int32Value;
case SpecialType.System_IntPtr: return (int)int32Value;
case SpecialType.System_UIntPtr: return (uint)int32Value;
case SpecialType.System_Single: return (double)(float)int32Value;
case SpecialType.System_Double: return (double)int32Value;
case SpecialType.System_Decimal: return (decimal)int32Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Int64:
long int64Value = value.Int64Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)int64Value;
case SpecialType.System_Char: return (char)int64Value;
case SpecialType.System_UInt16: return (ushort)int64Value;
case SpecialType.System_UInt32: return (uint)int64Value;
case SpecialType.System_UInt64: return (ulong)int64Value;
case SpecialType.System_SByte: return (sbyte)int64Value;
case SpecialType.System_Int16: return (short)int64Value;
case SpecialType.System_Int32: return (int)int64Value;
case SpecialType.System_Int64: return (long)int64Value;
case SpecialType.System_IntPtr: return (int)int64Value;
case SpecialType.System_UIntPtr: return (uint)int64Value;
case SpecialType.System_Single: return (double)(float)int64Value;
case SpecialType.System_Double: return (double)int64Value;
case SpecialType.System_Decimal: return (decimal)int64Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.NInt:
int nintValue = value.Int32Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)nintValue;
case SpecialType.System_Char: return (char)nintValue;
case SpecialType.System_UInt16: return (ushort)nintValue;
case SpecialType.System_UInt32: return (uint)nintValue;
case SpecialType.System_UInt64: return (ulong)nintValue;
case SpecialType.System_SByte: return (sbyte)nintValue;
case SpecialType.System_Int16: return (short)nintValue;
case SpecialType.System_Int32: return (int)nintValue;
case SpecialType.System_Int64: return (long)nintValue;
case SpecialType.System_IntPtr: return (int)nintValue;
case SpecialType.System_UIntPtr: return (uint)nintValue;
case SpecialType.System_Single: return (double)(float)nintValue;
case SpecialType.System_Double: return (double)nintValue;
case SpecialType.System_Decimal: return (decimal)nintValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Single:
case ConstantValueTypeDiscriminator.Double:
// When converting from a floating-point type to an integral type, if the checked conversion would
// throw an overflow exception, then the unchecked conversion is undefined. So that we have
// identical behavior on every host platform, we yield a result of zero in that case.
double doubleValue = CheckConstantBounds(destinationType, value.DoubleValue, out _) ? value.DoubleValue : 0D;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)doubleValue;
case SpecialType.System_Char: return (char)doubleValue;
case SpecialType.System_UInt16: return (ushort)doubleValue;
case SpecialType.System_UInt32: return (uint)doubleValue;
case SpecialType.System_UInt64: return (ulong)doubleValue;
case SpecialType.System_SByte: return (sbyte)doubleValue;
case SpecialType.System_Int16: return (short)doubleValue;
case SpecialType.System_Int32: return (int)doubleValue;
case SpecialType.System_Int64: return (long)doubleValue;
case SpecialType.System_IntPtr: return (int)doubleValue;
case SpecialType.System_UIntPtr: return (uint)doubleValue;
case SpecialType.System_Single: return (double)(float)doubleValue;
case SpecialType.System_Double: return (double)doubleValue;
case SpecialType.System_Decimal: return (value.Discriminator == ConstantValueTypeDiscriminator.Single) ? (decimal)(float)doubleValue : (decimal)doubleValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Decimal:
decimal decimalValue = CheckConstantBounds(destinationType, value.DecimalValue, out _) ? value.DecimalValue : 0m;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)decimalValue;
case SpecialType.System_Char: return (char)decimalValue;
case SpecialType.System_UInt16: return (ushort)decimalValue;
case SpecialType.System_UInt32: return (uint)decimalValue;
case SpecialType.System_UInt64: return (ulong)decimalValue;
case SpecialType.System_SByte: return (sbyte)decimalValue;
case SpecialType.System_Int16: return (short)decimalValue;
case SpecialType.System_Int32: return (int)decimalValue;
case SpecialType.System_Int64: return (long)decimalValue;
case SpecialType.System_IntPtr: return (int)decimalValue;
case SpecialType.System_UIntPtr: return (uint)decimalValue;
case SpecialType.System_Single: return (double)(float)decimalValue;
case SpecialType.System_Double: return (double)decimalValue;
case SpecialType.System_Decimal: return (decimal)decimalValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
default:
throw ExceptionUtilities.UnexpectedValue(value.Discriminator);
}
}
// all cases should have been handled in the switch above.
// return value.Value;
}
public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value, out bool maySucceedAtRuntime)
{
if (value.IsBad)
{
//assume that the constant was intended to be in bounds
maySucceedAtRuntime = false;
return true;
}
// Compute whether the value fits into the bounds of the given destination type without
// error. We know that the constant will fit into either a double or a decimal, so
// convert it to one of those and then check the bounds on that.
var canonicalValue = CanonicalizeConstant(value);
return canonicalValue is decimal ?
CheckConstantBounds(destinationType, (decimal)canonicalValue, out maySucceedAtRuntime) :
CheckConstantBounds(destinationType, (double)canonicalValue, out maySucceedAtRuntime);
}
private static bool CheckConstantBounds(SpecialType destinationType, double value, out bool maySucceedAtRuntime)
{
maySucceedAtRuntime = false;
// Dev10 checks (minValue - 1) < value < (maxValue + 1).
// See ExpressionBinder::isConstantInRange.
switch (destinationType)
{
case SpecialType.System_Byte: return (byte.MinValue - 1D) < value && value < (byte.MaxValue + 1D);
case SpecialType.System_Char: return (char.MinValue - 1D) < value && value < (char.MaxValue + 1D);
case SpecialType.System_UInt16: return (ushort.MinValue - 1D) < value && value < (ushort.MaxValue + 1D);
case SpecialType.System_UInt32: return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D);
case SpecialType.System_UInt64: return (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D);
case SpecialType.System_SByte: return (sbyte.MinValue - 1D) < value && value < (sbyte.MaxValue + 1D);
case SpecialType.System_Int16: return (short.MinValue - 1D) < value && value < (short.MaxValue + 1D);
case SpecialType.System_Int32: return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D);
// Note: Using <= to compare the min value matches the native compiler.
case SpecialType.System_Int64: return (long.MinValue - 1D) <= value && value < (long.MaxValue + 1D);
case SpecialType.System_Decimal: return ((double)decimal.MinValue - 1D) < value && value < ((double)decimal.MaxValue + 1D);
case SpecialType.System_IntPtr:
maySucceedAtRuntime = (long.MinValue - 1D) < value && value < (long.MaxValue + 1D);
return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D);
case SpecialType.System_UIntPtr:
maySucceedAtRuntime = (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D);
return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D);
}
return true;
}
private static bool CheckConstantBounds(SpecialType destinationType, decimal value, out bool maySucceedAtRuntime)
{
maySucceedAtRuntime = false;
// Dev10 checks (minValue - 1) < value < (maxValue + 1).
// See ExpressionBinder::isConstantInRange.
switch (destinationType)
{
case SpecialType.System_Byte: return (byte.MinValue - 1M) < value && value < (byte.MaxValue + 1M);
case SpecialType.System_Char: return (char.MinValue - 1M) < value && value < (char.MaxValue + 1M);
case SpecialType.System_UInt16: return (ushort.MinValue - 1M) < value && value < (ushort.MaxValue + 1M);
case SpecialType.System_UInt32: return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M);
case SpecialType.System_UInt64: return (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M);
case SpecialType.System_SByte: return (sbyte.MinValue - 1M) < value && value < (sbyte.MaxValue + 1M);
case SpecialType.System_Int16: return (short.MinValue - 1M) < value && value < (short.MaxValue + 1M);
case SpecialType.System_Int32: return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M);
case SpecialType.System_Int64: return (long.MinValue - 1M) < value && value < (long.MaxValue + 1M);
case SpecialType.System_IntPtr:
maySucceedAtRuntime = (long.MinValue - 1M) < value && value < (long.MaxValue + 1M);
return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M);
case SpecialType.System_UIntPtr:
maySucceedAtRuntime = (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M);
return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M);
}
return true;
}
// Takes in a constant of any kind and returns the constant as either a double or decimal
private static object CanonicalizeConstant(ConstantValue value)
{
switch (value.Discriminator)
{
case ConstantValueTypeDiscriminator.SByte: return (decimal)value.SByteValue;
case ConstantValueTypeDiscriminator.Int16: return (decimal)value.Int16Value;
case ConstantValueTypeDiscriminator.Int32: return (decimal)value.Int32Value;
case ConstantValueTypeDiscriminator.Int64: return (decimal)value.Int64Value;
case ConstantValueTypeDiscriminator.NInt: return (decimal)value.Int32Value;
case ConstantValueTypeDiscriminator.Byte: return (decimal)value.ByteValue;
case ConstantValueTypeDiscriminator.Char: return (decimal)value.CharValue;
case ConstantValueTypeDiscriminator.UInt16: return (decimal)value.UInt16Value;
case ConstantValueTypeDiscriminator.UInt32: return (decimal)value.UInt32Value;
case ConstantValueTypeDiscriminator.UInt64: return (decimal)value.UInt64Value;
case ConstantValueTypeDiscriminator.NUInt: return (decimal)value.UInt32Value;
case ConstantValueTypeDiscriminator.Single:
case ConstantValueTypeDiscriminator.Double: return value.DoubleValue;
case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue;
default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator);
}
// all cases handled in the switch, above.
}
}
}
| // 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.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
internal BoundExpression CreateConversion(
BoundExpression source,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var conversion = Conversions.ClassifyConversionFromExpression(source, destination, ref useSiteInfo);
diagnostics.Add(source.Syntax, useSiteInfo);
return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics);
}
internal BoundExpression CreateConversion(
BoundExpression source,
Conversion conversion,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics);
}
internal BoundExpression CreateConversion(
SyntaxNode syntax,
BoundExpression source,
Conversion conversion,
bool isCast,
ConversionGroup? conversionGroupOpt,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
return CreateConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, source.WasCompilerGenerated, destination, diagnostics);
}
protected BoundExpression CreateConversion(
SyntaxNode syntax,
BoundExpression source,
Conversion conversion,
bool isCast,
ConversionGroup? conversionGroupOpt,
bool wasCompilerGenerated,
TypeSymbol destination,
BindingDiagnosticBag diagnostics,
bool hasErrors = false)
{
RoslynDebug.Assert(source != null);
RoslynDebug.Assert((object)destination != null);
RoslynDebug.Assert(!isCast || conversionGroupOpt != null);
if (conversion.IsIdentity)
{
if (source is BoundTupleLiteral sourceTuple)
{
NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(destination, sourceTuple, diagnostics);
}
// identity tuple and switch conversions result in a converted expression
// to indicate that such conversions are no longer applicable.
source = BindToNaturalType(source, diagnostics);
RoslynDebug.Assert(source.Type is object);
// We need to preserve any conversion that changes the type (even identity conversions, like object->dynamic),
// or that was explicitly written in code (so that GetSemanticInfo can find the syntax in the bound tree).
if (!isCast && source.Type.Equals(destination, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
return source;
}
}
if (conversion.IsMethodGroup)
{
return CreateMethodGroupConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics);
}
// Obsolete diagnostics for method group are reported as part of creating the method group conversion.
ReportDiagnosticsIfObsolete(diagnostics, conversion, syntax, hasBaseReceiver: false);
CheckConstraintLanguageVersionAndRuntimeSupportForConversion(syntax, conversion, diagnostics);
if (conversion.IsAnonymousFunction && source.Kind == BoundKind.UnboundLambda)
{
return CreateAnonymousFunctionConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics);
}
if (conversion.IsStackAlloc)
{
return CreateStackAllocConversion(syntax, source, conversion, isCast, conversionGroupOpt, destination, diagnostics);
}
if (conversion.IsTupleLiteralConversion ||
(conversion.IsNullable && conversion.UnderlyingConversions[0].IsTupleLiteralConversion))
{
return CreateTupleLiteralConversion(syntax, (BoundTupleLiteral)source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics);
}
if (conversion.Kind == ConversionKind.SwitchExpression)
{
var convertedSwitch = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, destination, conversionIfTargetTyped: conversion, diagnostics);
return new BoundConversion(
syntax,
convertedSwitch,
conversion,
CheckOverflowAtRuntime,
explicitCastInCode: isCast && !wasCompilerGenerated,
conversionGroupOpt,
convertedSwitch.ConstantValue,
destination,
hasErrors);
}
if (conversion.Kind == ConversionKind.ConditionalExpression)
{
var convertedConditional = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, destination, conversionIfTargetTyped: conversion, diagnostics);
return new BoundConversion(
syntax,
convertedConditional,
conversion,
CheckOverflowAtRuntime,
explicitCastInCode: isCast && !wasCompilerGenerated,
conversionGroupOpt,
convertedConditional.ConstantValue,
destination,
hasErrors);
}
if (conversion.Kind == ConversionKind.InterpolatedString)
{
var unconvertedSource = (BoundUnconvertedInterpolatedString)source;
source = new BoundInterpolatedString(
unconvertedSource.Syntax,
interpolationData: null,
BindInterpolatedStringParts(unconvertedSource, diagnostics),
unconvertedSource.ConstantValue,
unconvertedSource.Type,
unconvertedSource.HasErrors);
}
if (conversion.Kind == ConversionKind.InterpolatedStringHandler)
{
return new BoundConversion(
syntax,
BindUnconvertedInterpolatedExpressionToHandlerType(source, (NamedTypeSymbol)destination, diagnostics),
conversion,
@checked: CheckOverflowAtRuntime,
explicitCastInCode: isCast && !wasCompilerGenerated,
conversionGroupOpt,
constantValueOpt: null,
destination);
}
if (source.Kind == BoundKind.UnconvertedSwitchExpression)
{
TypeSymbol? type = source.Type;
if (type is null)
{
Debug.Assert(!conversion.Exists);
type = CreateErrorType();
hasErrors = true;
}
source = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors);
if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated)
{
return source;
}
}
if (conversion.IsObjectCreation)
{
return ConvertObjectCreationExpression(syntax, (BoundUnconvertedObjectCreationExpression)source, isCast, destination, diagnostics);
}
if (source.Kind == BoundKind.UnconvertedConditionalOperator)
{
TypeSymbol? type = source.Type;
if (type is null)
{
Debug.Assert(!conversion.Exists);
type = CreateErrorType();
hasErrors = true;
}
source = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors);
if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated)
{
return source;
}
}
if (conversion.IsUserDefined)
{
// User-defined conversions are likely to be represented as multiple
// BoundConversion instances so a ConversionGroup is necessary.
return CreateUserDefinedConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt ?? new ConversionGroup(conversion), destination, diagnostics, hasErrors);
}
ConstantValue? constantValue = this.FoldConstantConversion(syntax, source, conversion, destination, diagnostics);
if (conversion.Kind == ConversionKind.DefaultLiteral)
{
source = new BoundDefaultExpression(source.Syntax, targetType: null, constantValue, type: destination)
.WithSuppression(source.IsSuppressed);
}
return new BoundConversion(
syntax,
BindToNaturalType(source, diagnostics),
conversion,
@checked: CheckOverflowAtRuntime,
explicitCastInCode: isCast && !wasCompilerGenerated,
conversionGroupOpt,
constantValueOpt: constantValue,
type: destination,
hasErrors: hasErrors)
{ WasCompilerGenerated = wasCompilerGenerated };
}
internal void CheckConstraintLanguageVersionAndRuntimeSupportForConversion(SyntaxNodeOrToken syntax, Conversion conversion, BindingDiagnosticBag diagnostics)
{
if (conversion.IsUserDefined && conversion.Method is MethodSymbol method && method.IsStatic && method.IsAbstract)
{
Debug.Assert(conversion.ConstrainedToTypeOpt is TypeParameterSymbol);
if (Compilation.SourceModule != method.ContainingModule)
{
Debug.Assert(syntax.SyntaxTree is object);
CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics, syntax.GetLocation()!);
if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces)
{
Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, syntax);
}
}
}
}
private BoundExpression ConvertObjectCreationExpression(SyntaxNode syntax, BoundUnconvertedObjectCreationExpression node, bool isCast, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt);
BoundExpression expr = BindObjectCreationExpression(node, destination.StrippedType(), arguments, diagnostics);
if (destination.IsNullableType())
{
// We manually create an ImplicitNullable conversion
// if the destination is nullable, in which case we
// target the underlying type e.g. `S? x = new();`
// is actually identical to `S? x = new S();`.
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var conversion = Conversions.ClassifyStandardConversion(null, expr.Type, destination, ref useSiteInfo);
expr = new BoundConversion(
node.Syntax,
operand: expr,
conversion: conversion,
@checked: false,
explicitCastInCode: isCast,
conversionGroupOpt: new ConversionGroup(conversion),
constantValueOpt: expr.ConstantValue,
type: destination);
diagnostics.Add(syntax, useSiteInfo);
}
arguments.Free();
return expr;
}
private BoundExpression BindObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, TypeSymbol type, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics)
{
var syntax = node.Syntax;
switch (type.TypeKind)
{
case TypeKind.Enum:
case TypeKind.Struct:
case TypeKind.Class when !type.IsAnonymousType: // We don't want to enable object creation with unspeakable types
return BindClassCreationExpression(syntax, type.Name, typeNode: syntax, (NamedTypeSymbol)type, arguments, diagnostics, node.InitializerOpt, wasTargetTyped: true);
case TypeKind.TypeParameter:
return BindTypeParameterCreationExpression(syntax, (TypeParameterSymbol)type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics);
case TypeKind.Delegate:
return BindDelegateCreationExpression(syntax, (NamedTypeSymbol)type, arguments, node.InitializerOpt, diagnostics);
case TypeKind.Interface:
return BindInterfaceCreationExpression(syntax, (NamedTypeSymbol)type, diagnostics, typeNode: syntax, arguments, node.InitializerOpt, wasTargetTyped: true);
case TypeKind.Array:
case TypeKind.Class:
case TypeKind.Dynamic:
Error(diagnostics, ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, syntax, type);
goto case TypeKind.Error;
case TypeKind.Pointer:
case TypeKind.FunctionPointer:
Error(diagnostics, ErrorCode.ERR_UnsafeTypeInObjectCreation, syntax, type);
goto case TypeKind.Error;
case TypeKind.Error:
return MakeBadExpressionForObjectCreation(syntax, type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics);
case var v:
throw ExceptionUtilities.UnexpectedValue(v);
}
}
/// <summary>
/// Rewrite the subexpressions in a conditional expression to convert the whole thing to the destination type.
/// </summary>
private BoundExpression ConvertConditionalExpression(
BoundUnconvertedConditionalOperator source,
TypeSymbol destination,
Conversion? conversionIfTargetTyped,
BindingDiagnosticBag diagnostics,
bool hasErrors = false)
{
bool targetTyped = conversionIfTargetTyped is { };
Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything));
ImmutableArray<Conversion> underlyingConversions = conversionIfTargetTyped.GetValueOrDefault().UnderlyingConversions;
var condition = source.Condition;
hasErrors |= source.HasErrors || destination.IsErrorType();
var trueExpr =
targetTyped
? CreateConversion(source.Consequence.Syntax, source.Consequence, underlyingConversions[0], isCast: false, conversionGroupOpt: null, destination, diagnostics)
: GenerateConversionForAssignment(destination, source.Consequence, diagnostics);
var falseExpr =
targetTyped
? CreateConversion(source.Alternative.Syntax, source.Alternative, underlyingConversions[1], isCast: false, conversionGroupOpt: null, destination, diagnostics)
: GenerateConversionForAssignment(destination, source.Alternative, diagnostics);
var constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr);
hasErrors |= constantValue?.IsBad == true;
if (targetTyped && !destination.IsErrorType() && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureTargetTypedConditional))
{
diagnostics.Add(
ErrorCode.ERR_NoImplicitConvTargetTypedConditional,
source.Syntax.Location,
Compilation.LanguageVersion.ToDisplayString(),
source.Consequence.Display,
source.Alternative.Display,
new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()));
}
return new BoundConditionalOperator(source.Syntax, isRef: false, condition, trueExpr, falseExpr, constantValue, source.Type, wasTargetTyped: targetTyped, destination, hasErrors)
.WithSuppression(source.IsSuppressed);
}
/// <summary>
/// Rewrite the expressions in the switch expression arms to add a conversion to the destination type.
/// </summary>
private BoundExpression ConvertSwitchExpression(BoundUnconvertedSwitchExpression source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false)
{
bool targetTyped = conversionIfTargetTyped is { };
Conversion conversion = conversionIfTargetTyped ?? Conversion.Identity;
Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything));
ImmutableArray<Conversion> underlyingConversions = conversion.UnderlyingConversions;
var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(source.SwitchArms.Length);
for (int i = 0, n = source.SwitchArms.Length; i < n; i++)
{
var oldCase = source.SwitchArms[i];
Debug.Assert(oldCase.Syntax is SwitchExpressionArmSyntax);
var binder = GetRequiredBinder(oldCase.Syntax);
var oldValue = oldCase.Value;
var newValue =
targetTyped
? binder.CreateConversion(oldValue.Syntax, oldValue, underlyingConversions[i], isCast: false, conversionGroupOpt: null, destination, diagnostics)
: binder.GenerateConversionForAssignment(destination, oldValue, diagnostics);
var newCase = (oldValue == newValue) ? oldCase :
new BoundSwitchExpressionArm(oldCase.Syntax, oldCase.Locals, oldCase.Pattern, oldCase.WhenClause, newValue, oldCase.Label, oldCase.HasErrors);
builder.Add(newCase);
}
var newSwitchArms = builder.ToImmutableAndFree();
return new BoundConvertedSwitchExpression(
source.Syntax, source.Type, targetTyped, conversion, source.Expression, newSwitchArms, source.DecisionDag,
source.DefaultLabel, source.ReportedNotExhaustive, destination, hasErrors || source.HasErrors);
}
private BoundExpression CreateUserDefinedConversion(
SyntaxNode syntax,
BoundExpression source,
Conversion conversion,
bool isCast,
ConversionGroup conversionGroup,
TypeSymbol destination,
BindingDiagnosticBag diagnostics,
bool hasErrors)
{
Debug.Assert(conversionGroup != null);
Debug.Assert(conversion.IsUserDefined);
if (!conversion.IsValid)
{
if (!hasErrors)
GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination);
return new BoundConversion(
syntax,
source,
conversion,
CheckOverflowAtRuntime,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: destination,
hasErrors: true)
{ WasCompilerGenerated = source.WasCompilerGenerated };
}
// Due to an oddity in the way we create a non-lifted user-defined conversion from A to D?
// (required backwards compatibility with the native compiler) we can end up in a situation
// where we have:
// a standard conversion from A to B?
// then a standard conversion from B? to B
// then a user-defined conversion from B to C
// then a standard conversion from C to C?
// then a standard conversion from C? to D?
//
// In that scenario, the "from type" of the conversion will be B? and the "from conversion" will be
// from A to B?. Similarly the "to type" of the conversion will be C? and the "to conversion"
// of the conversion will be from C? to D?.
//
// Therefore, we might need to introduce an extra conversion on the source side, from B? to B.
// Now, you might think we should also introduce an extra conversion on the destination side,
// from C to C?. But that then gives us the following bad situation: If we in fact bind this as
//
// (D?)(C?)(C)(B)(B?)(A)x
//
// then what we are in effect doing is saying "convert C? to D? by checking for null, unwrapping,
// converting C to D, and then wrapping". But we know that the C? will never be null. In this case
// we should actually generate
//
// (D?)(C)(B)(B?)(A)x
//
// And thereby skip the unnecessary nullable conversion.
Debug.Assert(conversion.BestUserDefinedConversionAnalysis is object); // All valid user-defined conversions have this populated
// Original expression --> conversion's "from" type
BoundExpression convertedOperand = CreateConversion(
syntax: source.Syntax,
source: source,
conversion: conversion.UserDefinedFromConversion,
isCast: false,
conversionGroupOpt: conversionGroup,
wasCompilerGenerated: false,
destination: conversion.BestUserDefinedConversionAnalysis.FromType,
diagnostics: diagnostics);
TypeSymbol conversionParameterType = conversion.BestUserDefinedConversionAnalysis.Operator.GetParameterType(0);
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm &&
!TypeSymbol.Equals(conversion.BestUserDefinedConversionAnalysis.FromType, conversionParameterType, TypeCompareKind.ConsiderEverything2))
{
// Conversion's "from" type --> conversion method's parameter type.
convertedOperand = CreateConversion(
syntax: syntax,
source: convertedOperand,
conversion: Conversions.ClassifyStandardConversion(null, convertedOperand.Type, conversionParameterType, ref useSiteInfo),
isCast: false,
conversionGroupOpt: conversionGroup,
wasCompilerGenerated: true,
destination: conversionParameterType,
diagnostics: diagnostics);
}
BoundExpression userDefinedConversion;
TypeSymbol conversionReturnType = conversion.BestUserDefinedConversionAnalysis.Operator.ReturnType;
TypeSymbol conversionToType = conversion.BestUserDefinedConversionAnalysis.ToType;
Conversion toConversion = conversion.UserDefinedToConversion;
if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm &&
!TypeSymbol.Equals(conversionToType, conversionReturnType, TypeCompareKind.ConsiderEverything2))
{
// Conversion method's parameter type --> conversion method's return type
// NB: not calling CreateConversion here because this is the recursive base case.
userDefinedConversion = new BoundConversion(
syntax,
convertedOperand,
conversion,
@checked: false, // There are no checked user-defined conversions, but the conversions on either side might be checked.
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: conversionReturnType)
{ WasCompilerGenerated = true };
if (conversionToType.IsNullableType() && TypeSymbol.Equals(conversionToType.GetNullableUnderlyingType(), conversionReturnType, TypeCompareKind.ConsiderEverything2))
{
// Skip introducing the conversion from C to C?. The "to" conversion is now wrong though,
// because it will still assume converting C? to D?.
toConversion = Conversions.ClassifyConversionFromType(conversionReturnType, destination, ref useSiteInfo);
Debug.Assert(toConversion.Exists);
}
else
{
// Conversion method's return type --> conversion's "to" type
userDefinedConversion = CreateConversion(
syntax: syntax,
source: userDefinedConversion,
conversion: Conversions.ClassifyStandardConversion(null, conversionReturnType, conversionToType, ref useSiteInfo),
isCast: false,
conversionGroupOpt: conversionGroup,
wasCompilerGenerated: true,
destination: conversionToType,
diagnostics: diagnostics);
}
}
else
{
// Conversion method's parameter type --> conversion method's "to" type
// NB: not calling CreateConversion here because this is the recursive base case.
userDefinedConversion = new BoundConversion(
syntax,
convertedOperand,
conversion,
@checked: false,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: conversionToType)
{ WasCompilerGenerated = true };
}
diagnostics.Add(syntax, useSiteInfo);
// Conversion's "to" type --> final type
BoundExpression finalConversion = CreateConversion(
syntax: syntax,
source: userDefinedConversion,
conversion: toConversion,
isCast: false,
conversionGroupOpt: conversionGroup,
wasCompilerGenerated: true, // NOTE: doesn't necessarily set flag on resulting bound expression.
destination: destination,
diagnostics: diagnostics);
finalConversion.ResetCompilerGenerated(source.WasCompilerGenerated);
return finalConversion;
}
private BoundExpression CreateAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
// We have a successful anonymous function conversion; rather than producing a node
// which is a conversion on top of an unbound lambda, replace it with the bound
// lambda.
// UNDONE: Figure out what to do about the error case, where a lambda
// UNDONE: is converted to a delegate that does not match. What to surface then?
var unboundLambda = (UnboundLambda)source;
if ((destination.SpecialType == SpecialType.System_Delegate || destination.IsNonGenericExpressionType()) &&
syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType))
{
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var delegateType = unboundLambda.InferDelegateType(ref useSiteInfo);
BoundLambda boundLambda;
if (delegateType is { })
{
bool isExpressionTree = destination.IsNonGenericExpressionType();
if (isExpressionTree)
{
delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType);
delegateType.AddUseSiteInfo(ref useSiteInfo);
}
boundLambda = unboundLambda.Bind(delegateType, isExpressionTree);
}
else
{
diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation());
delegateType = CreateErrorType();
boundLambda = unboundLambda.BindForErrorRecovery();
}
diagnostics.AddRange(boundLambda.Diagnostics);
var expr = createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, delegateType);
conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo);
diagnostics.Add(syntax, useSiteInfo);
return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics);
}
else
{
#if DEBUG
// Test inferring a delegate type for all callers.
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
_ = unboundLambda.InferDelegateType(ref discardedUseSiteInfo);
#endif
var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination, isExpressionTree: destination.IsGenericOrNonGenericExpressionType(out _));
diagnostics.AddRange(boundLambda.Diagnostics);
return createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, destination);
}
static BoundConversion createAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, BoundLambda boundLambda, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination)
{
return new BoundConversion(
syntax,
boundLambda,
conversion,
@checked: false,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: destination)
{ WasCompilerGenerated = source.WasCompilerGenerated };
}
}
private BoundExpression CreateMethodGroupConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
var (originalGroup, isAddressOf) = source switch
{
BoundMethodGroup m => (m, false),
BoundUnconvertedAddressOfOperator { Operand: { } m } => (m, true),
_ => throw ExceptionUtilities.UnexpectedValue(source),
};
BoundMethodGroup group = FixMethodGroupWithTypeOrValue(originalGroup, conversion, diagnostics);
bool hasErrors = false;
if (MethodGroupConversionHasErrors(syntax, conversion, group.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf, destination, diagnostics))
{
hasErrors = true;
}
if (destination.SpecialType == SpecialType.System_Delegate &&
syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType))
{
// https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion.
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var delegateType = GetMethodGroupDelegateType(group, ref useSiteInfo);
var expr = createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, delegateType!, hasErrors);
conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo);
diagnostics.Add(syntax, useSiteInfo);
return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics);
}
#if DEBUG
// Test inferring a delegate type for all callers.
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
_ = GetMethodGroupDelegateType(group, ref discardedUseSiteInfo);
#endif
return createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, destination, hasErrors);
static BoundConversion createMethodGroupConversion(SyntaxNode syntax, BoundMethodGroup group, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, bool hasErrors)
{
return new BoundConversion(syntax, group, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = group.WasCompilerGenerated };
}
}
private BoundExpression CreateStackAllocConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
Debug.Assert(conversion.IsStackAlloc);
var boundStackAlloc = (BoundStackAllocArrayCreation)source;
var elementType = boundStackAlloc.ElementType;
TypeSymbol stackAllocType;
switch (conversion.Kind)
{
case ConversionKind.StackAllocToPointerType:
ReportUnsafeIfNotAllowed(syntax.Location, diagnostics);
stackAllocType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType));
break;
case ConversionKind.StackAllocToSpanType:
CheckFeatureAvailability(syntax, MessageID.IDS_FeatureRefStructs, diagnostics);
stackAllocType = Compilation.GetWellKnownType(WellKnownType.System_Span_T).Construct(elementType);
break;
default:
throw ExceptionUtilities.UnexpectedValue(conversion.Kind);
}
var convertedNode = new BoundConvertedStackAllocExpression(syntax, elementType, boundStackAlloc.Count, boundStackAlloc.InitializerOpt, stackAllocType, boundStackAlloc.HasErrors);
var underlyingConversion = conversion.UnderlyingConversions.Single();
return CreateConversion(syntax, convertedNode, underlyingConversion, isCast: isCast, conversionGroup, destination, diagnostics);
}
private BoundExpression CreateTupleLiteralConversion(SyntaxNode syntax, BoundTupleLiteral sourceTuple, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics)
{
// We have a successful tuple conversion; rather than producing a separate conversion node
// which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments.
Debug.Assert(conversion.IsNullable == destination.IsNullableType());
var destinationWithoutNullable = destination;
var conversionWithoutNullable = conversion;
if (conversion.IsNullable)
{
destinationWithoutNullable = destination.GetNullableUnderlyingType();
conversionWithoutNullable = conversion.UnderlyingConversions[0];
}
Debug.Assert(conversionWithoutNullable.IsTupleLiteralConversion);
NamedTypeSymbol targetType = (NamedTypeSymbol)destinationWithoutNullable;
if (targetType.IsTupleType)
{
NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(targetType, sourceTuple, diagnostics);
// do not lose the original element names and locations in the literal if different from names in the target
//
// the tuple has changed the type of elements due to target-typing,
// but element names has not changed and locations of their declarations
// should not be confused with element locations on the target type.
if (sourceTuple.Type is NamedTypeSymbol { IsTupleType: true } sourceType)
{
targetType = targetType.WithTupleDataFrom(sourceType);
}
else
{
var tupleSyntax = (TupleExpressionSyntax)sourceTuple.Syntax;
var locationBuilder = ArrayBuilder<Location?>.GetInstance();
foreach (var argument in tupleSyntax.Arguments)
{
locationBuilder.Add(argument.NameColon?.Name.Location);
}
targetType = targetType.WithElementNames(sourceTuple.ArgumentNamesOpt!,
locationBuilder.ToImmutableAndFree(),
errorPositions: default,
ImmutableArray.Create(tupleSyntax.Location));
}
}
var arguments = sourceTuple.Arguments;
var convertedArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Length);
var targetElementTypes = targetType.TupleElementTypesWithAnnotations;
Debug.Assert(targetElementTypes.Length == arguments.Length, "converting a tuple literal to incompatible type?");
var underlyingConversions = conversionWithoutNullable.UnderlyingConversions;
for (int i = 0; i < arguments.Length; i++)
{
var argument = arguments[i];
var destType = targetElementTypes[i];
var elementConversion = underlyingConversions[i];
var elementConversionGroup = isCast ? new ConversionGroup(elementConversion, destType) : null;
convertedArguments.Add(CreateConversion(argument.Syntax, argument, elementConversion, isCast: isCast, elementConversionGroup, destType.Type, diagnostics));
}
BoundExpression result = new BoundConvertedTupleLiteral(
sourceTuple.Syntax,
sourceTuple,
wasTargetTyped: true,
convertedArguments.ToImmutableAndFree(),
sourceTuple.ArgumentNamesOpt,
sourceTuple.InferredNamesOpt,
targetType).WithSuppression(sourceTuple.IsSuppressed);
if (!TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything2))
{
// literal cast is applied to the literal
result = new BoundConversion(
sourceTuple.Syntax,
result,
conversion,
@checked: false,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: destination);
}
// If we had a cast in the code, keep conversion in the tree.
// even though the literal is already converted to the target type.
if (isCast)
{
result = new BoundConversion(
syntax,
result,
Conversion.Identity,
@checked: false,
explicitCastInCode: isCast,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: destination);
}
return result;
}
private static bool IsMethodGroupWithTypeOrValueReceiver(BoundNode node)
{
if (node.Kind != BoundKind.MethodGroup)
{
return false;
}
return Binder.IsTypeOrValueExpression(((BoundMethodGroup)node).ReceiverOpt);
}
private BoundMethodGroup FixMethodGroupWithTypeOrValue(BoundMethodGroup group, Conversion conversion, BindingDiagnosticBag diagnostics)
{
if (!IsMethodGroupWithTypeOrValueReceiver(group))
{
return group;
}
BoundExpression? receiverOpt = group.ReceiverOpt;
RoslynDebug.Assert(receiverOpt != null);
receiverOpt = ReplaceTypeOrValueReceiver(receiverOpt, useType: conversion.Method?.RequiresInstanceReceiver == false && !conversion.IsExtensionMethod, diagnostics);
return group.Update(
group.TypeArgumentsOpt,
group.Name,
group.Methods,
group.LookupSymbolOpt,
group.LookupError,
group.Flags,
receiverOpt, //only change
group.ResultKind);
}
/// <summary>
/// This method implements the algorithm in spec section 7.6.5.1.
///
/// For method group conversions, there are situations in which the conversion is
/// considered to exist ("Otherwise the algorithm produces a single best method M having
/// the same number of parameters as D and the conversion is considered to exist"), but
/// application of the conversion fails. These are the "final validation" steps of
/// overload resolution.
/// </summary>
/// <returns>
/// True if there is any error, except lack of runtime support errors.
/// </returns>
private bool MemberGroupFinalValidation(BoundExpression? receiverOpt, MethodSymbol methodSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod)
{
if (!IsBadBaseAccess(node, receiverOpt, methodSymbol, diagnostics))
{
CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, methodSymbol, diagnostics);
}
if (MemberGroupFinalValidationAccessibilityChecks(receiverOpt, methodSymbol, node, diagnostics, invokedAsExtensionMethod))
{
return true;
}
// SPEC: If the best method is a generic method, the type arguments (supplied or inferred) are checked against the constraints
// SPEC: declared on the generic method. If any type argument does not satisfy the corresponding constraint(s) on
// SPEC: the type parameter, a binding-time error occurs.
// The portion of the overload resolution spec quoted above is subtle and somewhat
// controversial. The upshot of this is that overload resolution does not consider
// constraints to be a part of the signature. Overload resolution matches arguments to
// parameter lists; it does not consider things which are outside of the parameter list.
// If the best match from the arguments to the formal parameters is not viable then we
// give an error rather than falling back to a worse match.
//
// Consider the following:
//
// void M<T>(T t) where T : Reptile {}
// void M(object x) {}
// ...
// M(new Giraffe());
//
// The correct analysis is to determine that the applicable candidates are
// M<Giraffe>(Giraffe) and M(object). Overload resolution then chooses the former
// because it is an exact match, over the latter which is an inexact match. Only after
// the best method is determined do we check the constraints and discover that the
// constraint on T has been violated.
//
// Note that this is different from the rule that says that during type inference, if an
// inference violates a constraint then inference fails. For example:
//
// class C<T> where T : struct {}
// ...
// void M<U>(U u, C<U> c){}
// void M(object x, object y) {}
// ...
// M("hello", null);
//
// Type inference determines that U is string, but since C<string> is not a valid type
// because of the constraint, type inference fails. M<string> is never added to the
// applicable candidate set, so the applicable candidate set consists solely of
// M(object, object) and is therefore the best match.
return !methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, node.Location, diagnostics));
}
/// <summary>
/// Performs the following checks:
///
/// Spec 7.6.5: Invocation expressions (definition of Final Validation)
/// The method is validated in the context of the method group: If the best method is a static method,
/// the method group must have resulted from a simple-name or a member-access through a type. If the best
/// method is an instance method, the method group must have resulted from a simple-name, a member-access
/// through a variable or value, or a base-access. If neither of these requirements is true, a binding-time
/// error occurs.
/// (Note that the spec omits to mention, in the case of an instance method invoked through a simple name, that
/// the invocation must appear within the body of an instance method)
///
/// Spec 7.5.4: Compile-time checking of dynamic overload resolution
/// If F is a static method, the method group must have resulted from a simple-name, a member-access through a type,
/// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
/// If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value,
/// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1).
/// </summary>
/// <returns>
/// True if there is any error.
/// </returns>
private bool MemberGroupFinalValidationAccessibilityChecks(BoundExpression? receiverOpt, Symbol memberSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod)
{
// Perform final validation of the method to be invoked.
Debug.Assert(memberSymbol.Kind != SymbolKind.Method ||
memberSymbol.CanBeReferencedByName);
//note that the same assert does not hold for all properties. Some properties and (all indexers) are not referenceable by name, yet
//their binding brings them through here, perhaps needlessly.
if (IsTypeOrValueExpression(receiverOpt))
{
// TypeOrValue expression isn't replaced only if the invocation is late bound, in which case it can't be extension method.
// None of the checks below apply if the receiver can't be classified as a type or value.
Debug.Assert(!invokedAsExtensionMethod);
}
else if (!memberSymbol.RequiresInstanceReceiver())
{
Debug.Assert(!invokedAsExtensionMethod || (receiverOpt != null));
if (invokedAsExtensionMethod)
{
if (IsMemberAccessedThroughType(receiverOpt))
{
if (receiverOpt.Kind == BoundKind.QueryClause)
{
RoslynDebug.Assert(receiverOpt.Type is object);
// Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found.
diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, receiverOpt.Type, memberSymbol.Name);
}
else
{
// An object reference is required for the non-static field, method, or property '{0}'
diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol);
}
return true;
}
}
else if (!WasImplicitReceiver(receiverOpt) && IsMemberAccessedThroughVariableOrValue(receiverOpt))
{
if (this.Flags.Includes(BinderFlags.CollectionInitializerAddMethod))
{
diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, node.Location, memberSymbol);
}
else if (node.Kind() == SyntaxKind.AwaitExpression && memberSymbol.Name == WellKnownMemberNames.GetAwaiter)
{
RoslynDebug.Assert(receiverOpt.Type is object);
diagnostics.Add(ErrorCode.ERR_BadAwaitArg, node.Location, receiverOpt.Type);
}
else
{
diagnostics.Add(ErrorCode.ERR_ObjectProhibited, node.Location, memberSymbol);
}
return true;
}
}
else if (IsMemberAccessedThroughType(receiverOpt))
{
diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol);
return true;
}
else if (WasImplicitReceiver(receiverOpt))
{
if (InFieldInitializer && !ContainingType!.IsScriptClass || InConstructorInitializer || InAttributeArgument)
{
SyntaxNode errorNode = node;
if (node.Parent != null && node.Parent.Kind() == SyntaxKind.InvocationExpression)
{
errorNode = node.Parent;
}
ErrorCode code = InFieldInitializer ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired;
diagnostics.Add(code, errorNode.Location, memberSymbol);
return true;
}
// If we could access the member through implicit "this" the receiver would be a BoundThisReference.
// If it is null it means that the instance member is inaccessible.
if (receiverOpt == null || ContainingMember().IsStatic)
{
Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, memberSymbol);
return true;
}
}
var containingType = this.ContainingType;
if (containingType is object)
{
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
bool isAccessible = this.IsSymbolAccessibleConditional(memberSymbol.GetTypeOrReturnType().Type, containingType, ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
if (!isAccessible)
{
// In the presence of non-transitive [InternalsVisibleTo] in source, or obnoxious symbols from metadata, it is possible
// to select a method through overload resolution in which the type is not accessible. In this case a method cannot
// be called through normal IL, so we give an error. Neither [InternalsVisibleTo] nor the need for this diagnostic is
// described by the language specification.
//
// Dev11 perform different access checks. See bug #530360 and tests AccessCheckTests.InaccessibleReturnType.
Error(diagnostics, ErrorCode.ERR_BadAccess, node, memberSymbol);
return true;
}
}
return false;
}
private static bool IsMemberAccessedThroughVariableOrValue(BoundExpression? receiverOpt)
{
if (receiverOpt == null)
{
return false;
}
return !IsMemberAccessedThroughType(receiverOpt);
}
internal static bool IsMemberAccessedThroughType([NotNullWhen(true)] BoundExpression? receiverOpt)
{
if (receiverOpt == null)
{
return false;
}
while (receiverOpt.Kind == BoundKind.QueryClause)
{
receiverOpt = ((BoundQueryClause)receiverOpt).Value;
}
return receiverOpt.Kind == BoundKind.TypeExpression;
}
/// <summary>
/// Was the receiver expression compiler-generated?
/// </summary>
internal static bool WasImplicitReceiver([NotNullWhen(false)] BoundExpression? receiverOpt)
{
if (receiverOpt == null) return true;
if (!receiverOpt.WasCompilerGenerated) return false;
switch (receiverOpt.Kind)
{
case BoundKind.ThisReference:
case BoundKind.HostObjectMemberReference:
case BoundKind.PreviousSubmissionReference:
return true;
default:
return false;
}
}
/// <summary>
/// This method implements the checks in spec section 15.2.
/// </summary>
internal bool MethodIsCompatibleWithDelegateOrFunctionPointer(BoundExpression? receiverOpt, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, Location errorLocation, BindingDiagnosticBag diagnostics)
{
Debug.Assert(delegateType is NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { HasUseSiteError: false } }
|| delegateType.TypeKind == TypeKind.FunctionPointer,
"This method should only be called for valid delegate or function pointer types.");
MethodSymbol delegateOrFuncPtrMethod = delegateType switch
{
NamedTypeSymbol { DelegateInvokeMethod: { } invokeMethod } => invokeMethod,
FunctionPointerTypeSymbol { Signature: { } signature } => signature,
_ => throw ExceptionUtilities.UnexpectedValue(delegateType),
};
Debug.Assert(!isExtensionMethod || (receiverOpt != null));
// - Argument types "match", and
var delegateOrFuncPtrParameters = delegateOrFuncPtrMethod.Parameters;
var methodParameters = method.Parameters;
int numParams = delegateOrFuncPtrParameters.Length;
if (methodParameters.Length != numParams + (isExtensionMethod ? 1 : 0))
{
// This can happen if "method" has optional parameters.
Debug.Assert(methodParameters.Length > numParams + (isExtensionMethod ? 1 : 0));
Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType);
return false;
}
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
// If this is an extension method delegate, the caller should have verified the
// receiver is compatible with the "this" parameter of the extension method.
Debug.Assert(!isExtensionMethod ||
(Conversions.ConvertExtensionMethodThisArg(methodParameters[0].Type, receiverOpt!.Type, ref useSiteInfo).Exists && useSiteInfo.Diagnostics.IsNullOrEmpty()));
useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo);
for (int i = 0; i < numParams; i++)
{
var delegateParameter = delegateOrFuncPtrParameters[i];
var methodParameter = methodParameters[isExtensionMethod ? i + 1 : i];
// The delegate compatibility checks are stricter than the checks on applicable functions: it's possible
// to get here with a method that, while all the parameters are applicable, is not actually delegate
// compatible. This is because the Applicable function member spec requires that:
// * Every value parameter (non-ref or similar) from the delegate type has an implicit conversion to the corresponding
// target parameter
// * Every ref or similar parameter has an identity conversion to the corresponding target parameter
// However, the delegate compatibility requirements are stricter:
// * Every value parameter (non-ref or similar) from the delegate type has an implicit _reference_ conversion to the
// corresponding target parameter.
// * Every ref or similar parameter has an identity conversion to the corresponding target parameter
// Note the addition of the reference requirement: it means that for delegate type void D(int i), void M(long l) is
// _applicable_, but not _compatible_.
if (!hasConversion(delegateType.TypeKind, Conversions, delegateParameter.Type, methodParameter.Type, delegateParameter.RefKind, methodParameter.RefKind, ref useSiteInfo))
{
// No overload for '{0}' matches delegate '{1}'
Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
}
if (delegateOrFuncPtrMethod.RefKind != method.RefKind)
{
Error(diagnostics, getRefMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
var methodReturnType = method.ReturnType;
var delegateReturnType = delegateOrFuncPtrMethod.ReturnType;
bool returnsMatch = delegateOrFuncPtrMethod switch
{
{ RefKind: RefKind.None, ReturnsVoid: true } => method.ReturnsVoid,
{ RefKind: var destinationRefKind } => hasConversion(delegateType.TypeKind, Conversions, methodReturnType, delegateReturnType, method.RefKind, destinationRefKind, ref useSiteInfo),
};
if (!returnsMatch)
{
Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
if (delegateType.IsFunctionPointer())
{
if (isExtensionMethod)
{
Error(diagnostics, ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, errorLocation);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
if (!method.IsStatic)
{
// This check is here purely for completeness of implementing the spec. It should
// never be hit, as static methods should be eliminated as candidates in overload
// resolution and should never make it to this point.
Debug.Fail("This method should have been eliminated in overload resolution!");
Error(diagnostics, ErrorCode.ERR_FuncPtrMethMustBeStatic, errorLocation, method);
diagnostics.Add(errorLocation, useSiteInfo);
return false;
}
}
diagnostics.Add(errorLocation, useSiteInfo);
return true;
static bool hasConversion(TypeKind targetKind, Conversions conversions, TypeSymbol source, TypeSymbol destination,
RefKind sourceRefKind, RefKind destinationRefKind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
if (sourceRefKind != destinationRefKind)
{
return false;
}
if (sourceRefKind != RefKind.None)
{
return ConversionsBase.HasIdentityConversion(source, destination);
}
if (conversions.HasIdentityOrImplicitReferenceConversion(source, destination, ref useSiteInfo))
{
return true;
}
return targetKind == TypeKind.FunctionPointer
&& (ConversionsBase.HasImplicitPointerToVoidConversion(source, destination)
|| conversions.HasImplicitPointerConversion(source, destination, ref useSiteInfo));
}
static ErrorCode getMethodMismatchErrorCode(TypeKind type)
=> type switch
{
TypeKind.Delegate => ErrorCode.ERR_MethDelegateMismatch,
TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch,
_ => throw ExceptionUtilities.UnexpectedValue(type)
};
static ErrorCode getRefMismatchErrorCode(TypeKind type)
=> type switch
{
TypeKind.Delegate => ErrorCode.ERR_DelegateRefMismatch,
TypeKind.FunctionPointer => ErrorCode.ERR_FuncPtrRefMismatch,
_ => throw ExceptionUtilities.UnexpectedValue(type)
};
}
/// <summary>
/// This method combines final validation (section 7.6.5.1) and delegate compatibility (section 15.2).
/// </summary>
/// <param name="syntax">CSharpSyntaxNode of the expression requiring method group conversion.</param>
/// <param name="conversion">Conversion to be performed.</param>
/// <param name="receiverOpt">Optional receiver.</param>
/// <param name="isExtensionMethod">Method invoked as extension method.</param>
/// <param name="delegateOrFuncPtrType">Target delegate type.</param>
/// <param name="diagnostics">Where diagnostics should be added.</param>
/// <returns>True if a diagnostic has been added.</returns>
private bool MethodGroupConversionHasErrors(
SyntaxNode syntax,
Conversion conversion,
BoundExpression? receiverOpt,
bool isExtensionMethod,
bool isAddressOf,
TypeSymbol delegateOrFuncPtrType,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(delegateOrFuncPtrType.SpecialType == SpecialType.System_Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer);
Debug.Assert(conversion.Method is object);
MethodSymbol selectedMethod = conversion.Method;
var location = syntax.Location;
if (delegateOrFuncPtrType.SpecialType != SpecialType.System_Delegate)
{
if (!MethodIsCompatibleWithDelegateOrFunctionPointer(receiverOpt, isExtensionMethod, selectedMethod, delegateOrFuncPtrType, location, diagnostics) ||
MemberGroupFinalValidation(receiverOpt, selectedMethod, syntax, diagnostics, isExtensionMethod))
{
return true;
}
}
if (selectedMethod.IsConditional)
{
// CS1618: Cannot create delegate with '{0}' because it has a Conditional attribute
Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, location, selectedMethod);
return true;
}
var sourceMethod = selectedMethod as SourceOrdinaryMethodSymbol;
if (sourceMethod is object && sourceMethod.IsPartialWithoutImplementation)
{
// CS0762: Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, location, selectedMethod);
return true;
}
if ((selectedMethod.HasUnsafeParameter() || selectedMethod.ReturnType.IsUnsafe()) && ReportUnsafeIfNotAllowed(syntax, diagnostics))
{
return true;
}
if (!isAddressOf)
{
ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, selectedMethod, location, isDelegateConversion: true);
}
ReportDiagnosticsIfObsolete(diagnostics, selectedMethod, syntax, hasBaseReceiver: false);
// No use site errors, but there could be use site warnings.
// If there are use site warnings, they were reported during the overload resolution process
// that chose selectedMethod.
Debug.Assert(!selectedMethod.HasUseSiteError, "Shouldn't have reached this point if there were use site errors.");
return false;
}
/// <summary>
/// This method is a wrapper around MethodGroupConversionHasErrors. As a preliminary step,
/// it checks whether a conversion exists.
/// </summary>
private bool MethodGroupConversionDoesNotExistOrHasErrors(
BoundMethodGroup boundMethodGroup,
NamedTypeSymbol delegateType,
Location delegateMismatchLocation,
BindingDiagnosticBag diagnostics,
out Conversion conversion)
{
if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation))
{
conversion = Conversion.NoConversion;
return true;
}
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
conversion = Conversions.GetMethodGroupDelegateConversion(boundMethodGroup, delegateType, ref useSiteInfo);
diagnostics.Add(delegateMismatchLocation, useSiteInfo);
if (!conversion.Exists)
{
if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, delegateType, diagnostics))
{
// No overload for '{0}' matches delegate '{1}'
diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType);
}
return true;
}
else
{
Debug.Assert(conversion.IsValid); // i.e. if it exists, then it is valid.
// Only cares about nullness and type of receiver, so no need to worry about BoundTypeOrValueExpression.
return this.MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf: false, delegateType, diagnostics);
}
}
public ConstantValue? FoldConstantConversion(
SyntaxNode syntax,
BoundExpression source,
Conversion conversion,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
RoslynDebug.Assert(source != null);
RoslynDebug.Assert((object)destination != null);
// The diagnostics bag can be null in cases where we know ahead of time that the
// conversion will succeed without error or warning. (For example, if we have a valid
// implicit numeric conversion on a constant of numeric type.)
// SPEC: A constant expression must be the null literal or a value with one of
// SPEC: the following types: sbyte, byte, short, ushort, int, uint, long,
// SPEC: ulong, char, float, double, decimal, bool, string, or any enumeration type.
// SPEC: The following conversions are permitted in constant expressions:
// SPEC: Identity conversions
// SPEC: Numeric conversions
// SPEC: Enumeration conversions
// SPEC: Constant expression conversions
// SPEC: Implicit and explicit reference conversions, provided that the source of the conversions
// SPEC: is a constant expression that evaluates to the null value.
// SPEC VIOLATION: C# has always allowed the following, even though this does violate the rule that
// SPEC VIOLATION: a constant expression must be either the null literal, or an expression of one
// SPEC VIOLATION: of the given types.
// SPEC VIOLATION: const C c = (C)null;
// TODO: Some conversions can produce errors or warnings depending on checked/unchecked.
// TODO: Fold conversions on enums and strings too.
var sourceConstantValue = source.ConstantValue;
if (sourceConstantValue == null)
{
if (conversion.Kind == ConversionKind.DefaultLiteral)
{
return destination.GetDefaultValue();
}
else
{
return sourceConstantValue;
}
}
else if (sourceConstantValue.IsBad)
{
return sourceConstantValue;
}
if (source.HasAnyErrors)
{
return null;
}
switch (conversion.Kind)
{
case ConversionKind.Identity:
// An identity conversion to a floating-point type (for example from a cast in
// source code) changes the internal representation of the constant value
// to precisely the required precision.
switch (destination.SpecialType)
{
case SpecialType.System_Single:
return ConstantValue.Create(sourceConstantValue.SingleValue);
case SpecialType.System_Double:
return ConstantValue.Create(sourceConstantValue.DoubleValue);
default:
return sourceConstantValue;
}
case ConversionKind.NullLiteral:
return sourceConstantValue;
case ConversionKind.ImplicitConstant:
return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics);
case ConversionKind.ExplicitNumeric:
case ConversionKind.ImplicitNumeric:
case ConversionKind.ExplicitEnumeration:
case ConversionKind.ImplicitEnumeration:
// The C# specification categorizes conversion from literal zero to nullable enum as
// an Implicit Enumeration Conversion. Such a thing should not be constant folded
// because nullable enums are never constants.
if (destination.IsNullableType())
{
return null;
}
return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics);
case ConversionKind.ExplicitReference:
case ConversionKind.ImplicitReference:
return sourceConstantValue.IsNull ? sourceConstantValue : null;
}
return null;
}
private ConstantValue? FoldConstantNumericConversion(
SyntaxNode syntax,
ConstantValue sourceValue,
TypeSymbol destination,
BindingDiagnosticBag diagnostics)
{
RoslynDebug.Assert(sourceValue != null);
Debug.Assert(!sourceValue.IsBad);
SpecialType destinationType;
if ((object)destination != null && destination.IsEnumType())
{
var underlyingType = ((NamedTypeSymbol)destination).EnumUnderlyingType;
RoslynDebug.Assert((object)underlyingType != null);
Debug.Assert(underlyingType.SpecialType != SpecialType.None);
destinationType = underlyingType.SpecialType;
}
else
{
destinationType = destination.GetSpecialTypeSafe();
}
// In an unchecked context we ignore overflowing conversions on conversions from any
// integral type, float and double to any integral type. "unchecked" actually does not
// affect conversions from decimal to any integral type; if those are out of bounds then
// we always give an error regardless.
if (sourceValue.IsDecimal)
{
if (!CheckConstantBounds(destinationType, sourceValue, out _))
{
// NOTE: Dev10 puts a suffix, "M", on the constant value.
Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value + "M", destination!);
return ConstantValue.Bad;
}
}
else if (destinationType == SpecialType.System_Decimal)
{
if (!CheckConstantBounds(destinationType, sourceValue, out _))
{
Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value!, destination!);
return ConstantValue.Bad;
}
}
else if (CheckOverflowAtCompileTime)
{
if (!CheckConstantBounds(destinationType, sourceValue, out bool maySucceedAtRuntime))
{
if (maySucceedAtRuntime)
{
// Can be calculated at runtime, but is not a compile-time constant.
Error(diagnostics, ErrorCode.WRN_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!);
return null;
}
else
{
Error(diagnostics, ErrorCode.ERR_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!);
return ConstantValue.Bad;
}
}
}
else if (destinationType == SpecialType.System_IntPtr || destinationType == SpecialType.System_UIntPtr)
{
if (!CheckConstantBounds(destinationType, sourceValue, out _))
{
// Can be calculated at runtime, but is not a compile-time constant.
return null;
}
}
return ConstantValue.Create(DoUncheckedConversion(destinationType, sourceValue), destinationType);
}
private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value)
{
// Note that we keep "single" floats as doubles internally to maintain higher precision. However,
// we do not do so in an entirely "lossless" manner. When *converting* to a float, we do lose
// the precision lost due to the conversion. But when doing arithmetic, we do the arithmetic on
// the double values.
//
// An example will help. Suppose we have:
//
// const float cf1 = 1.0f;
// const float cf2 = 1.0e-15f;
// const double cd3 = cf1 - cf2;
//
// We first take the double-precision values for 1.0 and 1.0e-15 and round them to floats,
// and then turn them back into doubles. Then when we do the subtraction, we do the subtraction
// in doubles, not in floats. Had we done the subtraction in floats, we'd get 1.0; but instead we
// do it in doubles and get 0.99999999999999.
//
// Similarly, if we have
//
// const int i4 = int.MaxValue; // 2147483647
// const float cf5 = int.MaxValue; // 2147483648.0
// const double cd6 = cf5; // 2147483648.0
//
// The int is converted to float and stored internally as the double 214783648, even though the
// fully precise int would fit into a double.
unchecked
{
switch (value.Discriminator)
{
case ConstantValueTypeDiscriminator.Byte:
byte byteValue = value.ByteValue;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)byteValue;
case SpecialType.System_Char: return (char)byteValue;
case SpecialType.System_UInt16: return (ushort)byteValue;
case SpecialType.System_UInt32: return (uint)byteValue;
case SpecialType.System_UInt64: return (ulong)byteValue;
case SpecialType.System_SByte: return (sbyte)byteValue;
case SpecialType.System_Int16: return (short)byteValue;
case SpecialType.System_Int32: return (int)byteValue;
case SpecialType.System_Int64: return (long)byteValue;
case SpecialType.System_IntPtr: return (int)byteValue;
case SpecialType.System_UIntPtr: return (uint)byteValue;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)byteValue;
case SpecialType.System_Decimal: return (decimal)byteValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Char:
char charValue = value.CharValue;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)charValue;
case SpecialType.System_Char: return (char)charValue;
case SpecialType.System_UInt16: return (ushort)charValue;
case SpecialType.System_UInt32: return (uint)charValue;
case SpecialType.System_UInt64: return (ulong)charValue;
case SpecialType.System_SByte: return (sbyte)charValue;
case SpecialType.System_Int16: return (short)charValue;
case SpecialType.System_Int32: return (int)charValue;
case SpecialType.System_Int64: return (long)charValue;
case SpecialType.System_IntPtr: return (int)charValue;
case SpecialType.System_UIntPtr: return (uint)charValue;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)charValue;
case SpecialType.System_Decimal: return (decimal)charValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.UInt16:
ushort uint16Value = value.UInt16Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)uint16Value;
case SpecialType.System_Char: return (char)uint16Value;
case SpecialType.System_UInt16: return (ushort)uint16Value;
case SpecialType.System_UInt32: return (uint)uint16Value;
case SpecialType.System_UInt64: return (ulong)uint16Value;
case SpecialType.System_SByte: return (sbyte)uint16Value;
case SpecialType.System_Int16: return (short)uint16Value;
case SpecialType.System_Int32: return (int)uint16Value;
case SpecialType.System_Int64: return (long)uint16Value;
case SpecialType.System_IntPtr: return (int)uint16Value;
case SpecialType.System_UIntPtr: return (uint)uint16Value;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)uint16Value;
case SpecialType.System_Decimal: return (decimal)uint16Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.UInt32:
uint uint32Value = value.UInt32Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)uint32Value;
case SpecialType.System_Char: return (char)uint32Value;
case SpecialType.System_UInt16: return (ushort)uint32Value;
case SpecialType.System_UInt32: return (uint)uint32Value;
case SpecialType.System_UInt64: return (ulong)uint32Value;
case SpecialType.System_SByte: return (sbyte)uint32Value;
case SpecialType.System_Int16: return (short)uint32Value;
case SpecialType.System_Int32: return (int)uint32Value;
case SpecialType.System_Int64: return (long)uint32Value;
case SpecialType.System_IntPtr: return (int)uint32Value;
case SpecialType.System_UIntPtr: return (uint)uint32Value;
case SpecialType.System_Single: return (double)(float)uint32Value;
case SpecialType.System_Double: return (double)uint32Value;
case SpecialType.System_Decimal: return (decimal)uint32Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.UInt64:
ulong uint64Value = value.UInt64Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)uint64Value;
case SpecialType.System_Char: return (char)uint64Value;
case SpecialType.System_UInt16: return (ushort)uint64Value;
case SpecialType.System_UInt32: return (uint)uint64Value;
case SpecialType.System_UInt64: return (ulong)uint64Value;
case SpecialType.System_SByte: return (sbyte)uint64Value;
case SpecialType.System_Int16: return (short)uint64Value;
case SpecialType.System_Int32: return (int)uint64Value;
case SpecialType.System_Int64: return (long)uint64Value;
case SpecialType.System_IntPtr: return (int)uint64Value;
case SpecialType.System_UIntPtr: return (uint)uint64Value;
case SpecialType.System_Single: return (double)(float)uint64Value;
case SpecialType.System_Double: return (double)uint64Value;
case SpecialType.System_Decimal: return (decimal)uint64Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.NUInt:
uint nuintValue = value.UInt32Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)nuintValue;
case SpecialType.System_Char: return (char)nuintValue;
case SpecialType.System_UInt16: return (ushort)nuintValue;
case SpecialType.System_UInt32: return (uint)nuintValue;
case SpecialType.System_UInt64: return (ulong)nuintValue;
case SpecialType.System_SByte: return (sbyte)nuintValue;
case SpecialType.System_Int16: return (short)nuintValue;
case SpecialType.System_Int32: return (int)nuintValue;
case SpecialType.System_Int64: return (long)nuintValue;
case SpecialType.System_IntPtr: return (int)nuintValue;
case SpecialType.System_Single: return (double)(float)nuintValue;
case SpecialType.System_Double: return (double)nuintValue;
case SpecialType.System_Decimal: return (decimal)nuintValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.SByte:
sbyte sbyteValue = value.SByteValue;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)sbyteValue;
case SpecialType.System_Char: return (char)sbyteValue;
case SpecialType.System_UInt16: return (ushort)sbyteValue;
case SpecialType.System_UInt32: return (uint)sbyteValue;
case SpecialType.System_UInt64: return (ulong)sbyteValue;
case SpecialType.System_SByte: return (sbyte)sbyteValue;
case SpecialType.System_Int16: return (short)sbyteValue;
case SpecialType.System_Int32: return (int)sbyteValue;
case SpecialType.System_Int64: return (long)sbyteValue;
case SpecialType.System_IntPtr: return (int)sbyteValue;
case SpecialType.System_UIntPtr: return (uint)sbyteValue;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)sbyteValue;
case SpecialType.System_Decimal: return (decimal)sbyteValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Int16:
short int16Value = value.Int16Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)int16Value;
case SpecialType.System_Char: return (char)int16Value;
case SpecialType.System_UInt16: return (ushort)int16Value;
case SpecialType.System_UInt32: return (uint)int16Value;
case SpecialType.System_UInt64: return (ulong)int16Value;
case SpecialType.System_SByte: return (sbyte)int16Value;
case SpecialType.System_Int16: return (short)int16Value;
case SpecialType.System_Int32: return (int)int16Value;
case SpecialType.System_Int64: return (long)int16Value;
case SpecialType.System_IntPtr: return (int)int16Value;
case SpecialType.System_UIntPtr: return (uint)int16Value;
case SpecialType.System_Single:
case SpecialType.System_Double: return (double)int16Value;
case SpecialType.System_Decimal: return (decimal)int16Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Int32:
int int32Value = value.Int32Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)int32Value;
case SpecialType.System_Char: return (char)int32Value;
case SpecialType.System_UInt16: return (ushort)int32Value;
case SpecialType.System_UInt32: return (uint)int32Value;
case SpecialType.System_UInt64: return (ulong)int32Value;
case SpecialType.System_SByte: return (sbyte)int32Value;
case SpecialType.System_Int16: return (short)int32Value;
case SpecialType.System_Int32: return (int)int32Value;
case SpecialType.System_Int64: return (long)int32Value;
case SpecialType.System_IntPtr: return (int)int32Value;
case SpecialType.System_UIntPtr: return (uint)int32Value;
case SpecialType.System_Single: return (double)(float)int32Value;
case SpecialType.System_Double: return (double)int32Value;
case SpecialType.System_Decimal: return (decimal)int32Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Int64:
long int64Value = value.Int64Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)int64Value;
case SpecialType.System_Char: return (char)int64Value;
case SpecialType.System_UInt16: return (ushort)int64Value;
case SpecialType.System_UInt32: return (uint)int64Value;
case SpecialType.System_UInt64: return (ulong)int64Value;
case SpecialType.System_SByte: return (sbyte)int64Value;
case SpecialType.System_Int16: return (short)int64Value;
case SpecialType.System_Int32: return (int)int64Value;
case SpecialType.System_Int64: return (long)int64Value;
case SpecialType.System_IntPtr: return (int)int64Value;
case SpecialType.System_UIntPtr: return (uint)int64Value;
case SpecialType.System_Single: return (double)(float)int64Value;
case SpecialType.System_Double: return (double)int64Value;
case SpecialType.System_Decimal: return (decimal)int64Value;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.NInt:
int nintValue = value.Int32Value;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)nintValue;
case SpecialType.System_Char: return (char)nintValue;
case SpecialType.System_UInt16: return (ushort)nintValue;
case SpecialType.System_UInt32: return (uint)nintValue;
case SpecialType.System_UInt64: return (ulong)nintValue;
case SpecialType.System_SByte: return (sbyte)nintValue;
case SpecialType.System_Int16: return (short)nintValue;
case SpecialType.System_Int32: return (int)nintValue;
case SpecialType.System_Int64: return (long)nintValue;
case SpecialType.System_IntPtr: return (int)nintValue;
case SpecialType.System_UIntPtr: return (uint)nintValue;
case SpecialType.System_Single: return (double)(float)nintValue;
case SpecialType.System_Double: return (double)nintValue;
case SpecialType.System_Decimal: return (decimal)nintValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Single:
case ConstantValueTypeDiscriminator.Double:
// When converting from a floating-point type to an integral type, if the checked conversion would
// throw an overflow exception, then the unchecked conversion is undefined. So that we have
// identical behavior on every host platform, we yield a result of zero in that case.
double doubleValue = CheckConstantBounds(destinationType, value.DoubleValue, out _) ? value.DoubleValue : 0D;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)doubleValue;
case SpecialType.System_Char: return (char)doubleValue;
case SpecialType.System_UInt16: return (ushort)doubleValue;
case SpecialType.System_UInt32: return (uint)doubleValue;
case SpecialType.System_UInt64: return (ulong)doubleValue;
case SpecialType.System_SByte: return (sbyte)doubleValue;
case SpecialType.System_Int16: return (short)doubleValue;
case SpecialType.System_Int32: return (int)doubleValue;
case SpecialType.System_Int64: return (long)doubleValue;
case SpecialType.System_IntPtr: return (int)doubleValue;
case SpecialType.System_UIntPtr: return (uint)doubleValue;
case SpecialType.System_Single: return (double)(float)doubleValue;
case SpecialType.System_Double: return (double)doubleValue;
case SpecialType.System_Decimal: return (value.Discriminator == ConstantValueTypeDiscriminator.Single) ? (decimal)(float)doubleValue : (decimal)doubleValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
case ConstantValueTypeDiscriminator.Decimal:
decimal decimalValue = CheckConstantBounds(destinationType, value.DecimalValue, out _) ? value.DecimalValue : 0m;
switch (destinationType)
{
case SpecialType.System_Byte: return (byte)decimalValue;
case SpecialType.System_Char: return (char)decimalValue;
case SpecialType.System_UInt16: return (ushort)decimalValue;
case SpecialType.System_UInt32: return (uint)decimalValue;
case SpecialType.System_UInt64: return (ulong)decimalValue;
case SpecialType.System_SByte: return (sbyte)decimalValue;
case SpecialType.System_Int16: return (short)decimalValue;
case SpecialType.System_Int32: return (int)decimalValue;
case SpecialType.System_Int64: return (long)decimalValue;
case SpecialType.System_IntPtr: return (int)decimalValue;
case SpecialType.System_UIntPtr: return (uint)decimalValue;
case SpecialType.System_Single: return (double)(float)decimalValue;
case SpecialType.System_Double: return (double)decimalValue;
case SpecialType.System_Decimal: return (decimal)decimalValue;
default: throw ExceptionUtilities.UnexpectedValue(destinationType);
}
default:
throw ExceptionUtilities.UnexpectedValue(value.Discriminator);
}
}
// all cases should have been handled in the switch above.
// return value.Value;
}
public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value, out bool maySucceedAtRuntime)
{
if (value.IsBad)
{
//assume that the constant was intended to be in bounds
maySucceedAtRuntime = false;
return true;
}
// Compute whether the value fits into the bounds of the given destination type without
// error. We know that the constant will fit into either a double or a decimal, so
// convert it to one of those and then check the bounds on that.
var canonicalValue = CanonicalizeConstant(value);
return canonicalValue is decimal ?
CheckConstantBounds(destinationType, (decimal)canonicalValue, out maySucceedAtRuntime) :
CheckConstantBounds(destinationType, (double)canonicalValue, out maySucceedAtRuntime);
}
private static bool CheckConstantBounds(SpecialType destinationType, double value, out bool maySucceedAtRuntime)
{
maySucceedAtRuntime = false;
// Dev10 checks (minValue - 1) < value < (maxValue + 1).
// See ExpressionBinder::isConstantInRange.
switch (destinationType)
{
case SpecialType.System_Byte: return (byte.MinValue - 1D) < value && value < (byte.MaxValue + 1D);
case SpecialType.System_Char: return (char.MinValue - 1D) < value && value < (char.MaxValue + 1D);
case SpecialType.System_UInt16: return (ushort.MinValue - 1D) < value && value < (ushort.MaxValue + 1D);
case SpecialType.System_UInt32: return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D);
case SpecialType.System_UInt64: return (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D);
case SpecialType.System_SByte: return (sbyte.MinValue - 1D) < value && value < (sbyte.MaxValue + 1D);
case SpecialType.System_Int16: return (short.MinValue - 1D) < value && value < (short.MaxValue + 1D);
case SpecialType.System_Int32: return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D);
// Note: Using <= to compare the min value matches the native compiler.
case SpecialType.System_Int64: return (long.MinValue - 1D) <= value && value < (long.MaxValue + 1D);
case SpecialType.System_Decimal: return ((double)decimal.MinValue - 1D) < value && value < ((double)decimal.MaxValue + 1D);
case SpecialType.System_IntPtr:
maySucceedAtRuntime = (long.MinValue - 1D) < value && value < (long.MaxValue + 1D);
return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D);
case SpecialType.System_UIntPtr:
maySucceedAtRuntime = (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D);
return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D);
}
return true;
}
private static bool CheckConstantBounds(SpecialType destinationType, decimal value, out bool maySucceedAtRuntime)
{
maySucceedAtRuntime = false;
// Dev10 checks (minValue - 1) < value < (maxValue + 1).
// See ExpressionBinder::isConstantInRange.
switch (destinationType)
{
case SpecialType.System_Byte: return (byte.MinValue - 1M) < value && value < (byte.MaxValue + 1M);
case SpecialType.System_Char: return (char.MinValue - 1M) < value && value < (char.MaxValue + 1M);
case SpecialType.System_UInt16: return (ushort.MinValue - 1M) < value && value < (ushort.MaxValue + 1M);
case SpecialType.System_UInt32: return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M);
case SpecialType.System_UInt64: return (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M);
case SpecialType.System_SByte: return (sbyte.MinValue - 1M) < value && value < (sbyte.MaxValue + 1M);
case SpecialType.System_Int16: return (short.MinValue - 1M) < value && value < (short.MaxValue + 1M);
case SpecialType.System_Int32: return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M);
case SpecialType.System_Int64: return (long.MinValue - 1M) < value && value < (long.MaxValue + 1M);
case SpecialType.System_IntPtr:
maySucceedAtRuntime = (long.MinValue - 1M) < value && value < (long.MaxValue + 1M);
return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M);
case SpecialType.System_UIntPtr:
maySucceedAtRuntime = (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M);
return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M);
}
return true;
}
// Takes in a constant of any kind and returns the constant as either a double or decimal
private static object CanonicalizeConstant(ConstantValue value)
{
switch (value.Discriminator)
{
case ConstantValueTypeDiscriminator.SByte: return (decimal)value.SByteValue;
case ConstantValueTypeDiscriminator.Int16: return (decimal)value.Int16Value;
case ConstantValueTypeDiscriminator.Int32: return (decimal)value.Int32Value;
case ConstantValueTypeDiscriminator.Int64: return (decimal)value.Int64Value;
case ConstantValueTypeDiscriminator.NInt: return (decimal)value.Int32Value;
case ConstantValueTypeDiscriminator.Byte: return (decimal)value.ByteValue;
case ConstantValueTypeDiscriminator.Char: return (decimal)value.CharValue;
case ConstantValueTypeDiscriminator.UInt16: return (decimal)value.UInt16Value;
case ConstantValueTypeDiscriminator.UInt32: return (decimal)value.UInt32Value;
case ConstantValueTypeDiscriminator.UInt64: return (decimal)value.UInt64Value;
case ConstantValueTypeDiscriminator.NUInt: return (decimal)value.UInt32Value;
case ConstantValueTypeDiscriminator.Single:
case ConstantValueTypeDiscriminator.Double: return value.DoubleValue;
case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue;
default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator);
}
// all cases handled in the switch, above.
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Test/Resources/Core/SymbolsTests/netModule/netModule1.vb | ' 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.
'vbc /t:module /vbruntime- netModule1.vb
Public Class Class1
Public Class Class3
Private Class Class5
End Class
End Class
End Class
Namespace NS1
Public Class Class4
Private Class Class6
End Class
Public Class Class7
End Class
End Class
Friend Class Class8
End Class
End Namespace
| ' 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.
'vbc /t:module /vbruntime- netModule1.vb
Public Class Class1
Public Class Class3
Private Class Class5
End Class
End Class
End Class
Namespace NS1
Public Class Class4
Private Class Class6
End Class
Public Class Class7
End Class
End Class
Friend Class Class8
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/ExtractMethod/Extensions.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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal static class Extensions
{
public static bool Succeeded(this OperationStatus status)
=> status.Flag.Succeeded();
public static bool FailedWithNoBestEffortSuggestion(this OperationStatus status)
=> status.Flag.Failed() && !status.Flag.HasBestEffort();
public static bool Failed(this OperationStatus status)
=> status.Flag.Failed();
public static bool Succeeded(this OperationStatusFlag flag)
=> (flag & OperationStatusFlag.Succeeded) != 0;
public static bool Failed(this OperationStatusFlag flag)
=> !flag.Succeeded();
public static bool HasBestEffort(this OperationStatusFlag flag)
=> (flag & OperationStatusFlag.BestEffort) != 0;
public static bool HasSuggestion(this OperationStatusFlag flag)
=> (flag & OperationStatusFlag.Suggestion) != 0;
public static bool HasMask(this OperationStatusFlag flag, OperationStatusFlag mask)
=> (flag & mask) != 0x0;
public static OperationStatusFlag RemoveFlag(this OperationStatusFlag baseFlag, OperationStatusFlag flagToRemove)
=> baseFlag & ~flagToRemove;
public static ITypeSymbol? GetLambdaOrAnonymousMethodReturnType(this SemanticModel binding, SyntaxNode node)
{
var info = binding.GetSymbolInfo(node);
if (info.Symbol == null)
{
return null;
}
var methodSymbol = info.Symbol as IMethodSymbol;
if (methodSymbol?.MethodKind != MethodKind.AnonymousFunction)
{
return null;
}
return methodSymbol.ReturnType;
}
public static Task<SemanticDocument> WithSyntaxRootAsync(this SemanticDocument semanticDocument, SyntaxNode root, CancellationToken cancellationToken)
=> SemanticDocument.CreateAsync(semanticDocument.Document.WithSyntaxRoot(root), cancellationToken);
/// <summary>
/// get tokens with given annotation in current document
/// </summary>
public static SyntaxToken GetTokenWithAnnotation(this SemanticDocument document, SyntaxAnnotation annotation)
=> document.Root.GetAnnotatedNodesAndTokens(annotation).Single().AsToken();
/// <summary>
/// resolve the given symbol against compilation this snapshot has
/// </summary>
public static T ResolveType<T>(this SemanticModel semanticModel, T symbol) where T : class, ITypeSymbol
{
// Can be cleaned up when https://github.com/dotnet/roslyn/issues/38061 is resolved
var typeSymbol = (T?)symbol.GetSymbolKey().Resolve(semanticModel.Compilation).GetAnySymbol();
Contract.ThrowIfNull(typeSymbol);
return (T)typeSymbol.WithNullableAnnotation(symbol.NullableAnnotation);
}
/// <summary>
/// check whether node contains error for itself but not from its child node
/// </summary>
public static bool HasDiagnostics(this SyntaxNode node)
{
var set = new HashSet<Diagnostic>(node.GetDiagnostics());
foreach (var child in node.ChildNodes())
{
set.ExceptWith(child.GetDiagnostics());
}
return set.Count > 0;
}
public static bool FromScript(this SyntaxNode node)
{
if (node.SyntaxTree == null)
{
return false;
}
return node.SyntaxTree.Options.Kind != SourceCodeKind.Regular;
}
}
}
| // 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal static class Extensions
{
public static bool Succeeded(this OperationStatus status)
=> status.Flag.Succeeded();
public static bool FailedWithNoBestEffortSuggestion(this OperationStatus status)
=> status.Flag.Failed() && !status.Flag.HasBestEffort();
public static bool Failed(this OperationStatus status)
=> status.Flag.Failed();
public static bool Succeeded(this OperationStatusFlag flag)
=> (flag & OperationStatusFlag.Succeeded) != 0;
public static bool Failed(this OperationStatusFlag flag)
=> !flag.Succeeded();
public static bool HasBestEffort(this OperationStatusFlag flag)
=> (flag & OperationStatusFlag.BestEffort) != 0;
public static bool HasSuggestion(this OperationStatusFlag flag)
=> (flag & OperationStatusFlag.Suggestion) != 0;
public static bool HasMask(this OperationStatusFlag flag, OperationStatusFlag mask)
=> (flag & mask) != 0x0;
public static OperationStatusFlag RemoveFlag(this OperationStatusFlag baseFlag, OperationStatusFlag flagToRemove)
=> baseFlag & ~flagToRemove;
public static ITypeSymbol? GetLambdaOrAnonymousMethodReturnType(this SemanticModel binding, SyntaxNode node)
{
var info = binding.GetSymbolInfo(node);
if (info.Symbol == null)
{
return null;
}
var methodSymbol = info.Symbol as IMethodSymbol;
if (methodSymbol?.MethodKind != MethodKind.AnonymousFunction)
{
return null;
}
return methodSymbol.ReturnType;
}
public static Task<SemanticDocument> WithSyntaxRootAsync(this SemanticDocument semanticDocument, SyntaxNode root, CancellationToken cancellationToken)
=> SemanticDocument.CreateAsync(semanticDocument.Document.WithSyntaxRoot(root), cancellationToken);
/// <summary>
/// get tokens with given annotation in current document
/// </summary>
public static SyntaxToken GetTokenWithAnnotation(this SemanticDocument document, SyntaxAnnotation annotation)
=> document.Root.GetAnnotatedNodesAndTokens(annotation).Single().AsToken();
/// <summary>
/// resolve the given symbol against compilation this snapshot has
/// </summary>
public static T ResolveType<T>(this SemanticModel semanticModel, T symbol) where T : class, ITypeSymbol
{
// Can be cleaned up when https://github.com/dotnet/roslyn/issues/38061 is resolved
var typeSymbol = (T?)symbol.GetSymbolKey().Resolve(semanticModel.Compilation).GetAnySymbol();
Contract.ThrowIfNull(typeSymbol);
return (T)typeSymbol.WithNullableAnnotation(symbol.NullableAnnotation);
}
/// <summary>
/// check whether node contains error for itself but not from its child node
/// </summary>
public static bool HasDiagnostics(this SyntaxNode node)
{
var set = new HashSet<Diagnostic>(node.GetDiagnostics());
foreach (var child in node.ChildNodes())
{
set.ExceptWith(child.GetDiagnostics());
}
return set.Count > 0;
}
public static bool FromScript(this SyntaxNode node)
{
if (node.SyntaxTree == null)
{
return false;
}
return node.SyntaxTree.Options.Kind != SourceCodeKind.Regular;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Portable/Lowering/LambdaRewriter/LambdaFrame.vb | ' 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.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' A class that represents the set of variables in a scope that have been
''' captured by lambdas within that scope.
''' </summary>
Friend NotInheritable Class LambdaFrame
Inherits SynthesizedContainer
Implements ISynthesizedMethodBodyImplementationSymbol
Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol)
Private ReadOnly _topLevelMethod As MethodSymbol
Private ReadOnly _sharedConstructor As MethodSymbol
Private ReadOnly _singletonCache As FieldSymbol
Friend ReadOnly ClosureOrdinal As Integer
'NOTE: this does not include captured parent frame references
Friend ReadOnly CapturedLocals As New ArrayBuilder(Of LambdaCapturedVariable)
Private ReadOnly _constructor As SynthesizedLambdaConstructor
Friend ReadOnly TypeMap As TypeSubstitution
Private ReadOnly _scopeSyntaxOpt As SyntaxNode
Private Shared ReadOnly s_typeSubstitutionFactory As Func(Of Symbol, TypeSubstitution) =
Function(container)
Dim f = TryCast(container, LambdaFrame)
Return If(f IsNot Nothing, f.TypeMap, DirectCast(container, SynthesizedMethod).TypeMap)
End Function
Friend Shared ReadOnly CreateTypeParameter As Func(Of TypeParameterSymbol, Symbol, TypeParameterSymbol) =
Function(typeParameter, container) New SynthesizedClonedTypeParameterSymbol(typeParameter,
container,
GeneratedNames.MakeDisplayClassGenericParameterName(typeParameter.Ordinal),
s_typeSubstitutionFactory)
Friend Sub New(topLevelMethod As MethodSymbol,
scopeSyntaxOpt As SyntaxNode,
methodId As DebugId,
closureId As DebugId,
copyConstructor As Boolean,
isStatic As Boolean,
isDelegateRelaxationFrame As Boolean)
MyBase.New(topLevelMethod, MakeName(scopeSyntaxOpt, methodId, closureId, isStatic, isDelegateRelaxationFrame), topLevelMethod.ContainingType, ImmutableArray(Of NamedTypeSymbol).Empty)
If copyConstructor Then
Me._constructor = New SynthesizedLambdaCopyConstructor(scopeSyntaxOpt, Me)
Else
Me._constructor = New SynthesizedLambdaConstructor(scopeSyntaxOpt, Me)
End If
' static lambdas technically have the class scope so the scope syntax is Nothing
If isStatic Then
Me._sharedConstructor = New SynthesizedConstructorSymbol(Nothing, Me, isShared:=True, isDebuggable:=False, binder:=Nothing, diagnostics:=Nothing)
Dim cacheVariableName = GeneratedNames.MakeCachedFrameInstanceName()
Me._singletonCache = New SynthesizedLambdaCacheFieldSymbol(Me, Me, Me, cacheVariableName, topLevelMethod, Accessibility.Public, isReadOnly:=True, isShared:=True)
_scopeSyntaxOpt = Nothing
Else
_scopeSyntaxOpt = scopeSyntaxOpt
End If
If Not isDelegateRelaxationFrame Then
AssertIsClosureScopeSyntax(_scopeSyntaxOpt)
End If
Me._typeParameters = SynthesizedClonedTypeParameterSymbol.MakeTypeParameters(topLevelMethod.TypeParameters, Me, CreateTypeParameter)
Me.TypeMap = TypeSubstitution.Create(topLevelMethod, topLevelMethod.TypeParameters, Me.TypeArgumentsNoUseSiteDiagnostics)
Me._topLevelMethod = topLevelMethod
End Sub
Private Shared Function MakeName(scopeSyntaxOpt As SyntaxNode,
methodId As DebugId,
closureId As DebugId,
isStatic As Boolean,
isDelegateRelaxation As Boolean) As String
If isStatic Then
' Display class is shared among static non-generic lambdas across generations, method ordinal is -1 in that case.
' A new display class of a static generic lambda is created for each method and each generation.
Return GeneratedNames.MakeStaticLambdaDisplayClassName(methodId.Ordinal, methodId.Generation)
End If
Debug.Assert(methodId.Ordinal >= 0)
Return GeneratedNames.MakeLambdaDisplayClassName(methodId.Ordinal, methodId.Generation, closureId.Ordinal, closureId.Generation, isDelegateRelaxation)
End Function
<Conditional("DEBUG")>
Private Shared Sub AssertIsClosureScopeSyntax(syntaxOpt As SyntaxNode)
' static lambdas technically have the class scope so the scope syntax is nothing
If syntaxOpt Is Nothing Then
Return
End If
If LambdaUtilities.IsClosureScope(syntaxOpt) Then
Return
End If
Select Case syntaxOpt.Kind()
Case SyntaxKind.ObjectMemberInitializer
' TODO: Closure capturing a synthesized "with" variable
Return
End Select
ExceptionUtilities.UnexpectedValue(syntaxOpt.Kind())
End Sub
Public ReadOnly Property ScopeSyntax As SyntaxNode
Get
Return _constructor.Syntax
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
' Dev11 uses "assembly" here. No need to be different.
Return Accessibility.Friend
End Get
End Property
Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol)
Dim members = StaticCast(Of Symbol).From(CapturedLocals.AsImmutable())
If _sharedConstructor IsNot Nothing Then
members = members.AddRange(ImmutableArray.Create(Of Symbol)(_constructor, _sharedConstructor, _singletonCache))
Else
members = members.Add(_constructor)
End If
Return members
End Function
Protected Friend Overrides ReadOnly Property Constructor As MethodSymbol
Get
Return _constructor
End Get
End Property
Protected Friend ReadOnly Property SharedConstructor As MethodSymbol
Get
Return _sharedConstructor
End Get
End Property
Friend ReadOnly Property SingletonCache As FieldSymbol
Get
Return _singletonCache
End Get
End Property
Public Overrides ReadOnly Property IsSerializable As Boolean
Get
Return _singletonCache IsNot Nothing
End Get
End Property
Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol)
If _singletonCache Is Nothing Then
Return CapturedLocals
Else
Return DirectCast(CapturedLocals, IEnumerable(Of FieldSymbol)).Concat(Me._singletonCache)
End If
End Function
Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol
Dim type = ContainingAssembly.GetSpecialType(SpecialType.System_Object)
' WARN: We assume that if System_Object was not found we would never reach
' this point because the error should have been/processed generated earlier
Debug.Assert(type.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Return type
End Function
Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol
Dim type = ContainingAssembly.GetSpecialType(SpecialType.System_Object)
' WARN: We assume that if System_Object was not found we would never reach
' this point because the error should have been/processed generated earlier
Debug.Assert(type.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Return type
End Function
Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String)
Get
Return SpecializedCollections.EmptyEnumerable(Of String)()
End Get
End Property
Public Overrides ReadOnly Property TypeKind As TypeKind
Get
Return TypeKind.Class
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return Me._typeParameters.Length
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return Me._typeParameters
End Get
End Property
Friend Overrides ReadOnly Property IsInterface As Boolean
Get
Return False
End Get
End Property
Public ReadOnly Property HasMethodBodyDependency As Boolean Implements ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency
Get
' This method contains user code from the lambda.
Return True
End Get
End Property
Public ReadOnly Property Method As IMethodSymbolInternal Implements ISynthesizedMethodBodyImplementationSymbol.Method
Get
Return _topLevelMethod
End Get
End Property
End Class
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' A class that represents the set of variables in a scope that have been
''' captured by lambdas within that scope.
''' </summary>
Friend NotInheritable Class LambdaFrame
Inherits SynthesizedContainer
Implements ISynthesizedMethodBodyImplementationSymbol
Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol)
Private ReadOnly _topLevelMethod As MethodSymbol
Private ReadOnly _sharedConstructor As MethodSymbol
Private ReadOnly _singletonCache As FieldSymbol
Friend ReadOnly ClosureOrdinal As Integer
'NOTE: this does not include captured parent frame references
Friend ReadOnly CapturedLocals As New ArrayBuilder(Of LambdaCapturedVariable)
Private ReadOnly _constructor As SynthesizedLambdaConstructor
Friend ReadOnly TypeMap As TypeSubstitution
Private ReadOnly _scopeSyntaxOpt As SyntaxNode
Private Shared ReadOnly s_typeSubstitutionFactory As Func(Of Symbol, TypeSubstitution) =
Function(container)
Dim f = TryCast(container, LambdaFrame)
Return If(f IsNot Nothing, f.TypeMap, DirectCast(container, SynthesizedMethod).TypeMap)
End Function
Friend Shared ReadOnly CreateTypeParameter As Func(Of TypeParameterSymbol, Symbol, TypeParameterSymbol) =
Function(typeParameter, container) New SynthesizedClonedTypeParameterSymbol(typeParameter,
container,
GeneratedNames.MakeDisplayClassGenericParameterName(typeParameter.Ordinal),
s_typeSubstitutionFactory)
Friend Sub New(topLevelMethod As MethodSymbol,
scopeSyntaxOpt As SyntaxNode,
methodId As DebugId,
closureId As DebugId,
copyConstructor As Boolean,
isStatic As Boolean,
isDelegateRelaxationFrame As Boolean)
MyBase.New(topLevelMethod, MakeName(scopeSyntaxOpt, methodId, closureId, isStatic, isDelegateRelaxationFrame), topLevelMethod.ContainingType, ImmutableArray(Of NamedTypeSymbol).Empty)
If copyConstructor Then
Me._constructor = New SynthesizedLambdaCopyConstructor(scopeSyntaxOpt, Me)
Else
Me._constructor = New SynthesizedLambdaConstructor(scopeSyntaxOpt, Me)
End If
' static lambdas technically have the class scope so the scope syntax is Nothing
If isStatic Then
Me._sharedConstructor = New SynthesizedConstructorSymbol(Nothing, Me, isShared:=True, isDebuggable:=False, binder:=Nothing, diagnostics:=Nothing)
Dim cacheVariableName = GeneratedNames.MakeCachedFrameInstanceName()
Me._singletonCache = New SynthesizedLambdaCacheFieldSymbol(Me, Me, Me, cacheVariableName, topLevelMethod, Accessibility.Public, isReadOnly:=True, isShared:=True)
_scopeSyntaxOpt = Nothing
Else
_scopeSyntaxOpt = scopeSyntaxOpt
End If
If Not isDelegateRelaxationFrame Then
AssertIsClosureScopeSyntax(_scopeSyntaxOpt)
End If
Me._typeParameters = SynthesizedClonedTypeParameterSymbol.MakeTypeParameters(topLevelMethod.TypeParameters, Me, CreateTypeParameter)
Me.TypeMap = TypeSubstitution.Create(topLevelMethod, topLevelMethod.TypeParameters, Me.TypeArgumentsNoUseSiteDiagnostics)
Me._topLevelMethod = topLevelMethod
End Sub
Private Shared Function MakeName(scopeSyntaxOpt As SyntaxNode,
methodId As DebugId,
closureId As DebugId,
isStatic As Boolean,
isDelegateRelaxation As Boolean) As String
If isStatic Then
' Display class is shared among static non-generic lambdas across generations, method ordinal is -1 in that case.
' A new display class of a static generic lambda is created for each method and each generation.
Return GeneratedNames.MakeStaticLambdaDisplayClassName(methodId.Ordinal, methodId.Generation)
End If
Debug.Assert(methodId.Ordinal >= 0)
Return GeneratedNames.MakeLambdaDisplayClassName(methodId.Ordinal, methodId.Generation, closureId.Ordinal, closureId.Generation, isDelegateRelaxation)
End Function
<Conditional("DEBUG")>
Private Shared Sub AssertIsClosureScopeSyntax(syntaxOpt As SyntaxNode)
' static lambdas technically have the class scope so the scope syntax is nothing
If syntaxOpt Is Nothing Then
Return
End If
If LambdaUtilities.IsClosureScope(syntaxOpt) Then
Return
End If
Select Case syntaxOpt.Kind()
Case SyntaxKind.ObjectMemberInitializer
' TODO: Closure capturing a synthesized "with" variable
Return
End Select
ExceptionUtilities.UnexpectedValue(syntaxOpt.Kind())
End Sub
Public ReadOnly Property ScopeSyntax As SyntaxNode
Get
Return _constructor.Syntax
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
' Dev11 uses "assembly" here. No need to be different.
Return Accessibility.Friend
End Get
End Property
Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol)
Dim members = StaticCast(Of Symbol).From(CapturedLocals.AsImmutable())
If _sharedConstructor IsNot Nothing Then
members = members.AddRange(ImmutableArray.Create(Of Symbol)(_constructor, _sharedConstructor, _singletonCache))
Else
members = members.Add(_constructor)
End If
Return members
End Function
Protected Friend Overrides ReadOnly Property Constructor As MethodSymbol
Get
Return _constructor
End Get
End Property
Protected Friend ReadOnly Property SharedConstructor As MethodSymbol
Get
Return _sharedConstructor
End Get
End Property
Friend ReadOnly Property SingletonCache As FieldSymbol
Get
Return _singletonCache
End Get
End Property
Public Overrides ReadOnly Property IsSerializable As Boolean
Get
Return _singletonCache IsNot Nothing
End Get
End Property
Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol)
If _singletonCache Is Nothing Then
Return CapturedLocals
Else
Return DirectCast(CapturedLocals, IEnumerable(Of FieldSymbol)).Concat(Me._singletonCache)
End If
End Function
Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol
Dim type = ContainingAssembly.GetSpecialType(SpecialType.System_Object)
' WARN: We assume that if System_Object was not found we would never reach
' this point because the error should have been/processed generated earlier
Debug.Assert(type.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Return type
End Function
Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol
Dim type = ContainingAssembly.GetSpecialType(SpecialType.System_Object)
' WARN: We assume that if System_Object was not found we would never reach
' this point because the error should have been/processed generated earlier
Debug.Assert(type.GetUseSiteInfo().DiagnosticInfo Is Nothing)
Return type
End Function
Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String)
Get
Return SpecializedCollections.EmptyEnumerable(Of String)()
End Get
End Property
Public Overrides ReadOnly Property TypeKind As TypeKind
Get
Return TypeKind.Class
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return Me._typeParameters.Length
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return Me._typeParameters
End Get
End Property
Friend Overrides ReadOnly Property IsInterface As Boolean
Get
Return False
End Get
End Property
Public ReadOnly Property HasMethodBodyDependency As Boolean Implements ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency
Get
' This method contains user code from the lambda.
Return True
End Get
End Property
Public ReadOnly Property Method As IMethodSymbolInternal Implements ISynthesizedMethodBodyImplementationSymbol.Method
Get
Return _topLevelMethod
End Get
End Property
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxTokenExtensions.vb | ' 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.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Partial Friend Module SyntaxTokenExtensions
<Extension()>
Public Function IsKind(token As SyntaxToken, kind1 As SyntaxKind, kind2 As SyntaxKind) As Boolean
Return token.Kind = kind1 OrElse
token.Kind = kind2
End Function
<Extension()>
Public Function IsKind(token As SyntaxToken, ParamArray kinds As SyntaxKind()) As Boolean
Return kinds.Contains(token.Kind)
End Function
<Extension()>
Public Function IsKindOrHasMatchingText(token As SyntaxToken, kind As SyntaxKind) As Boolean
Return token.Kind = kind OrElse
token.HasMatchingText(kind)
End Function
<Extension()>
Public Function HasMatchingText(token As SyntaxToken, kind As SyntaxKind) As Boolean
Return String.Equals(token.ToString(), SyntaxFacts.GetText(kind), StringComparison.OrdinalIgnoreCase)
End Function
<Extension()>
Public Function IsCharacterLiteral(token As SyntaxToken) As Boolean
Return token.Kind = SyntaxKind.CharacterLiteralToken
End Function
<Extension()>
Public Function IsNumericLiteral(token As SyntaxToken) As Boolean
Return _
token.Kind = SyntaxKind.DateLiteralToken OrElse
token.Kind = SyntaxKind.DecimalLiteralToken OrElse
token.Kind = SyntaxKind.FloatingLiteralToken OrElse
token.Kind = SyntaxKind.IntegerLiteralToken
End Function
<Extension()>
Public Function IsNewOnRightSideOfDotOrBang(token As SyntaxToken) As Boolean
Dim expression = TryCast(token.Parent, ExpressionSyntax)
Return If(expression IsNot Nothing,
expression.IsNewOnRightSideOfDotOrBang(),
False)
End Function
<Extension()>
Public Function IsSkipped(token As SyntaxToken) As Boolean
Return TypeOf token.Parent Is SkippedTokensTriviaSyntax
End Function
<Extension()>
Public Function FirstAncestorOrSelf(token As SyntaxToken, predicate As Func(Of SyntaxNode, Boolean)) As SyntaxNode
Return token.Parent.FirstAncestorOrSelf(predicate)
End Function
<Extension()>
Public Function HasAncestor(Of T As SyntaxNode)(token As SyntaxToken) As Boolean
Return token.GetAncestor(Of T)() IsNot Nothing
End Function
''' <summary>
''' Returns true if is a given token is a child token of a certain type of parent node.
''' </summary>
''' <typeparam name="TParent">The type of the parent node.</typeparam>
''' <param name="token">The token that we are testing.</param>
''' <param name="childGetter">A function that, when given the parent node, returns the child token we are interested in.</param>
<Extension()>
Public Function IsChildToken(Of TParent As SyntaxNode)(token As SyntaxToken, childGetter As Func(Of TParent, SyntaxToken)) As Boolean
Dim ancestor = token.GetAncestor(Of TParent)()
If ancestor Is Nothing Then
Return False
End If
Dim ancestorToken = childGetter(ancestor)
Return token = ancestorToken
End Function
''' <summary>
''' Returns true if is a given token is a separator token in a given parent list.
''' </summary>
''' <typeparam name="TParent">The type of the parent node containing the separated list.</typeparam>
''' <param name="token">The token that we are testing.</param>
''' <param name="childGetter">A function that, when given the parent node, returns the separated list.</param>
<Extension()>
Public Function IsChildSeparatorToken(Of TParent As SyntaxNode, TChild As SyntaxNode)(token As SyntaxToken, childGetter As Func(Of TParent, SeparatedSyntaxList(Of TChild))) As Boolean
Dim ancestor = token.GetAncestor(Of TParent)()
If ancestor Is Nothing Then
Return False
End If
Dim separatedList = childGetter(ancestor)
For i = 0 To separatedList.SeparatorCount - 1
If separatedList.GetSeparator(i) = token Then
Return True
End If
Next
Return False
End Function
<Extension>
Public Function IsDescendantOf(token As SyntaxToken, node As SyntaxNode) As Boolean
Return token.Parent IsNot Nothing AndAlso
token.Parent.AncestorsAndSelf().Any(Function(n) n Is node)
End Function
<Extension()>
Friend Function GetInnermostDeclarationContext(node As SyntaxToken) As SyntaxNode
Dim ancestors = node.GetAncestors(Of SyntaxNode)
' In error cases where the declaration is not complete, the parser attaches the incomplete token to the
' trailing trivia of preceding block. In such cases, skip through the siblings and search upwards to find a candidate ancestor.
If TypeOf ancestors.FirstOrDefault() Is EndBlockStatementSyntax Then
' If the first ancestor is an EndBlock, the second is the matching OpenBlock, if one exists
Dim openBlock = ancestors.ElementAtOrDefault(1)
Dim closeTypeBlock = DirectCast(ancestors.First(), EndBlockStatementSyntax)
If openBlock Is Nothing Then
' case: No matching open block
' End Class
' C|
ancestors = ancestors.Skip(1)
ElseIf TypeOf openBlock Is TypeBlockSyntax Then
ancestors = FilterAncestors(ancestors, DirectCast(openBlock, TypeBlockSyntax).EndBlockStatement, closeTypeBlock)
ElseIf TypeOf openBlock Is NamespaceBlockSyntax Then
ancestors = FilterAncestors(ancestors, DirectCast(openBlock, NamespaceBlockSyntax).EndNamespaceStatement, closeTypeBlock)
ElseIf TypeOf openBlock Is EnumBlockSyntax Then
ancestors = FilterAncestors(ancestors, DirectCast(openBlock, EnumBlockSyntax).EndEnumStatement, closeTypeBlock)
End If
End If
Return ancestors.FirstOrDefault(
Function(ancestor) ancestor.IsKind(SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.EnumBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.CompilationUnit))
End Function
Private Function FilterAncestors(ancestors As IEnumerable(Of SyntaxNode),
parentEndBlock As EndBlockStatementSyntax,
precedingEndBlock As EndBlockStatementSyntax) As IEnumerable(Of SyntaxNode)
If parentEndBlock.Equals(precedingEndBlock) Then
' case: the preceding end block has a matching open block and the declaration context for 'C' is 'N1'
' Namespace N1
' Class C1
'
' End Class
' C|
' End Namespace
Return ancestors.Skip(2)
Else
' case: mismatched end block and the declaration context for 'C' is 'N1'
' Namespace N1
' End Class
' C|
' End Namespace
Return ancestors.Skip(1)
End If
End Function
<Extension()>
Public Function GetContainingMember(token As SyntaxToken) As DeclarationStatementSyntax
Return token.GetAncestors(Of DeclarationStatementSyntax) _
.FirstOrDefault(Function(a)
Return a.IsMemberDeclaration() OrElse
(a.IsMemberBlock() AndAlso a.GetMemberBlockBegin().IsMemberDeclaration())
End Function)
End Function
<Extension()>
Public Function GetContainingMemberBlockBegin(token As SyntaxToken) As StatementSyntax
Return token.GetContainingMember().GetMemberBlockBegin()
End Function
''' <summary>
''' Determines whether the given SyntaxToken is the first token on a line
''' </summary>
<Extension()>
Public Function IsFirstTokenOnLine(token As SyntaxToken) As Boolean
Dim previousToken = token.GetPreviousToken(includeSkipped:=True, includeDirectives:=True, includeDocumentationComments:=True)
If previousToken.Kind = SyntaxKind.None Then
Return True
End If
Dim text = token.SyntaxTree.GetText()
Dim tokenLine = text.Lines.IndexOf(token.SpanStart)
Dim previousTokenLine = text.Lines.IndexOf(previousToken.SpanStart)
Return tokenLine > previousTokenLine
End Function
<Extension()>
Public Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean
Return VisualBasicSyntaxFacts.Instance.SpansPreprocessorDirective(tokens)
End Function
<Extension()>
Public Function GetPreviousTokenIfTouchingWord(token As SyntaxToken, position As Integer) As SyntaxToken
Return If(token.IntersectsWith(position) AndAlso IsWord(token),
token.GetPreviousToken(includeSkipped:=True),
token)
End Function
<Extension>
Public Function IsWord(token As SyntaxToken) As Boolean
Return VisualBasicSyntaxFacts.Instance.IsWord(token)
End Function
<Extension()>
Public Function IntersectsWith(token As SyntaxToken, position As Integer) As Boolean
Return token.Span.IntersectsWith(position)
End Function
<Extension()>
Public Function GetNextNonZeroWidthTokenOrEndOfFile(token As SyntaxToken) As SyntaxToken
Dim nextToken = token.GetNextToken()
Return If(nextToken.Kind = SyntaxKind.None, token.GetAncestor(Of CompilationUnitSyntax)().EndOfFileToken, nextToken)
End Function
<Extension>
Public Function IsValidAttributeTarget(token As SyntaxToken) As Boolean
Return token.Kind() = SyntaxKind.AssemblyKeyword OrElse
token.Kind() = SyntaxKind.ModuleKeyword
End Function
End Module
End Namespace
| ' 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.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Partial Friend Module SyntaxTokenExtensions
<Extension()>
Public Function IsKind(token As SyntaxToken, kind1 As SyntaxKind, kind2 As SyntaxKind) As Boolean
Return token.Kind = kind1 OrElse
token.Kind = kind2
End Function
<Extension()>
Public Function IsKind(token As SyntaxToken, ParamArray kinds As SyntaxKind()) As Boolean
Return kinds.Contains(token.Kind)
End Function
<Extension()>
Public Function IsKindOrHasMatchingText(token As SyntaxToken, kind As SyntaxKind) As Boolean
Return token.Kind = kind OrElse
token.HasMatchingText(kind)
End Function
<Extension()>
Public Function HasMatchingText(token As SyntaxToken, kind As SyntaxKind) As Boolean
Return String.Equals(token.ToString(), SyntaxFacts.GetText(kind), StringComparison.OrdinalIgnoreCase)
End Function
<Extension()>
Public Function IsCharacterLiteral(token As SyntaxToken) As Boolean
Return token.Kind = SyntaxKind.CharacterLiteralToken
End Function
<Extension()>
Public Function IsNumericLiteral(token As SyntaxToken) As Boolean
Return _
token.Kind = SyntaxKind.DateLiteralToken OrElse
token.Kind = SyntaxKind.DecimalLiteralToken OrElse
token.Kind = SyntaxKind.FloatingLiteralToken OrElse
token.Kind = SyntaxKind.IntegerLiteralToken
End Function
<Extension()>
Public Function IsNewOnRightSideOfDotOrBang(token As SyntaxToken) As Boolean
Dim expression = TryCast(token.Parent, ExpressionSyntax)
Return If(expression IsNot Nothing,
expression.IsNewOnRightSideOfDotOrBang(),
False)
End Function
<Extension()>
Public Function IsSkipped(token As SyntaxToken) As Boolean
Return TypeOf token.Parent Is SkippedTokensTriviaSyntax
End Function
<Extension()>
Public Function FirstAncestorOrSelf(token As SyntaxToken, predicate As Func(Of SyntaxNode, Boolean)) As SyntaxNode
Return token.Parent.FirstAncestorOrSelf(predicate)
End Function
<Extension()>
Public Function HasAncestor(Of T As SyntaxNode)(token As SyntaxToken) As Boolean
Return token.GetAncestor(Of T)() IsNot Nothing
End Function
''' <summary>
''' Returns true if is a given token is a child token of a certain type of parent node.
''' </summary>
''' <typeparam name="TParent">The type of the parent node.</typeparam>
''' <param name="token">The token that we are testing.</param>
''' <param name="childGetter">A function that, when given the parent node, returns the child token we are interested in.</param>
<Extension()>
Public Function IsChildToken(Of TParent As SyntaxNode)(token As SyntaxToken, childGetter As Func(Of TParent, SyntaxToken)) As Boolean
Dim ancestor = token.GetAncestor(Of TParent)()
If ancestor Is Nothing Then
Return False
End If
Dim ancestorToken = childGetter(ancestor)
Return token = ancestorToken
End Function
''' <summary>
''' Returns true if is a given token is a separator token in a given parent list.
''' </summary>
''' <typeparam name="TParent">The type of the parent node containing the separated list.</typeparam>
''' <param name="token">The token that we are testing.</param>
''' <param name="childGetter">A function that, when given the parent node, returns the separated list.</param>
<Extension()>
Public Function IsChildSeparatorToken(Of TParent As SyntaxNode, TChild As SyntaxNode)(token As SyntaxToken, childGetter As Func(Of TParent, SeparatedSyntaxList(Of TChild))) As Boolean
Dim ancestor = token.GetAncestor(Of TParent)()
If ancestor Is Nothing Then
Return False
End If
Dim separatedList = childGetter(ancestor)
For i = 0 To separatedList.SeparatorCount - 1
If separatedList.GetSeparator(i) = token Then
Return True
End If
Next
Return False
End Function
<Extension>
Public Function IsDescendantOf(token As SyntaxToken, node As SyntaxNode) As Boolean
Return token.Parent IsNot Nothing AndAlso
token.Parent.AncestorsAndSelf().Any(Function(n) n Is node)
End Function
<Extension()>
Friend Function GetInnermostDeclarationContext(node As SyntaxToken) As SyntaxNode
Dim ancestors = node.GetAncestors(Of SyntaxNode)
' In error cases where the declaration is not complete, the parser attaches the incomplete token to the
' trailing trivia of preceding block. In such cases, skip through the siblings and search upwards to find a candidate ancestor.
If TypeOf ancestors.FirstOrDefault() Is EndBlockStatementSyntax Then
' If the first ancestor is an EndBlock, the second is the matching OpenBlock, if one exists
Dim openBlock = ancestors.ElementAtOrDefault(1)
Dim closeTypeBlock = DirectCast(ancestors.First(), EndBlockStatementSyntax)
If openBlock Is Nothing Then
' case: No matching open block
' End Class
' C|
ancestors = ancestors.Skip(1)
ElseIf TypeOf openBlock Is TypeBlockSyntax Then
ancestors = FilterAncestors(ancestors, DirectCast(openBlock, TypeBlockSyntax).EndBlockStatement, closeTypeBlock)
ElseIf TypeOf openBlock Is NamespaceBlockSyntax Then
ancestors = FilterAncestors(ancestors, DirectCast(openBlock, NamespaceBlockSyntax).EndNamespaceStatement, closeTypeBlock)
ElseIf TypeOf openBlock Is EnumBlockSyntax Then
ancestors = FilterAncestors(ancestors, DirectCast(openBlock, EnumBlockSyntax).EndEnumStatement, closeTypeBlock)
End If
End If
Return ancestors.FirstOrDefault(
Function(ancestor) ancestor.IsKind(SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.EnumBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.CompilationUnit))
End Function
Private Function FilterAncestors(ancestors As IEnumerable(Of SyntaxNode),
parentEndBlock As EndBlockStatementSyntax,
precedingEndBlock As EndBlockStatementSyntax) As IEnumerable(Of SyntaxNode)
If parentEndBlock.Equals(precedingEndBlock) Then
' case: the preceding end block has a matching open block and the declaration context for 'C' is 'N1'
' Namespace N1
' Class C1
'
' End Class
' C|
' End Namespace
Return ancestors.Skip(2)
Else
' case: mismatched end block and the declaration context for 'C' is 'N1'
' Namespace N1
' End Class
' C|
' End Namespace
Return ancestors.Skip(1)
End If
End Function
<Extension()>
Public Function GetContainingMember(token As SyntaxToken) As DeclarationStatementSyntax
Return token.GetAncestors(Of DeclarationStatementSyntax) _
.FirstOrDefault(Function(a)
Return a.IsMemberDeclaration() OrElse
(a.IsMemberBlock() AndAlso a.GetMemberBlockBegin().IsMemberDeclaration())
End Function)
End Function
<Extension()>
Public Function GetContainingMemberBlockBegin(token As SyntaxToken) As StatementSyntax
Return token.GetContainingMember().GetMemberBlockBegin()
End Function
''' <summary>
''' Determines whether the given SyntaxToken is the first token on a line
''' </summary>
<Extension()>
Public Function IsFirstTokenOnLine(token As SyntaxToken) As Boolean
Dim previousToken = token.GetPreviousToken(includeSkipped:=True, includeDirectives:=True, includeDocumentationComments:=True)
If previousToken.Kind = SyntaxKind.None Then
Return True
End If
Dim text = token.SyntaxTree.GetText()
Dim tokenLine = text.Lines.IndexOf(token.SpanStart)
Dim previousTokenLine = text.Lines.IndexOf(previousToken.SpanStart)
Return tokenLine > previousTokenLine
End Function
<Extension()>
Public Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean
Return VisualBasicSyntaxFacts.Instance.SpansPreprocessorDirective(tokens)
End Function
<Extension()>
Public Function GetPreviousTokenIfTouchingWord(token As SyntaxToken, position As Integer) As SyntaxToken
Return If(token.IntersectsWith(position) AndAlso IsWord(token),
token.GetPreviousToken(includeSkipped:=True),
token)
End Function
<Extension>
Public Function IsWord(token As SyntaxToken) As Boolean
Return VisualBasicSyntaxFacts.Instance.IsWord(token)
End Function
<Extension()>
Public Function IntersectsWith(token As SyntaxToken, position As Integer) As Boolean
Return token.Span.IntersectsWith(position)
End Function
<Extension()>
Public Function GetNextNonZeroWidthTokenOrEndOfFile(token As SyntaxToken) As SyntaxToken
Dim nextToken = token.GetNextToken()
Return If(nextToken.Kind = SyntaxKind.None, token.GetAncestor(Of CompilationUnitSyntax)().EndOfFileToken, nextToken)
End Function
<Extension>
Public Function IsValidAttributeTarget(token As SyntaxToken) As Boolean
Return token.Kind() = SyntaxKind.AssemblyKeyword OrElse
token.Kind() = SyntaxKind.ModuleKeyword
End Function
End Module
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Test/WinRT/Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests.csproj | <?xml version="1.0" encoding="utf-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. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen</RootNamespace>
<TargetFramework>net472</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project>
| <?xml version="1.0" encoding="utf-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. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen</RootNamespace>
<TargetFramework>net472</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project>
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/EventHandling/AddHandlerKeywordRecommender.vb | ' 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.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.EventHandling
''' <summary>
''' Recommends the "AddHandler" keyword.
''' </summary>
Friend Class AddHandlerKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(CreateRecommendedKeywordForIntrinsicOperator(
SyntaxKind.AddHandlerKeyword, VBFeaturesResources.AddHandler_statement, Glyph.Keyword, New AddHandlerStatementDocumentation()))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsSingleLineStatementContext OrElse context.CanDeclareCustomEventAccessor(SyntaxKind.AddHandlerAccessorBlock),
s_keywords,
ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.EventHandling
''' <summary>
''' Recommends the "AddHandler" keyword.
''' </summary>
Friend Class AddHandlerKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(CreateRecommendedKeywordForIntrinsicOperator(
SyntaxKind.AddHandlerKeyword, VBFeaturesResources.AddHandler_statement, Glyph.Keyword, New AddHandlerStatementDocumentation()))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsSingleLineStatementContext OrElse context.CanDeclareCustomEventAccessor(SyntaxKind.AddHandlerAccessorBlock),
s_keywords,
ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Core/Portable/PEWriter/LocalScope.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;
namespace Microsoft.Cci
{
/// <summary>
/// A range of CLR IL operations that comprise a lexical scope.
/// </summary>
internal struct LocalScope
{
/// <summary>
/// The offset of the first operation in the scope.
/// </summary>
public readonly int StartOffset;
/// <summary>
/// The offset of the first operation outside of the scope, or the method body length.
/// </summary>
public readonly int EndOffset;
private readonly ImmutableArray<ILocalDefinition> _constants;
private readonly ImmutableArray<ILocalDefinition> _locals;
internal LocalScope(int offset, int endOffset, ImmutableArray<ILocalDefinition> constants, ImmutableArray<ILocalDefinition> locals)
{
Debug.Assert(!locals.Any(l => l.Name == null));
Debug.Assert(!constants.Any(c => c.Name == null));
Debug.Assert(offset >= 0);
Debug.Assert(endOffset > offset);
StartOffset = offset;
EndOffset = endOffset;
_constants = constants;
_locals = locals;
}
public int Length => EndOffset - StartOffset;
/// <summary>
/// Returns zero or more local constant definitions that are local to the given scope.
/// </summary>
public ImmutableArray<ILocalDefinition> Constants => _constants.NullToEmpty();
/// <summary>
/// Returns zero or more local variable definitions that are local to the given scope.
/// </summary>
public ImmutableArray<ILocalDefinition> Variables => _locals.NullToEmpty();
}
}
| // 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;
namespace Microsoft.Cci
{
/// <summary>
/// A range of CLR IL operations that comprise a lexical scope.
/// </summary>
internal struct LocalScope
{
/// <summary>
/// The offset of the first operation in the scope.
/// </summary>
public readonly int StartOffset;
/// <summary>
/// The offset of the first operation outside of the scope, or the method body length.
/// </summary>
public readonly int EndOffset;
private readonly ImmutableArray<ILocalDefinition> _constants;
private readonly ImmutableArray<ILocalDefinition> _locals;
internal LocalScope(int offset, int endOffset, ImmutableArray<ILocalDefinition> constants, ImmutableArray<ILocalDefinition> locals)
{
Debug.Assert(!locals.Any(l => l.Name == null));
Debug.Assert(!constants.Any(c => c.Name == null));
Debug.Assert(offset >= 0);
Debug.Assert(endOffset > offset);
StartOffset = offset;
EndOffset = endOffset;
_constants = constants;
_locals = locals;
}
public int Length => EndOffset - StartOffset;
/// <summary>
/// Returns zero or more local constant definitions that are local to the given scope.
/// </summary>
public ImmutableArray<ILocalDefinition> Constants => _constants.NullToEmpty();
/// <summary>
/// Returns zero or more local variable definitions that are local to the given scope.
/// </summary>
public ImmutableArray<ILocalDefinition> Variables => _locals.NullToEmpty();
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/LoadingEvents.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.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System;
using System.Linq;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE
{
public class LoadingEvents : CSharpTestBase
{
[Fact]
public void LoadNonGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("NonGeneric");
CheckInstanceAndStaticEvents(@class, "System.Action");
}
[Fact]
public void LoadGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("Generic");
CheckInstanceAndStaticEvents(@class, "System.Action<T>");
}
[Fact]
public void LoadClosedGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("ClosedGeneric");
CheckInstanceAndStaticEvents(@class, "System.Action<System.Int32>");
}
private static void CheckInstanceAndStaticEvents(NamedTypeSymbol @class, string eventTypeDisplayString)
{
var instanceEvent = @class.GetMember<EventSymbol>("InstanceEvent");
Assert.Equal(SymbolKind.Event, instanceEvent.Kind);
Assert.False(instanceEvent.IsStatic);
Assert.Equal(eventTypeDisplayString, instanceEvent.Type.ToTestDisplayString());
CheckAccessorShape(instanceEvent.AddMethod, instanceEvent);
CheckAccessorShape(instanceEvent.RemoveMethod, instanceEvent);
var staticEvent = @class.GetMember<EventSymbol>("StaticEvent");
Assert.Equal(SymbolKind.Event, staticEvent.Kind);
Assert.True(staticEvent.IsStatic);
Assert.Equal(eventTypeDisplayString, staticEvent.Type.ToTestDisplayString());
CheckAccessorShape(staticEvent.AddMethod, staticEvent);
CheckAccessorShape(staticEvent.RemoveMethod, staticEvent);
}
private static void CheckAccessorShape(MethodSymbol accessor, EventSymbol @event)
{
Assert.Same(@event, accessor.AssociatedSymbol);
switch (accessor.MethodKind)
{
case MethodKind.EventAdd:
Assert.Same(@event.AddMethod, accessor);
break;
case MethodKind.EventRemove:
Assert.Same(@event.RemoveMethod, accessor);
break;
default:
Assert.False(true, string.Format("Accessor {0} has unexpected MethodKind {1}", accessor, accessor.MethodKind));
break;
}
Assert.Equal(@event.IsAbstract, accessor.IsAbstract);
Assert.Equal(@event.IsOverride, @accessor.IsOverride);
Assert.Equal(@event.IsVirtual, @accessor.IsVirtual);
Assert.Equal(@event.IsSealed, @accessor.IsSealed);
Assert.Equal(@event.IsExtern, @accessor.IsExtern);
Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType);
Assert.Equal(@event.Type, accessor.Parameters.Single().Type);
}
[Fact]
public void LoadSignatureMismatchEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("SignatureMismatch");
var mismatchedAddEvent = @class.GetMember<EventSymbol>("AddMismatch");
var mismatchedRemoveEvent = @class.GetMember<EventSymbol>("RemoveMismatch");
Assert.NotEqual(mismatchedAddEvent.Type, mismatchedAddEvent.AddMethod.Parameters.Single().Type);
Assert.True(mismatchedAddEvent.MustCallMethodsDirectly);
Assert.NotEqual(mismatchedRemoveEvent.Type, mismatchedRemoveEvent.RemoveMethod.Parameters.Single().Type);
Assert.True(mismatchedRemoveEvent.MustCallMethodsDirectly);
}
[Fact]
public void LoadMissingParameterEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("AccessorMissingParameter");
var noParamAddEvent = @class.GetMember<EventSymbol>("AddNoParam");
var noParamRemoveEvent = @class.GetMember<EventSymbol>("RemoveNoParam");
Assert.Equal(0, noParamAddEvent.AddMethod.Parameters.Length);
Assert.True(noParamAddEvent.MustCallMethodsDirectly);
Assert.Equal(0, noParamRemoveEvent.RemoveMethod.Parameters.Length);
Assert.True(noParamRemoveEvent.MustCallMethodsDirectly);
}
[Fact]
public void LoadNonDelegateEvent()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("NonDelegateEvent");
var nonDelegateEvent = @class.GetMember<EventSymbol>("NonDelegate");
Assert.Equal(SpecialType.System_Int32, nonDelegateEvent.Type.SpecialType);
}
[Fact]
public void TestExplicitImplementationSimple()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Class").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classEvent = (EventSymbol)@class.GetMembers("Interface.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceEvent, explicitImpl);
}
[Fact]
public void TestExplicitImplementationGeneric()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Generic").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceEvent = (EventSymbol)substitutedInterface.GetMembers("Event").Single();
Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition);
var classEvent = (EventSymbol)@class.GetMembers("IGeneric<S>.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceEvent, explicitImpl);
}
[Fact]
public void TestExplicitImplementationConstructed()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Constructed").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceEvent = (EventSymbol)substitutedInterface.GetMembers("Event").Single();
Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition);
var classEvent = (EventSymbol)@class.GetMembers("IGeneric<System.Int32>.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceEvent, explicitImpl);
}
/// <summary>
/// A type def explicitly implements an interface, also a type def, but only
/// indirectly, via a type ref.
/// </summary>
[Fact]
public void TestExplicitImplementationDefRefDef()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var defInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
var defInterfaceEvent = (EventSymbol)defInterface.GetMembers("Event").Single();
var refInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGenericInterface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
Assert.True(refInterface.Interfaces().Contains(defInterface));
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IndirectImplementation").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var classInterfacesConstructedFrom = @class.Interfaces().Select(i => i.ConstructedFrom);
Assert.Equal(2, classInterfacesConstructedFrom.Count());
Assert.Contains(defInterface, classInterfacesConstructedFrom);
Assert.Contains(refInterface, classInterfacesConstructedFrom);
var classEvent = (EventSymbol)@class.GetMembers("Interface.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(defInterfaceEvent, explicitImpl);
}
/// <summary>
/// In metadata, nested types implicitly share all type parameters of their containing types.
/// This results in some extra computations when mapping a type parameter position to a type
/// parameter symbol.
/// </summary>
[Fact]
public void TestTypeParameterPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var outerInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric2").Single();
Assert.Equal(1, outerInterface.Arity);
Assert.Equal(TypeKind.Interface, outerInterface.TypeKind);
var outerInterfaceEvent = outerInterface.GetMembers().Single(m => m.Kind == SymbolKind.Event);
var outerClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Outer").Single();
Assert.Equal(1, outerClass.Arity);
Assert.Equal(TypeKind.Class, outerClass.TypeKind);
var innerInterface = (NamedTypeSymbol)outerClass.GetTypeMembers("IInner").Single();
Assert.Equal(1, innerInterface.Arity);
Assert.Equal(TypeKind.Interface, innerInterface.TypeKind);
var innerInterfaceEvent = innerInterface.GetMembers().Single(m => m.Kind == SymbolKind.Event);
var innerClass1 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner1").Single();
CheckInnerClassHelper(innerClass1, "IGeneric2<A>.Event", outerInterfaceEvent);
var innerClass2 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner2").Single();
CheckInnerClassHelper(innerClass2, "IGeneric2<T>.Event", outerInterfaceEvent);
var innerClass3 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner3").Single();
CheckInnerClassHelper(innerClass3, "Outer<T>.IInner<C>.Event", innerInterfaceEvent);
var innerClass4 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner4").Single();
CheckInnerClassHelper(innerClass4, "Outer<T>.IInner<T>.Event", innerInterfaceEvent);
}
private static void CheckInnerClassHelper(NamedTypeSymbol innerClass, string methodName, Symbol interfaceEvent)
{
var @interface = interfaceEvent.ContainingType;
Assert.Equal(1, innerClass.Arity);
Assert.Equal(TypeKind.Class, innerClass.TypeKind);
Assert.Equal(@interface, innerClass.Interfaces().Single().ConstructedFrom);
var innerClassEvent = (EventSymbol)innerClass.GetMembers(methodName).Single();
var innerClassImplementingEvent = innerClassEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceEvent, innerClassImplementingEvent.OriginalDefinition);
Assert.Equal(@interface, innerClassImplementingEvent.ContainingType.ConstructedFrom);
}
// NOTE: results differ from corresponding property test.
[WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")]
[Fact]
public void TestMixedAccessorModifiers()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.Events);
var globalNamespace = assembly.GlobalNamespace;
var type = globalNamespace.GetMember<NamedTypeSymbol>("AccessorModifierMismatch");
const VirtualnessModifiers @none = VirtualnessModifiers.None;
const VirtualnessModifiers @abstract = VirtualnessModifiers.Abstract;
const VirtualnessModifiers @virtual = VirtualnessModifiers.Virtual;
const VirtualnessModifiers @override = VirtualnessModifiers.Override;
const VirtualnessModifiers @sealed = VirtualnessModifiers.Sealed;
VirtualnessModifiers[] modList = new[]
{
@none,
@abstract,
@virtual,
@override,
@sealed,
};
int length = 1 + modList.Cast<int>().Max();
VirtualnessModifiers[,] expected = new VirtualnessModifiers[length, length];
expected[(int)@none, (int)@none] = @none;
expected[(int)@none, (int)@abstract] = @abstract;
expected[(int)@none, (int)@virtual] = @virtual;
expected[(int)@none, (int)@override] = @override;
expected[(int)@none, (int)@sealed] = @sealed;
expected[(int)@abstract, (int)@none] = @abstract;
expected[(int)@abstract, (int)@abstract] = @abstract;
expected[(int)@abstract, (int)@virtual] = @abstract;
expected[(int)@abstract, (int)@override] = @abstract | @override;
expected[(int)@abstract, (int)@sealed] = @abstract | @sealed;
expected[(int)@virtual, (int)@none] = @virtual;
expected[(int)@virtual, (int)@abstract] = @abstract;
expected[(int)@virtual, (int)@virtual] = @virtual;
expected[(int)@virtual, (int)@override] = @override;
expected[(int)@virtual, (int)@sealed] = @sealed;
expected[(int)@override, (int)@none] = @override;
expected[(int)@override, (int)@abstract] = @override | @abstract;
expected[(int)@override, (int)@virtual] = @override;
expected[(int)@override, (int)@override] = @override;
expected[(int)@override, (int)@sealed] = @sealed;
expected[(int)@sealed, (int)@none] = @sealed;
expected[(int)@sealed, (int)@abstract] = @abstract | @sealed;
expected[(int)@sealed, (int)@virtual] = @sealed;
expected[(int)@sealed, (int)@override] = @sealed;
expected[(int)@sealed, (int)@sealed] = @sealed;
// Table should be symmetrical.
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
Assert.Equal(expected[i, j], expected[j, i]);
}
}
foreach (var mod1 in modList)
{
foreach (var mod2 in modList)
{
var @event = type.GetMember<EventSymbol>(mod1.ToString() + mod2.ToString());
var addMethod = @event.AddMethod;
var removeMethod = @event.RemoveMethod;
Assert.Equal(mod1, GetVirtualnessModifiers(addMethod));
Assert.Equal(mod2, GetVirtualnessModifiers(removeMethod));
Assert.Equal(expected[(int)mod1, (int)mod2], GetVirtualnessModifiers(@event));
}
}
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField()
{
var source = @"
public class C
{
public event System.Action E;
}
";
var reference = CreateCompilation(source).EmitToImageReference();
var comp = CreateCompilation("", new[] { reference }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var @event = type.GetMember<PEEventSymbol>("E");
Assert.True(@event.HasAssociatedField);
var field = @event.AssociatedField;
Assert.NotNull(field);
Assert.Equal(@event, field.AssociatedSymbol);
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField_MultipleFields()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private int32 E
.field private class [mscorlib]System.Action E
.method public hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
} // end of class C
";
var ilRef = CompileIL(ilSource);
var comp = CreateCompilation("", new[] { ilRef }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var @event = type.GetMembers().OfType<PEEventSymbol>().Single();
Assert.True(@event.HasAssociatedField);
var field = @event.AssociatedField;
Assert.NotNull(field);
Assert.Equal(@event, field.AssociatedSymbol);
Assert.Equal(@event.Type, field.Type);
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField_DuplicateEvents()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action E
.method public hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
} // end of class C
";
var ilRef = CompileIL(ilSource);
var comp = CreateCompilation("", new[] { ilRef }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var events = type.GetMembers().OfType<PEEventSymbol>();
Assert.Equal(2, events.Count());
AssertEx.All(events, e => e.HasAssociatedField);
var field = events.First().AssociatedField;
Assert.NotNull(field);
AssertEx.All(events, e => e.AssociatedField == field);
Assert.Contains(field.AssociatedSymbol, events);
}
[Flags]
private enum VirtualnessModifiers
{
None = 0,
Abstract = 1,
Virtual = 2,
Override = 4,
Sealed = 8, //actually indicates sealed override
}
private static VirtualnessModifiers GetVirtualnessModifiers(Symbol symbol)
{
VirtualnessModifiers mods = VirtualnessModifiers.None;
if (symbol.IsAbstract) mods |= VirtualnessModifiers.Abstract;
if (symbol.IsVirtual) mods |= VirtualnessModifiers.Virtual;
if (symbol.IsSealed) mods |= VirtualnessModifiers.Sealed;
else if (symbol.IsOverride) mods |= VirtualnessModifiers.Override;
return mods;
}
}
}
| // 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.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System;
using System.Linq;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE
{
public class LoadingEvents : CSharpTestBase
{
[Fact]
public void LoadNonGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("NonGeneric");
CheckInstanceAndStaticEvents(@class, "System.Action");
}
[Fact]
public void LoadGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("Generic");
CheckInstanceAndStaticEvents(@class, "System.Action<T>");
}
[Fact]
public void LoadClosedGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("ClosedGeneric");
CheckInstanceAndStaticEvents(@class, "System.Action<System.Int32>");
}
private static void CheckInstanceAndStaticEvents(NamedTypeSymbol @class, string eventTypeDisplayString)
{
var instanceEvent = @class.GetMember<EventSymbol>("InstanceEvent");
Assert.Equal(SymbolKind.Event, instanceEvent.Kind);
Assert.False(instanceEvent.IsStatic);
Assert.Equal(eventTypeDisplayString, instanceEvent.Type.ToTestDisplayString());
CheckAccessorShape(instanceEvent.AddMethod, instanceEvent);
CheckAccessorShape(instanceEvent.RemoveMethod, instanceEvent);
var staticEvent = @class.GetMember<EventSymbol>("StaticEvent");
Assert.Equal(SymbolKind.Event, staticEvent.Kind);
Assert.True(staticEvent.IsStatic);
Assert.Equal(eventTypeDisplayString, staticEvent.Type.ToTestDisplayString());
CheckAccessorShape(staticEvent.AddMethod, staticEvent);
CheckAccessorShape(staticEvent.RemoveMethod, staticEvent);
}
private static void CheckAccessorShape(MethodSymbol accessor, EventSymbol @event)
{
Assert.Same(@event, accessor.AssociatedSymbol);
switch (accessor.MethodKind)
{
case MethodKind.EventAdd:
Assert.Same(@event.AddMethod, accessor);
break;
case MethodKind.EventRemove:
Assert.Same(@event.RemoveMethod, accessor);
break;
default:
Assert.False(true, string.Format("Accessor {0} has unexpected MethodKind {1}", accessor, accessor.MethodKind));
break;
}
Assert.Equal(@event.IsAbstract, accessor.IsAbstract);
Assert.Equal(@event.IsOverride, @accessor.IsOverride);
Assert.Equal(@event.IsVirtual, @accessor.IsVirtual);
Assert.Equal(@event.IsSealed, @accessor.IsSealed);
Assert.Equal(@event.IsExtern, @accessor.IsExtern);
Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType);
Assert.Equal(@event.Type, accessor.Parameters.Single().Type);
}
[Fact]
public void LoadSignatureMismatchEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("SignatureMismatch");
var mismatchedAddEvent = @class.GetMember<EventSymbol>("AddMismatch");
var mismatchedRemoveEvent = @class.GetMember<EventSymbol>("RemoveMismatch");
Assert.NotEqual(mismatchedAddEvent.Type, mismatchedAddEvent.AddMethod.Parameters.Single().Type);
Assert.True(mismatchedAddEvent.MustCallMethodsDirectly);
Assert.NotEqual(mismatchedRemoveEvent.Type, mismatchedRemoveEvent.RemoveMethod.Parameters.Single().Type);
Assert.True(mismatchedRemoveEvent.MustCallMethodsDirectly);
}
[Fact]
public void LoadMissingParameterEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("AccessorMissingParameter");
var noParamAddEvent = @class.GetMember<EventSymbol>("AddNoParam");
var noParamRemoveEvent = @class.GetMember<EventSymbol>("RemoveNoParam");
Assert.Equal(0, noParamAddEvent.AddMethod.Parameters.Length);
Assert.True(noParamAddEvent.MustCallMethodsDirectly);
Assert.Equal(0, noParamRemoveEvent.RemoveMethod.Parameters.Length);
Assert.True(noParamRemoveEvent.MustCallMethodsDirectly);
}
[Fact]
public void LoadNonDelegateEvent()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("NonDelegateEvent");
var nonDelegateEvent = @class.GetMember<EventSymbol>("NonDelegate");
Assert.Equal(SpecialType.System_Int32, nonDelegateEvent.Type.SpecialType);
}
[Fact]
public void TestExplicitImplementationSimple()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Class").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classEvent = (EventSymbol)@class.GetMembers("Interface.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceEvent, explicitImpl);
}
[Fact]
public void TestExplicitImplementationGeneric()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Generic").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceEvent = (EventSymbol)substitutedInterface.GetMembers("Event").Single();
Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition);
var classEvent = (EventSymbol)@class.GetMembers("IGeneric<S>.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceEvent, explicitImpl);
}
[Fact]
public void TestExplicitImplementationConstructed()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Constructed").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceEvent = (EventSymbol)substitutedInterface.GetMembers("Event").Single();
Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition);
var classEvent = (EventSymbol)@class.GetMembers("IGeneric<System.Int32>.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceEvent, explicitImpl);
}
/// <summary>
/// A type def explicitly implements an interface, also a type def, but only
/// indirectly, via a type ref.
/// </summary>
[Fact]
public void TestExplicitImplementationDefRefDef()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var defInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
var defInterfaceEvent = (EventSymbol)defInterface.GetMembers("Event").Single();
var refInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGenericInterface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
Assert.True(refInterface.Interfaces().Contains(defInterface));
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IndirectImplementation").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var classInterfacesConstructedFrom = @class.Interfaces().Select(i => i.ConstructedFrom);
Assert.Equal(2, classInterfacesConstructedFrom.Count());
Assert.Contains(defInterface, classInterfacesConstructedFrom);
Assert.Contains(refInterface, classInterfacesConstructedFrom);
var classEvent = (EventSymbol)@class.GetMembers("Interface.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(defInterfaceEvent, explicitImpl);
}
/// <summary>
/// In metadata, nested types implicitly share all type parameters of their containing types.
/// This results in some extra computations when mapping a type parameter position to a type
/// parameter symbol.
/// </summary>
[Fact]
public void TestTypeParameterPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var outerInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric2").Single();
Assert.Equal(1, outerInterface.Arity);
Assert.Equal(TypeKind.Interface, outerInterface.TypeKind);
var outerInterfaceEvent = outerInterface.GetMembers().Single(m => m.Kind == SymbolKind.Event);
var outerClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Outer").Single();
Assert.Equal(1, outerClass.Arity);
Assert.Equal(TypeKind.Class, outerClass.TypeKind);
var innerInterface = (NamedTypeSymbol)outerClass.GetTypeMembers("IInner").Single();
Assert.Equal(1, innerInterface.Arity);
Assert.Equal(TypeKind.Interface, innerInterface.TypeKind);
var innerInterfaceEvent = innerInterface.GetMembers().Single(m => m.Kind == SymbolKind.Event);
var innerClass1 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner1").Single();
CheckInnerClassHelper(innerClass1, "IGeneric2<A>.Event", outerInterfaceEvent);
var innerClass2 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner2").Single();
CheckInnerClassHelper(innerClass2, "IGeneric2<T>.Event", outerInterfaceEvent);
var innerClass3 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner3").Single();
CheckInnerClassHelper(innerClass3, "Outer<T>.IInner<C>.Event", innerInterfaceEvent);
var innerClass4 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner4").Single();
CheckInnerClassHelper(innerClass4, "Outer<T>.IInner<T>.Event", innerInterfaceEvent);
}
private static void CheckInnerClassHelper(NamedTypeSymbol innerClass, string methodName, Symbol interfaceEvent)
{
var @interface = interfaceEvent.ContainingType;
Assert.Equal(1, innerClass.Arity);
Assert.Equal(TypeKind.Class, innerClass.TypeKind);
Assert.Equal(@interface, innerClass.Interfaces().Single().ConstructedFrom);
var innerClassEvent = (EventSymbol)innerClass.GetMembers(methodName).Single();
var innerClassImplementingEvent = innerClassEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceEvent, innerClassImplementingEvent.OriginalDefinition);
Assert.Equal(@interface, innerClassImplementingEvent.ContainingType.ConstructedFrom);
}
// NOTE: results differ from corresponding property test.
[WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")]
[Fact]
public void TestMixedAccessorModifiers()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.Events);
var globalNamespace = assembly.GlobalNamespace;
var type = globalNamespace.GetMember<NamedTypeSymbol>("AccessorModifierMismatch");
const VirtualnessModifiers @none = VirtualnessModifiers.None;
const VirtualnessModifiers @abstract = VirtualnessModifiers.Abstract;
const VirtualnessModifiers @virtual = VirtualnessModifiers.Virtual;
const VirtualnessModifiers @override = VirtualnessModifiers.Override;
const VirtualnessModifiers @sealed = VirtualnessModifiers.Sealed;
VirtualnessModifiers[] modList = new[]
{
@none,
@abstract,
@virtual,
@override,
@sealed,
};
int length = 1 + modList.Cast<int>().Max();
VirtualnessModifiers[,] expected = new VirtualnessModifiers[length, length];
expected[(int)@none, (int)@none] = @none;
expected[(int)@none, (int)@abstract] = @abstract;
expected[(int)@none, (int)@virtual] = @virtual;
expected[(int)@none, (int)@override] = @override;
expected[(int)@none, (int)@sealed] = @sealed;
expected[(int)@abstract, (int)@none] = @abstract;
expected[(int)@abstract, (int)@abstract] = @abstract;
expected[(int)@abstract, (int)@virtual] = @abstract;
expected[(int)@abstract, (int)@override] = @abstract | @override;
expected[(int)@abstract, (int)@sealed] = @abstract | @sealed;
expected[(int)@virtual, (int)@none] = @virtual;
expected[(int)@virtual, (int)@abstract] = @abstract;
expected[(int)@virtual, (int)@virtual] = @virtual;
expected[(int)@virtual, (int)@override] = @override;
expected[(int)@virtual, (int)@sealed] = @sealed;
expected[(int)@override, (int)@none] = @override;
expected[(int)@override, (int)@abstract] = @override | @abstract;
expected[(int)@override, (int)@virtual] = @override;
expected[(int)@override, (int)@override] = @override;
expected[(int)@override, (int)@sealed] = @sealed;
expected[(int)@sealed, (int)@none] = @sealed;
expected[(int)@sealed, (int)@abstract] = @abstract | @sealed;
expected[(int)@sealed, (int)@virtual] = @sealed;
expected[(int)@sealed, (int)@override] = @sealed;
expected[(int)@sealed, (int)@sealed] = @sealed;
// Table should be symmetrical.
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
Assert.Equal(expected[i, j], expected[j, i]);
}
}
foreach (var mod1 in modList)
{
foreach (var mod2 in modList)
{
var @event = type.GetMember<EventSymbol>(mod1.ToString() + mod2.ToString());
var addMethod = @event.AddMethod;
var removeMethod = @event.RemoveMethod;
Assert.Equal(mod1, GetVirtualnessModifiers(addMethod));
Assert.Equal(mod2, GetVirtualnessModifiers(removeMethod));
Assert.Equal(expected[(int)mod1, (int)mod2], GetVirtualnessModifiers(@event));
}
}
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField()
{
var source = @"
public class C
{
public event System.Action E;
}
";
var reference = CreateCompilation(source).EmitToImageReference();
var comp = CreateCompilation("", new[] { reference }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var @event = type.GetMember<PEEventSymbol>("E");
Assert.True(@event.HasAssociatedField);
var field = @event.AssociatedField;
Assert.NotNull(field);
Assert.Equal(@event, field.AssociatedSymbol);
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField_MultipleFields()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private int32 E
.field private class [mscorlib]System.Action E
.method public hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
} // end of class C
";
var ilRef = CompileIL(ilSource);
var comp = CreateCompilation("", new[] { ilRef }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var @event = type.GetMembers().OfType<PEEventSymbol>().Single();
Assert.True(@event.HasAssociatedField);
var field = @event.AssociatedField;
Assert.NotNull(field);
Assert.Equal(@event, field.AssociatedSymbol);
Assert.Equal(@event.Type, field.Type);
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField_DuplicateEvents()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action E
.method public hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
} // end of class C
";
var ilRef = CompileIL(ilSource);
var comp = CreateCompilation("", new[] { ilRef }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var events = type.GetMembers().OfType<PEEventSymbol>();
Assert.Equal(2, events.Count());
AssertEx.All(events, e => e.HasAssociatedField);
var field = events.First().AssociatedField;
Assert.NotNull(field);
AssertEx.All(events, e => e.AssociatedField == field);
Assert.Contains(field.AssociatedSymbol, events);
}
[Flags]
private enum VirtualnessModifiers
{
None = 0,
Abstract = 1,
Virtual = 2,
Override = 4,
Sealed = 8, //actually indicates sealed override
}
private static VirtualnessModifiers GetVirtualnessModifiers(Symbol symbol)
{
VirtualnessModifiers mods = VirtualnessModifiers.None;
if (symbol.IsAbstract) mods |= VirtualnessModifiers.Abstract;
if (symbol.IsVirtual) mods |= VirtualnessModifiers.Virtual;
if (symbol.IsSealed) mods |= VirtualnessModifiers.Sealed;
else if (symbol.IsOverride) mods |= VirtualnessModifiers.Override;
return mods;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Binding info for expressions and statements that are part of a member declaration.
/// </summary>
internal abstract partial class MemberSemanticModel : CSharpSemanticModel
{
private readonly Symbol _memberSymbol;
private readonly CSharpSyntaxNode _root;
private readonly ReaderWriterLockSlim _nodeMapLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
// The bound nodes associated with a syntax node, from highest in the tree to lowest.
private readonly Dictionary<SyntaxNode, ImmutableArray<BoundNode>> _guardedBoundNodeMap = new Dictionary<SyntaxNode, ImmutableArray<BoundNode>>();
private readonly Dictionary<SyntaxNode, IOperation> _guardedIOperationNodeMap = new Dictionary<SyntaxNode, IOperation>();
private Dictionary<SyntaxNode, BoundStatement> _lazyGuardedSynthesizedStatementsMap;
private NullableWalker.SnapshotManager _lazySnapshotManager;
private ImmutableDictionary<Symbol, Symbol> _lazyRemappedSymbols;
private readonly ImmutableDictionary<Symbol, Symbol> _parentRemappedSymbolsOpt;
/// <summary>
/// Only used when this is a speculative semantic model.
/// </summary>
private readonly NullableWalker.SnapshotManager _parentSnapshotManagerOpt;
internal readonly Binder RootBinder;
/// <summary>
/// Field specific to a non-speculative MemberSemanticModel that must have a containing semantic model.
/// </summary>
private readonly SyntaxTreeSemanticModel _containingSemanticModelOpt;
// Fields specific to a speculative MemberSemanticModel.
private readonly SyntaxTreeSemanticModel _parentSemanticModelOpt;
private readonly int _speculatedPosition;
private readonly Lazy<CSharpOperationFactory> _operationFactory;
protected MemberSemanticModel(
CSharpSyntaxNode root,
Symbol memberSymbol,
Binder rootBinder,
SyntaxTreeSemanticModel containingSemanticModelOpt,
SyntaxTreeSemanticModel parentSemanticModelOpt,
NullableWalker.SnapshotManager snapshotManagerOpt,
ImmutableDictionary<Symbol, Symbol> parentRemappedSymbolsOpt,
int speculatedPosition)
{
Debug.Assert(root != null);
Debug.Assert((object)memberSymbol != null);
Debug.Assert(parentSemanticModelOpt == null ^ containingSemanticModelOpt == null);
Debug.Assert(containingSemanticModelOpt == null || !containingSemanticModelOpt.IsSpeculativeSemanticModel);
Debug.Assert(parentSemanticModelOpt == null || !parentSemanticModelOpt.IsSpeculativeSemanticModel, CSharpResources.ChainingSpeculativeModelIsNotSupported);
Debug.Assert(snapshotManagerOpt == null || parentSemanticModelOpt != null);
_root = root;
_memberSymbol = memberSymbol;
this.RootBinder = rootBinder.WithAdditionalFlags(GetSemanticModelBinderFlags());
_containingSemanticModelOpt = containingSemanticModelOpt;
_parentSemanticModelOpt = parentSemanticModelOpt;
_parentSnapshotManagerOpt = snapshotManagerOpt;
_parentRemappedSymbolsOpt = parentRemappedSymbolsOpt;
_speculatedPosition = speculatedPosition;
_operationFactory = new Lazy<CSharpOperationFactory>(() => new CSharpOperationFactory(this));
}
public override CSharpCompilation Compilation
{
get
{
return (_containingSemanticModelOpt ?? _parentSemanticModelOpt).Compilation;
}
}
internal override CSharpSyntaxNode Root
{
get
{
return _root;
}
}
/// <summary>
/// The member symbol
/// </summary>
internal Symbol MemberSymbol
{
get
{
return _memberSymbol;
}
}
public sealed override bool IsSpeculativeSemanticModel
{
get
{
return _parentSemanticModelOpt != null;
}
}
public sealed override int OriginalPositionForSpeculation
{
get
{
return _speculatedPosition;
}
}
public sealed override CSharpSemanticModel ParentModel
{
get
{
return _parentSemanticModelOpt;
}
}
internal sealed override SemanticModel ContainingModelOrSelf
{
get
{
return _containingSemanticModelOpt ?? (SemanticModel)this;
}
}
internal override MemberSemanticModel GetMemberModel(SyntaxNode node)
{
// We do have to override this method, but should never call it because it might not do the right thing.
Debug.Assert(false);
return IsInTree(node) ? this : null;
}
/// <remarks>
/// This will cause the bound node cache to be populated if nullable semantic analysis is enabled.
/// </remarks>
protected virtual NullableWalker.SnapshotManager GetSnapshotManager()
{
EnsureNullabilityAnalysisPerformedIfNecessary();
Debug.Assert(_lazySnapshotManager is object || this is AttributeSemanticModel || !IsNullableAnalysisEnabled());
return _lazySnapshotManager;
}
internal ImmutableDictionary<Symbol, Symbol> GetRemappedSymbols()
{
EnsureNullabilityAnalysisPerformedIfNecessary();
Debug.Assert(_lazyRemappedSymbols is object || this is AttributeSemanticModel || !IsNullableAnalysisEnabled());
return _lazyRemappedSymbols;
}
internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out SemanticModel speculativeModel)
{
var expression = SyntaxFactory.GetStandaloneExpression(type);
var binder = this.GetSpeculativeBinder(position, expression, bindingOption);
if (binder != null)
{
speculativeModel = new SpeculativeMemberSemanticModel(parentModel, _memberSymbol, type, binder, GetSnapshotManager(), GetRemappedSymbols(), position);
return true;
}
speculativeModel = null;
return false;
}
internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel)
{
// crefs can never legally appear within members.
speculativeModel = null;
return false;
}
internal override BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
if (bindingOption == SpeculativeBindingOption.BindAsExpression && GetSnapshotManager() is { } snapshotManager)
{
crefSymbols = default;
position = CheckAndAdjustPosition(position);
expression = SyntaxFactory.GetStandaloneExpression(expression);
binder = GetSpeculativeBinder(position, expression, bindingOption);
var boundRoot = binder.BindExpression(expression, BindingDiagnosticBag.Discarded);
ImmutableDictionary<Symbol, Symbol> ignored = null;
return (BoundExpression)NullableWalker.AnalyzeAndRewriteSpeculation(position, boundRoot, binder, snapshotManager, newSnapshots: out _, remappedSymbols: ref ignored);
}
else
{
return GetSpeculativelyBoundExpressionWithoutNullability(position, expression, bindingOption, out binder, out crefSymbols);
}
}
private Binder GetEnclosingBinderInternalWithinRoot(SyntaxNode node, int position)
{
AssertPositionAdjusted(position);
return GetEnclosingBinderInternalWithinRoot(node, position, RootBinder, _root).WithAdditionalFlags(GetSemanticModelBinderFlags());
}
private static Binder GetEnclosingBinderInternalWithinRoot(SyntaxNode node, int position, Binder rootBinder, SyntaxNode root)
{
if (node == root)
{
return rootBinder.GetBinder(node) ?? rootBinder;
}
Debug.Assert(root.Contains(node));
ExpressionSyntax typeOfArgument = null;
LocalFunctionStatementSyntax ownerOfTypeParametersInScope = null;
Binder binder = null;
for (var current = node; binder == null; current = current.ParentOrStructuredTriviaParent)
{
Debug.Assert(current != null); // Why were we asked for an enclosing binder for a node outside our root?
StatementSyntax stmt = current as StatementSyntax;
TypeOfExpressionSyntax typeOfExpression;
SyntaxKind kind = current.Kind();
if (stmt != null)
{
if (LookupPosition.IsInStatementScope(position, stmt))
{
binder = rootBinder.GetBinder(current);
if (binder != null)
{
binder = AdjustBinderForPositionWithinStatement(position, binder, stmt);
}
else if (kind == SyntaxKind.LocalFunctionStatement)
{
Debug.Assert(ownerOfTypeParametersInScope == null);
var localFunction = (LocalFunctionStatementSyntax)stmt;
if (localFunction.TypeParameterList != null &&
!LookupPosition.IsBetweenTokens(position, localFunction.Identifier, localFunction.TypeParameterList.LessThanToken)) // Scope does not include method name.
{
ownerOfTypeParametersInScope = localFunction;
}
}
}
}
else if (kind == SyntaxKind.CatchClause)
{
if (LookupPosition.IsInCatchBlockScope(position, (CatchClauseSyntax)current))
{
binder = rootBinder.GetBinder(current);
}
}
else if (kind == SyntaxKind.CatchFilterClause)
{
if (LookupPosition.IsInCatchFilterScope(position, (CatchFilterClauseSyntax)current))
{
binder = rootBinder.GetBinder(current);
}
}
else if (current.IsAnonymousFunction())
{
if (LookupPosition.IsInAnonymousFunctionOrQuery(position, current))
{
binder = rootBinder.GetBinder(current.AnonymousFunctionBody());
Debug.Assert(binder != null);
}
}
else if (kind == SyntaxKind.TypeOfExpression &&
typeOfArgument == null &&
LookupPosition.IsBetweenTokens(
position,
(typeOfExpression = (TypeOfExpressionSyntax)current).OpenParenToken,
typeOfExpression.CloseParenToken))
{
typeOfArgument = typeOfExpression.Type;
}
else if (kind == SyntaxKind.SwitchSection)
{
if (LookupPosition.IsInSwitchSectionScope(position, (SwitchSectionSyntax)current))
{
binder = rootBinder.GetBinder(current);
}
}
else if (kind == SyntaxKind.ArgumentList)
{
var argList = (ArgumentListSyntax)current;
if (LookupPosition.IsBetweenTokens(position, argList.OpenParenToken, argList.CloseParenToken))
{
binder = rootBinder.GetBinder(current);
}
}
else if (kind == SyntaxKind.EqualsValueClause)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.Attribute)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.ArrowExpressionClause)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.ThisConstructorInitializer || kind == SyntaxKind.BaseConstructorInitializer || kind == SyntaxKind.PrimaryConstructorBaseType)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.ConstructorDeclaration)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.SwitchExpression)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.SwitchExpressionArm)
{
binder = rootBinder.GetBinder(current);
}
else if ((current as ExpressionSyntax).IsValidScopeDesignator())
{
binder = rootBinder.GetBinder(current);
}
else
{
// If this ever breaks, make sure that all callers of
// CanHaveAssociatedLocalBinder are in sync.
Debug.Assert(!current.CanHaveAssociatedLocalBinder());
}
if (current == root)
{
break;
}
}
binder = binder ?? rootBinder.GetBinder(root) ?? rootBinder;
Debug.Assert(binder != null);
if (ownerOfTypeParametersInScope != null)
{
LocalFunctionSymbol function = GetDeclaredLocalFunction(binder, ownerOfTypeParametersInScope.Identifier);
if ((object)function != null)
{
binder = function.SignatureBinder;
}
}
if (typeOfArgument != null)
{
binder = new TypeofBinder(typeOfArgument, binder);
}
return binder;
}
private static Binder AdjustBinderForPositionWithinStatement(int position, Binder binder, StatementSyntax stmt)
{
switch (stmt.Kind())
{
case SyntaxKind.SwitchStatement:
var switchStmt = (SwitchStatementSyntax)stmt;
if (LookupPosition.IsBetweenTokens(position, switchStmt.SwitchKeyword, switchStmt.OpenBraceToken))
{
binder = binder.GetBinder(switchStmt.Expression);
Debug.Assert(binder != null);
}
break;
case SyntaxKind.ForStatement:
var forStmt = (ForStatementSyntax)stmt;
if (LookupPosition.IsBetweenTokens(position, forStmt.SecondSemicolonToken, forStmt.CloseParenToken) &&
forStmt.Incrementors.Count > 0)
{
binder = binder.GetBinder(forStmt.Incrementors.First());
Debug.Assert(binder != null);
}
else if (LookupPosition.IsBetweenTokens(position, forStmt.FirstSemicolonToken, LookupPosition.GetFirstExcludedToken(forStmt)) &&
forStmt.Condition != null)
{
binder = binder.GetBinder(forStmt.Condition);
Debug.Assert(binder != null);
}
break;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
var foreachStmt = (CommonForEachStatementSyntax)stmt;
var start = stmt.Kind() == SyntaxKind.ForEachVariableStatement ? foreachStmt.InKeyword : foreachStmt.OpenParenToken;
if (LookupPosition.IsBetweenTokens(position, start, foreachStmt.Statement.GetFirstToken()))
{
binder = binder.GetBinder(foreachStmt.Expression);
Debug.Assert(binder != null);
}
break;
}
return binder;
}
public override Conversion ClassifyConversion(
ExpressionSyntax expression,
ITypeSymbol destination,
bool isExplicitInSource = false)
{
if ((object)destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
TypeSymbol csdestination = destination.EnsureCSharpSymbolOrNull(nameof(destination));
if (expression.Kind() == SyntaxKind.DeclarationExpression)
{
// Conversion from a declaration is unspecified.
return Conversion.NoConversion;
}
// Special Case: We have to treat anonymous functions differently, because of the way
// they are cached in the syntax-to-bound node map. Specifically, UnboundLambda nodes
// never appear in the map - they are converted to BoundLambdas, even in error scenarios.
// Since a BoundLambda has a type, we would end up doing a conversion from the delegate
// type, rather than from the anonymous function expression. If we use the overload that
// takes a position, it considers the request speculative and does not use the map.
// Bonus: Since the other overload will always bind the anonymous function from scratch,
// we don't have to worry about it affecting the trial-binding cache in the "real"
// UnboundLambda node (DevDiv #854548).
if (expression.IsAnonymousFunction())
{
CheckSyntaxNode(expression);
return this.ClassifyConversion(expression.SpanStart, expression, destination, isExplicitInSource);
}
if (isExplicitInSource)
{
return ClassifyConversionForCast(expression, csdestination);
}
// Note that it is possible for an expression to be convertible to a type
// via both an implicit user-defined conversion and an explicit built-in conversion.
// In that case, this method chooses the implicit conversion.
CheckSyntaxNode(expression);
var binder = this.GetEnclosingBinderInternal(expression, GetAdjustedNodePosition(expression));
CSharpSyntaxNode bindableNode = this.GetBindableSyntaxNode(expression);
var boundExpression = this.GetLowerBoundNode(bindableNode) as BoundExpression;
if (binder == null || boundExpression == null)
{
return Conversion.NoConversion;
}
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return binder.Conversions.ClassifyConversionFromExpression(boundExpression, csdestination, ref discardedUseSiteInfo);
}
internal override Conversion ClassifyConversionForCast(
ExpressionSyntax expression,
TypeSymbol destination)
{
CheckSyntaxNode(expression);
if ((object)destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
var binder = this.GetEnclosingBinderInternal(expression, GetAdjustedNodePosition(expression));
CSharpSyntaxNode bindableNode = this.GetBindableSyntaxNode(expression);
var boundExpression = this.GetLowerBoundNode(bindableNode) as BoundExpression;
if (binder == null || boundExpression == null)
{
return Conversion.NoConversion;
}
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return binder.Conversions.ClassifyConversionFromExpression(boundExpression, destination, ref discardedUseSiteInfo, forCast: true);
}
/// <summary>
/// Get the bound node corresponding to the root.
/// </summary>
internal virtual BoundNode GetBoundRoot()
{
return GetUpperBoundNode(GetBindableSyntaxNode(this.Root));
}
/// <summary>
/// Get the highest bound node in the tree associated with a particular syntax node.
/// </summary>
internal BoundNode GetUpperBoundNode(CSharpSyntaxNode node, bool promoteToBindable = false)
{
if (promoteToBindable)
{
node = GetBindableSyntaxNode(node);
}
else
{
Debug.Assert(node == GetBindableSyntaxNode(node));
}
// The bound nodes are stored in the map from highest to lowest, so the first bound node is the highest.
var boundNodes = GetBoundNodes(node);
if (boundNodes.Length == 0)
{
return null;
}
else
{
return boundNodes[0];
}
}
/// <summary>
/// Get the lowest bound node in the tree associated with a particular syntax node. Lowest is defined as last
/// in a pre-order traversal of the bound tree.
/// </summary>
internal BoundNode GetLowerBoundNode(CSharpSyntaxNode node)
{
Debug.Assert(node == GetBindableSyntaxNode(node));
// The bound nodes are stored in the map from highest to lowest, so the last bound node is the lowest.
var boundNodes = GetBoundNodes(node);
if (boundNodes.Length == 0)
{
return null;
}
else
{
return GetLowerBoundNode(boundNodes);
}
}
private static BoundNode GetLowerBoundNode(ImmutableArray<BoundNode> boundNodes)
{
return boundNodes[boundNodes.Length - 1];
}
public override ImmutableArray<Diagnostic> GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotSupportedException();
}
public override ImmutableArray<Diagnostic> GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotSupportedException();
}
public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotSupportedException();
}
public override ImmutableArray<Diagnostic> GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotSupportedException();
}
public override INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't defined namespace inside a member.
return null;
}
public override INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't defined namespace inside a member.
return null;
}
public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define type inside a member.
return null;
}
public override INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define type inside a member.
return null;
}
public override IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define member inside member.
return null;
}
public override ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
return GetDeclaredLocalFunction(declarationSyntax).GetPublicSymbol();
}
public override ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define member inside member.
return null;
}
public override IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default)
{
return null;
}
public override IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define method inside member.
return null;
}
public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define property inside member.
return null;
}
public override IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define property inside member.
return null;
}
public override IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define indexer inside member.
return null;
}
public override IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define event inside member.
return null;
}
public override IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define accessor inside member.
return null;
}
public override IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define another member inside member.
return null;
}
public override ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
return GetDeclaredLocal(declarationSyntax, declarationSyntax.Identifier).GetPublicSymbol();
}
public override ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
return GetDeclaredLocal(declarationSyntax, declarationSyntax.Identifier).GetPublicSymbol();
}
private LocalSymbol GetDeclaredLocal(CSharpSyntaxNode declarationSyntax, SyntaxToken declaredIdentifier)
{
for (var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(declarationSyntax)); binder != null; binder = binder.Next)
{
foreach (var local in binder.Locals)
{
if (local.IdentifierToken == declaredIdentifier)
{
return GetAdjustedLocalSymbol((SourceLocalSymbol)local);
}
}
}
return null;
}
#nullable enable
internal override LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol local)
{
return GetRemappedSymbol<LocalSymbol>(local);
}
private LocalFunctionSymbol GetDeclaredLocalFunction(LocalFunctionStatementSyntax declarationSyntax)
{
var originalSymbol = GetDeclaredLocalFunction(this.GetEnclosingBinder(GetAdjustedNodePosition(declarationSyntax)), declarationSyntax.Identifier);
return GetRemappedSymbol(originalSymbol);
}
private T GetRemappedSymbol<T>(T originalSymbol) where T : Symbol
{
EnsureNullabilityAnalysisPerformedIfNecessary();
if (_lazyRemappedSymbols is null) return originalSymbol;
if (_lazyRemappedSymbols.TryGetValue(originalSymbol, out Symbol? remappedSymbol))
{
RoslynDebug.Assert(remappedSymbol is object);
return (T)remappedSymbol;
}
return originalSymbol;
}
#nullable disable
private static LocalFunctionSymbol GetDeclaredLocalFunction(Binder enclosingBinder, SyntaxToken declaredIdentifier)
{
for (var binder = enclosingBinder; binder != null; binder = binder.Next)
{
foreach (var localFunction in binder.LocalFunctions)
{
if (localFunction.NameToken == declaredIdentifier)
{
return localFunction;
}
}
}
return null;
}
public override ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(declarationSyntax));
while (binder != null && !binder.IsLabelsScopeBinder)
{
binder = binder.Next;
}
if (binder != null)
{
foreach (var label in binder.Labels)
{
if (label.IdentifierNodeOrToken.IsToken &&
label.IdentifierNodeOrToken.AsToken() == declarationSyntax.Identifier)
{
return label.GetPublicSymbol();
}
}
}
return null;
}
public override ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(declarationSyntax));
while (binder != null && !(binder is SwitchBinder))
{
binder = binder.Next;
}
if (binder != null)
{
foreach (var label in binder.Labels)
{
if (label.IdentifierNodeOrToken.IsNode &&
label.IdentifierNodeOrToken.AsNode() == declarationSyntax)
{
return label.GetPublicSymbol();
}
}
}
return null;
}
public override IAliasSymbol GetDeclaredSymbol(UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define alias inside member.
return null;
}
public override IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define an extern alias inside a member.
return null;
}
public override IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Could be parameter of a lambda or a local function.
CheckSyntaxNode(declarationSyntax);
return GetLambdaOrLocalFunctionParameterSymbol(declarationSyntax, cancellationToken).GetPublicSymbol();
}
internal override ImmutableArray<ISymbol> GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define field inside member.
return ImmutableArray.Create<ISymbol>();
}
private ParameterSymbol GetLambdaOrLocalFunctionParameterSymbol(
ParameterSyntax parameter,
CancellationToken cancellationToken)
{
Debug.Assert(parameter != null);
var simpleLambda = parameter.Parent as SimpleLambdaExpressionSyntax;
if (simpleLambda != null)
{
return GetLambdaParameterSymbol(parameter, simpleLambda, cancellationToken);
}
var paramList = parameter.Parent as ParameterListSyntax;
if (paramList == null || paramList.Parent == null)
{
return null;
}
if (paramList.Parent.IsAnonymousFunction())
{
return GetLambdaParameterSymbol(parameter, (ExpressionSyntax)paramList.Parent, cancellationToken);
}
else if (paramList.Parent.Kind() == SyntaxKind.LocalFunctionStatement)
{
var localFunction = GetDeclaredSymbol((LocalFunctionStatementSyntax)paramList.Parent, cancellationToken).GetSymbol<MethodSymbol>();
if ((object)localFunction != null)
{
return GetParameterSymbol(localFunction.Parameters, parameter, cancellationToken);
}
}
return null;
}
private ParameterSymbol GetLambdaParameterSymbol(
ParameterSyntax parameter,
ExpressionSyntax lambda,
CancellationToken cancellationToken)
{
Debug.Assert(parameter != null);
Debug.Assert(lambda != null && lambda.IsAnonymousFunction());
// We should always be able to get at least an error binding for a lambda.
SymbolInfo symbolInfo = this.GetSymbolInfo(lambda, cancellationToken);
LambdaSymbol lambdaSymbol;
if ((object)symbolInfo.Symbol != null)
{
lambdaSymbol = symbolInfo.Symbol.GetSymbol<LambdaSymbol>();
}
else if (symbolInfo.CandidateSymbols.Length == 1)
{
lambdaSymbol = symbolInfo.CandidateSymbols.Single().GetSymbol<LambdaSymbol>();
}
else
{
Debug.Assert(this.GetMemberModel(lambda) == null, "Did not find a unique LambdaSymbol for lambda in member.");
return null;
}
return GetParameterSymbol(lambdaSymbol.Parameters, parameter, cancellationToken);
}
public override ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define alias inside member.
return null;
}
public override IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return bound == null ? null : bound.DefinedSymbol.GetPublicSymbol();
}
public override IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax queryClause, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(queryClause);
return bound == null ? null : bound.DefinedSymbol.GetPublicSymbol();
}
public override IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return bound == null ? null : bound.DefinedSymbol.GetPublicSymbol();
}
public override AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node)
{
if (node.Kind() != SyntaxKind.AwaitExpression)
{
throw new ArgumentException("node.Kind==" + node.Kind());
}
var bound = GetLowerBoundNode(node);
BoundAwaitableInfo awaitableInfo = (((bound as BoundExpressionStatement)?.Expression ?? bound) as BoundAwaitExpression)?.AwaitableInfo;
if (awaitableInfo == null)
{
return default(AwaitExpressionInfo);
}
return new AwaitExpressionInfo(
getAwaiter: (IMethodSymbol)awaitableInfo.GetAwaiter?.ExpressionSymbol.GetPublicSymbol(),
isCompleted: awaitableInfo.IsCompleted.GetPublicSymbol(),
getResult: awaitableInfo.GetResult.GetPublicSymbol(),
isDynamic: awaitableInfo.IsDynamic);
}
public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node)
{
return GetForEachStatementInfo((CommonForEachStatementSyntax)node);
}
public override ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node)
{
BoundForEachStatement boundForEach = (BoundForEachStatement)GetUpperBoundNode(node);
if (boundForEach == null)
{
return default(ForEachStatementInfo);
}
ForEachEnumeratorInfo enumeratorInfoOpt = boundForEach.EnumeratorInfoOpt;
Debug.Assert(enumeratorInfoOpt != null || boundForEach.HasAnyErrors);
if (enumeratorInfoOpt == null)
{
return default(ForEachStatementInfo);
}
// Even though we usually pretend to be using System.Collection.IEnumerable
// for arrays, that doesn't make sense for pointer arrays since object
// (the type of System.Collections.IEnumerator.Current) isn't convertible
// to pointer types.
if (enumeratorInfoOpt.ElementType.IsPointerType())
{
Debug.Assert(!enumeratorInfoOpt.CurrentConversion.IsValid);
return default(ForEachStatementInfo);
}
// NOTE: we're going to list GetEnumerator, etc for array and string
// collections, even though we know that's not how the implementation
// actually enumerates them.
MethodSymbol disposeMethod = null;
if (enumeratorInfoOpt.NeedsDisposal)
{
if (enumeratorInfoOpt.PatternDisposeInfo is { Method: var method })
{
disposeMethod = method;
}
else
{
disposeMethod = enumeratorInfoOpt.IsAsync
? (MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_IAsyncDisposable__DisposeAsync)
: (MethodSymbol)Compilation.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose);
}
}
return new ForEachStatementInfo(
enumeratorInfoOpt.IsAsync,
enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(),
enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(),
currentProperty: ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter?.AssociatedSymbol).GetPublicSymbol(),
disposeMethod.GetPublicSymbol(),
enumeratorInfoOpt.ElementType.GetPublicSymbol(),
boundForEach.ElementConversion,
enumeratorInfoOpt.CurrentConversion);
}
public override DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node)
{
var boundDeconstruction = GetUpperBoundNode(node) as BoundDeconstructionAssignmentOperator;
if (boundDeconstruction is null)
{
return default;
}
var boundConversion = boundDeconstruction.Right;
Debug.Assert(boundConversion != null);
if (boundConversion is null)
{
return default;
}
return new DeconstructionInfo(boundConversion.Conversion);
}
public override DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node)
{
var boundForEach = (BoundForEachStatement)GetUpperBoundNode(node);
if (boundForEach is null)
{
return default;
}
var boundDeconstruction = boundForEach.DeconstructionOpt;
Debug.Assert(boundDeconstruction != null || boundForEach.HasAnyErrors);
if (boundDeconstruction is null)
{
return default;
}
return new DeconstructionInfo(boundDeconstruction.DeconstructionAssignment.Right.Conversion);
}
private BoundQueryClause GetBoundQueryClause(CSharpSyntaxNode node)
{
CheckSyntaxNode(node);
return this.GetLowerBoundNode(node) as BoundQueryClause;
}
private QueryClauseInfo GetQueryClauseInfo(BoundQueryClause bound)
{
if (bound == null) return default(QueryClauseInfo);
var castInfo = (bound.Cast == null) ? SymbolInfo.None : GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, bound.Cast, bound.Cast, boundNodeForSyntacticParent: null, binderOpt: null);
var operationInfo = GetSymbolInfoForQuery(bound);
return new QueryClauseInfo(castInfo: castInfo, operationInfo: operationInfo);
}
private SymbolInfo GetSymbolInfoForQuery(BoundQueryClause bound)
{
var call = bound?.Operation as BoundCall;
if (call == null)
{
return SymbolInfo.None;
}
var operation = call.IsDelegateCall ? call.ReceiverOpt : call;
return GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, operation, operation, boundNodeForSyntacticParent: null, binderOpt: null);
}
private CSharpTypeInfo GetTypeInfoForQuery(BoundQueryClause bound)
{
return bound == null ?
CSharpTypeInfo.None :
GetTypeInfoForNode(bound, bound, bound);
}
public override QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return GetQueryClauseInfo(bound);
}
public override IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declaratorSyntax);
var anonymousObjectCreation = (AnonymousObjectCreationExpressionSyntax)declaratorSyntax.Parent;
if (anonymousObjectCreation == null)
{
return null;
}
var bound = this.GetLowerBoundNode(anonymousObjectCreation) as BoundAnonymousObjectCreationExpression;
if (bound == null)
{
return null;
}
var anonymousType = bound.Type as NamedTypeSymbol;
if ((object)anonymousType == null)
{
return null;
}
int index = anonymousObjectCreation.Initializers.IndexOf(declaratorSyntax);
Debug.Assert(index >= 0);
Debug.Assert(index < anonymousObjectCreation.Initializers.Count);
return AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, index).GetPublicSymbol();
}
public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declaratorSyntax);
var bound = this.GetLowerBoundNode(declaratorSyntax) as BoundAnonymousObjectCreationExpression;
return (bound == null) ? null : (bound.Type as NamedTypeSymbol).GetPublicSymbol();
}
public override INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declaratorSyntax);
return GetTypeOfTupleLiteral(declaratorSyntax).GetPublicSymbol();
}
public override ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declaratorSyntax);
var tupleLiteral = declaratorSyntax?.Parent as TupleExpressionSyntax;
// for now only arguments of a tuple literal may declare symbols
if (tupleLiteral == null)
{
return null;
}
var tupleLiteralType = GetTypeOfTupleLiteral(tupleLiteral);
if ((object)tupleLiteralType != null)
{
var elements = tupleLiteralType.TupleElements;
if (!elements.IsDefault)
{
var idx = tupleLiteral.Arguments.IndexOf(declaratorSyntax);
return elements[idx].GetPublicSymbol();
}
}
return null;
}
private NamedTypeSymbol GetTypeOfTupleLiteral(TupleExpressionSyntax declaratorSyntax)
{
var bound = this.GetLowerBoundNode(declaratorSyntax);
return (bound as BoundTupleExpression)?.Type as NamedTypeSymbol;
}
public override SyntaxTree SyntaxTree
{
get
{
return _root.SyntaxTree;
}
}
#nullable enable
internal override IOperation? GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken)
{
using (_nodeMapLock.DisposableRead())
{
if (_guardedIOperationNodeMap.Count != 0)
{
return guardedGetIOperation();
}
}
IOperation rootOperation = GetRootOperation();
using var _ = _nodeMapLock.DisposableWrite();
if (_guardedIOperationNodeMap.Count != 0)
{
return guardedGetIOperation();
}
OperationMapBuilder.AddToMap(rootOperation, _guardedIOperationNodeMap);
return guardedGetIOperation();
IOperation? guardedGetIOperation()
{
_nodeMapLock.AssertCanRead();
return _guardedIOperationNodeMap.TryGetValue(node, out var operation) ? operation : null;
}
}
#nullable disable
private CSharpSyntaxNode GetBindingRootOrInitializer(CSharpSyntaxNode node)
{
CSharpSyntaxNode bindingRoot = GetBindingRoot(node);
// if binding root is parameter, make it equal value
// we need to do this since node map doesn't contain bound node for parameter
if (bindingRoot is ParameterSyntax parameter && parameter.Default?.FullSpan.Contains(node.Span) == true)
{
return parameter.Default;
}
// if binding root is field variable declarator, make it initializer
// we need to do this since node map doesn't contain bound node for field/event variable declarator
if (bindingRoot is VariableDeclaratorSyntax variableDeclarator && variableDeclarator.Initializer?.FullSpan.Contains(node.Span) == true)
{
if (variableDeclarator.Parent?.Parent.IsKind(SyntaxKind.FieldDeclaration) == true ||
variableDeclarator.Parent?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) == true)
{
return variableDeclarator.Initializer;
}
}
// if binding root is enum member declaration, make it equal value
// we need to do this since node map doesn't contain bound node for enum member decl
if (bindingRoot is EnumMemberDeclarationSyntax enumMember && enumMember.EqualsValue?.FullSpan.Contains(node.Span) == true)
{
return enumMember.EqualsValue;
}
// if binding root is property member declaration, make it equal value
// we need to do this since node map doesn't contain bound node for property initializer
if (bindingRoot is PropertyDeclarationSyntax propertyMember && propertyMember.Initializer?.FullSpan.Contains(node.Span) == true)
{
return propertyMember.Initializer;
}
return bindingRoot;
}
#nullable enable
private IOperation GetRootOperation()
{
BoundNode highestBoundNode = GetBoundRoot();
Debug.Assert(highestBoundNode != null);
if (highestBoundNode is BoundGlobalStatementInitializer { Statement: var innerStatement })
{
// Script top-level field declarations use a BoundGlobalStatementInitializer to wrap initializers.
// We don't represent these nodes in IOperation, so skip it.
highestBoundNode = innerStatement;
}
// The CSharp operation factory assumes that UnboundLambda will be bound for error recovery and never be passed to the factory
// as the start of a tree to get operations for. This is guaranteed by the builder that populates the node map, as it will call
// UnboundLambda.BindForErrorRecovery() when it encounters an UnboundLambda node.
Debug.Assert(highestBoundNode.Kind != BoundKind.UnboundLambda);
IOperation operation = _operationFactory.Value.Create(highestBoundNode);
Operation.SetParentOperation(operation, null);
return operation;
}
#nullable disable
internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken))
{
ValidateSymbolInfoOptions(options);
CSharpSyntaxNode bindableNode;
BoundNode lowestBoundNode;
BoundNode highestBoundNode;
BoundNode boundParent;
GetBoundNodes(node, out bindableNode, out lowestBoundNode, out highestBoundNode, out boundParent);
Debug.Assert(IsInTree(node), "Since the node is in the tree, we can always recompute the binder later");
return base.GetSymbolInfoForNode(options, lowestBoundNode, highestBoundNode, boundParent, binderOpt: null);
}
internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
CSharpSyntaxNode bindableNode;
BoundNode lowestBoundNode;
BoundNode highestBoundNode;
BoundNode boundParent;
GetBoundNodes(node, out bindableNode, out lowestBoundNode, out highestBoundNode, out boundParent);
return GetTypeInfoForNode(lowestBoundNode, highestBoundNode, boundParent);
}
internal override ImmutableArray<Symbol> GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken))
{
CSharpSyntaxNode bindableNode;
BoundNode lowestBoundNode;
BoundNode highestBoundNode;
BoundNode boundParent;
GetBoundNodes(node, out bindableNode, out lowestBoundNode, out highestBoundNode, out boundParent);
Debug.Assert(IsInTree(node), "Since the node is in the tree, we can always recompute the binder later");
return base.GetMemberGroupForNode(options, lowestBoundNode, boundParent, binderOpt: null);
}
internal override ImmutableArray<IPropertySymbol> GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken))
{
CSharpSyntaxNode bindableNode;
BoundNode lowestBoundNode;
BoundNode highestBoundNode;
BoundNode boundParent;
GetBoundNodes(node, out bindableNode, out lowestBoundNode, out highestBoundNode, out boundParent);
Debug.Assert(IsInTree(node), "Since the node is in the tree, we can always recompute the binder later");
return base.GetIndexerGroupForNode(lowestBoundNode, binderOpt: null);
}
internal override Optional<object> GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken)
{
CSharpSyntaxNode bindableNode = this.GetBindableSyntaxNode(node);
BoundExpression boundExpr = this.GetLowerBoundNode(bindableNode) as BoundExpression;
if (boundExpr == null) return default(Optional<object>);
ConstantValue constantValue = boundExpr.ConstantValue;
return constantValue == null || constantValue.IsBad
? default(Optional<object>)
: new Optional<object>(constantValue.Value);
}
internal override SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var boundCollectionInitializer = GetLowerBoundNode(collectionInitializer) as BoundCollectionInitializerExpression;
if (boundCollectionInitializer != null)
{
var boundAdd = boundCollectionInitializer.Initializers[collectionInitializer.Expressions.IndexOf(node)];
return GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundAdd, boundAdd, null, binderOpt: null);
}
return SymbolInfo.None;
}
public override SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return GetSymbolInfoForQuery(bound);
}
public override SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return GetSymbolInfoForQuery(bound);
}
public override TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return GetTypeInfoForQuery(bound);
}
private void GetBoundNodes(CSharpSyntaxNode node, out CSharpSyntaxNode bindableNode, out BoundNode lowestBoundNode, out BoundNode highestBoundNode, out BoundNode boundParent)
{
bindableNode = this.GetBindableSyntaxNode(node);
CSharpSyntaxNode bindableParent = this.GetBindableParentNode(bindableNode);
// Special handling for the Color Color case.
//
// Suppose we have:
// public class Color {
// public void M(int x) {}
// public static void M(params int[] x) {}
// }
// public class C {
// public void Test() {
// Color Color = new Color();
// System.Action<int> d = Color.M;
// }
// }
//
// We actually don't know how to interpret the "Color" in "Color.M" until we
// perform overload resolution on the method group. Now, if we were getting
// the semantic info for the method group, then bindableParent would be the
// variable declarator "d = Color.M" and so we would be able to pull the result
// of overload resolution out of the bound (method group) conversion. However,
// if we are getting the semantic info for just the "Color" part, then
// bindableParent will be the member access, which doesn't have enough information
// to determine which "Color" to use (since no overload resolution has been
// performed). We resolve this problem by detecting the case where we're looking
// up the LHS of a member access and calling GetBindableParentNode one more time.
// This gets us up to the level where the method group conversion occurs.
if (bindableParent != null && bindableParent.Kind() == SyntaxKind.SimpleMemberAccessExpression && ((MemberAccessExpressionSyntax)bindableParent).Expression == bindableNode)
{
bindableParent = this.GetBindableParentNode(bindableParent);
}
boundParent = bindableParent == null ? null : this.GetLowerBoundNode(bindableParent);
lowestBoundNode = this.GetLowerBoundNode(bindableNode);
highestBoundNode = this.GetUpperBoundNode(bindableNode);
}
// In lambda binding scenarios we need to know two things: First,
// what is the *innermost* lambda that contains the expression we're
// interested in? Second, what is the smallest expression that contains
// the *outermost* lambda that we can bind in order to get a sensible
// lambda binding?
//
// For example, suppose we have the statement:
//
// A().B(x=>x.C(y=>y.D().E())).F().G();
//
// and the user wants binding information about method group "D". We must know
// the bindable expression that is outside of every lambda:
//
// A().B(x=>x.C(y=>y.D().E()))
//
// By binding that we can determine the type of lambda parameters "x" and "y" and
// put that information in the bound tree. Once we know those facts then
// we can obtain the binding object associated with the innermost lambda:
//
// y=>y.D().E()
//
// And use that binding to obtain the analysis of:
//
// y.D
//
private CSharpSyntaxNode GetInnermostLambdaOrQuery(CSharpSyntaxNode node, int position, bool allowStarting = false)
{
Debug.Assert(node != null);
for (var current = node; current != this.Root; current = current.ParentOrStructuredTriviaParent)
{
// current can only become null if we somehow got past the root. The only way we
// could have gotten past the root is to have started outside of it. That's
// unexpected; the binding should only be asked to provide an opinion on syntax
// nodes that it knows about.
Debug.Assert(current != null, "Why are we being asked to find an enclosing lambda outside of our root?");
if (!(current.IsAnonymousFunction() || current.IsQuery()))
{
continue;
}
// If the position is not actually within the scope of the lambda, then keep
// looking.
if (!LookupPosition.IsInAnonymousFunctionOrQuery(position, current))
{
continue;
}
// If we were asked for the innermost lambda enclosing a lambda then don't return
// that; it's not enclosing anything. Only return the lambda if it's enclosing the
// original node.
if (!allowStarting && current == node)
{
continue;
}
return current;
}
// If we made it to the root, then we are not "inside" a lambda even if the root is a
// lambda. Remember, the point of this code is to get the binding that is associated
// with the innermost lambda; if we are already in a binding associated with the
// innermost lambda then we're done.
return null;
}
private void GuardedAddSynthesizedStatementToMap(StatementSyntax node, BoundStatement statement)
{
if (_lazyGuardedSynthesizedStatementsMap == null)
{
_lazyGuardedSynthesizedStatementsMap = new Dictionary<SyntaxNode, BoundStatement>();
}
_lazyGuardedSynthesizedStatementsMap.Add(node, statement);
}
private BoundStatement GuardedGetSynthesizedStatementFromMap(StatementSyntax node)
{
if (_lazyGuardedSynthesizedStatementsMap != null &&
_lazyGuardedSynthesizedStatementsMap.TryGetValue(node, out BoundStatement result))
{
return result;
}
return null;
}
private ImmutableArray<BoundNode> GuardedGetBoundNodesFromMap(CSharpSyntaxNode node)
{
Debug.Assert(_nodeMapLock.IsWriteLockHeld || _nodeMapLock.IsReadLockHeld);
ImmutableArray<BoundNode> result;
return _guardedBoundNodeMap.TryGetValue(node, out result) ? result : default(ImmutableArray<BoundNode>);
}
/// <summary>
/// Internal for test purposes only
/// </summary>
internal ImmutableArray<BoundNode> TestOnlyTryGetBoundNodesFromMap(CSharpSyntaxNode node)
{
ImmutableArray<BoundNode> result;
return _guardedBoundNodeMap.TryGetValue(node, out result) ? result : default(ImmutableArray<BoundNode>);
}
// Adds every syntax/bound pair in a tree rooted at the given bound node to the map, and the
// performs a lookup of the given syntax node in the map.
private ImmutableArray<BoundNode> GuardedAddBoundTreeAndGetBoundNodeFromMap(CSharpSyntaxNode syntax, BoundNode bound)
{
Debug.Assert(_nodeMapLock.IsWriteLockHeld);
bool alreadyInTree = false;
if (bound != null)
{
alreadyInTree = _guardedBoundNodeMap.ContainsKey(bound.Syntax);
}
// check if we already have node in the cache.
// this may happen if we have races and in such case we are no longer interested in adding
if (!alreadyInTree)
{
NodeMapBuilder.AddToMap(bound, _guardedBoundNodeMap, SyntaxTree);
Debug.Assert(syntax != _root || _guardedBoundNodeMap.ContainsKey(bound.Syntax));
}
ImmutableArray<BoundNode> result;
return _guardedBoundNodeMap.TryGetValue(syntax, out result) ? result : default(ImmutableArray<BoundNode>);
}
protected void UnguardedAddBoundTreeForStandaloneSyntax(SyntaxNode syntax, BoundNode bound, NullableWalker.SnapshotManager manager = null, ImmutableDictionary<Symbol, Symbol> remappedSymbols = null)
{
using (_nodeMapLock.DisposableWrite())
{
GuardedAddBoundTreeForStandaloneSyntax(syntax, bound, manager, remappedSymbols);
}
}
protected void GuardedAddBoundTreeForStandaloneSyntax(SyntaxNode syntax, BoundNode bound, NullableWalker.SnapshotManager manager = null, ImmutableDictionary<Symbol, Symbol> remappedSymbols = null)
{
Debug.Assert(_nodeMapLock.IsWriteLockHeld);
bool alreadyInTree = false;
// check if we already have node in the cache.
// this may happen if we have races and in such case we are no longer interested in adding
if (bound != null)
{
alreadyInTree = _guardedBoundNodeMap.ContainsKey(bound.Syntax);
}
if (!alreadyInTree)
{
if (syntax == _root || syntax is StatementSyntax)
{
// Note: For speculative model we want to always cache the entire bound tree.
// If syntax is a statement, we need to add all its children.
// Node cache assumes that if statement is cached, then all
// its children are cached too.
NodeMapBuilder.AddToMap(bound, _guardedBoundNodeMap, SyntaxTree);
Debug.Assert(syntax != _root || _guardedBoundNodeMap.ContainsKey(bound.Syntax));
}
else
{
// expressions can be added individually.
NodeMapBuilder.AddToMap(bound, _guardedBoundNodeMap, SyntaxTree, syntax);
}
Debug.Assert((manager is null && (!IsNullableAnalysisEnabled() || syntax != Root || syntax is TypeSyntax ||
// Supporting attributes is tracked by
// https://github.com/dotnet/roslyn/issues/36066
this is AttributeSemanticModel)) ||
(manager is object && remappedSymbols is object && syntax == Root && IsNullableAnalysisEnabled() && _lazySnapshotManager is null));
if (manager is object)
{
_lazySnapshotManager = manager;
_lazyRemappedSymbols = remappedSymbols;
}
}
}
// We might not have actually been given a bindable expression or statement; the caller can
// give us variable declaration nodes, for example. If we're not at an expression or
// statement, back up until we find one.
private CSharpSyntaxNode GetBindingRoot(CSharpSyntaxNode node)
{
Debug.Assert(node != null);
#if DEBUG
for (CSharpSyntaxNode current = node; current != this.Root; current = current.ParentOrStructuredTriviaParent)
{
// make sure we never go out of Root
Debug.Assert(current != null, "How did we get outside the root?");
}
#endif
for (CSharpSyntaxNode current = node; current != this.Root; current = current.ParentOrStructuredTriviaParent)
{
if (current is StatementSyntax)
{
return current;
}
switch (current.Kind())
{
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
case SyntaxKind.PrimaryConstructorBaseType:
return current;
case SyntaxKind.ArrowExpressionClause:
// If this is an arrow expression on a local function statement, then our bindable root is actually our parent syntax as it's
// a statement in a function. If this is returned directly in IOperation, we'll end up with a separate tree.
if (current.Parent == null || current.Parent.Kind() != SyntaxKind.LocalFunctionStatement)
{
return current;
}
break;
}
}
return this.Root;
}
// We want the binder in which this syntax node is going to be bound, NOT the binder which
// this syntax node *produces*. That is, suppose we have
//
// void M() { int x; { int y; { int z; } } }
//
// We want the enclosing binder of the syntax node for { int z; }. We do not want the binder
// that has local z, but rather the binder that has local y. The inner block is going to be
// bound in the context of its enclosing binder; it's contents are going to be bound in the
// context of its binder.
internal override Binder GetEnclosingBinderInternal(int position)
{
AssertPositionAdjusted(position);
// If we have a root binder with no tokens in it, position can be outside the span event
// after position is adjusted. If this happens, there can't be any
if (!this.Root.FullSpan.Contains(position))
return this.RootBinder;
SyntaxToken token = this.Root.FindToken(position);
CSharpSyntaxNode node = (CSharpSyntaxNode)token.Parent;
return GetEnclosingBinderInternal(node, position);
}
/// <summary>
/// This overload exists for callers who already have a node in hand
/// and don't want to search through the tree.
/// </summary>
private Binder GetEnclosingBinderInternal(CSharpSyntaxNode node, int position)
{
AssertPositionAdjusted(position);
CSharpSyntaxNode innerLambdaOrQuery = GetInnermostLambdaOrQuery(node, position, allowStarting: true);
// There are three possible scenarios here.
//
// 1) the node is outside all lambdas in this context, or
// 2) The node is an outermost lambda in this context, or
// 3) the node is inside the outermost lambda in this context.
//
// In the first case, no lambdas are involved at all so let's just fall back on the
// original enclosing binder code.
//
// In the second case, we have been asked to bind an entire lambda and we know it to be
// the outermost lambda in this context. Therefore the enclosing binder is going to be
// the enclosing binder of this expression. However, we do not simply want to say
// "here's the enclosing binder":
//
// void M() { Func<int, int> f = x=>x+1; }
//
// We should step out to the enclosing statement or expression, if there is one, and
// bind that.
if (innerLambdaOrQuery == null)
{
return GetEnclosingBinderInternalWithinRoot(node, position);
}
// In the third case, we're in a child lambda.
BoundNode boundInnerLambdaOrQuery = GetBoundLambdaOrQuery(innerLambdaOrQuery);
return GetEnclosingBinderInLambdaOrQuery(position, node, innerLambdaOrQuery, ref boundInnerLambdaOrQuery);
}
private BoundNode GetBoundLambdaOrQuery(CSharpSyntaxNode lambdaOrQuery)
{
// Have we already cached a bound node for it?
// If not, bind the outermost expression containing the lambda and then fill in the map.
ImmutableArray<BoundNode> nodes;
EnsureNullabilityAnalysisPerformedIfNecessary();
using (_nodeMapLock.DisposableRead())
{
nodes = GuardedGetBoundNodesFromMap(lambdaOrQuery);
}
if (!nodes.IsDefaultOrEmpty)
{
return GetLowerBoundNode(nodes);
}
// We probably never tried to bind an enclosing statement
// Let's do that
Binder lambdaRecoveryBinder;
CSharpSyntaxNode bindingRoot = GetBindingRoot(lambdaOrQuery);
CSharpSyntaxNode enclosingLambdaOrQuery = GetInnermostLambdaOrQuery(lambdaOrQuery, lambdaOrQuery.SpanStart, allowStarting: false);
BoundNode boundEnclosingLambdaOrQuery = null;
CSharpSyntaxNode nodeToBind;
if (enclosingLambdaOrQuery == null)
{
nodeToBind = bindingRoot;
lambdaRecoveryBinder = GetEnclosingBinderInternalWithinRoot(nodeToBind, GetAdjustedNodePosition(nodeToBind));
}
else
{
if (enclosingLambdaOrQuery == bindingRoot || !enclosingLambdaOrQuery.Contains(bindingRoot))
{
Debug.Assert(bindingRoot.Contains(enclosingLambdaOrQuery));
nodeToBind = lambdaOrQuery;
}
else
{
nodeToBind = bindingRoot;
}
boundEnclosingLambdaOrQuery = GetBoundLambdaOrQuery(enclosingLambdaOrQuery);
using (_nodeMapLock.DisposableRead())
{
nodes = GuardedGetBoundNodesFromMap(lambdaOrQuery);
}
if (!nodes.IsDefaultOrEmpty)
{
// If everything is working as expected we should end up here because binding the enclosing lambda
// should also take care of binding and caching this lambda.
return GetLowerBoundNode(nodes);
}
lambdaRecoveryBinder = GetEnclosingBinderInLambdaOrQuery(GetAdjustedNodePosition(nodeToBind), nodeToBind, enclosingLambdaOrQuery, ref boundEnclosingLambdaOrQuery);
}
Binder incrementalBinder = new IncrementalBinder(this, lambdaRecoveryBinder);
using (_nodeMapLock.DisposableWrite())
{
BoundNode boundOuterExpression = this.Bind(incrementalBinder, nodeToBind, BindingDiagnosticBag.Discarded);
// https://github.com/dotnet/roslyn/issues/35038: Rewrite the above node and add a test that hits this path with nullable
// enabled
nodes = GuardedAddBoundTreeAndGetBoundNodeFromMap(lambdaOrQuery, boundOuterExpression);
}
if (!nodes.IsDefaultOrEmpty)
{
return GetLowerBoundNode(nodes);
}
Debug.Assert(lambdaOrQuery != nodeToBind);
// If there is a bug in the binder such that we "lose" a sub-expression containing a
// lambda, and never put bound state for it into the bound tree, then the bound lambda
// that comes back from the map lookup will be null. This can occur in error recovery
// situations. Let's bind the node directly.
if (enclosingLambdaOrQuery == null)
{
lambdaRecoveryBinder = GetEnclosingBinderInternalWithinRoot(lambdaOrQuery, GetAdjustedNodePosition(lambdaOrQuery));
}
else
{
lambdaRecoveryBinder = GetEnclosingBinderInLambdaOrQuery(GetAdjustedNodePosition(lambdaOrQuery), lambdaOrQuery, enclosingLambdaOrQuery, ref boundEnclosingLambdaOrQuery);
}
incrementalBinder = new IncrementalBinder(this, lambdaRecoveryBinder);
using (_nodeMapLock.DisposableWrite())
{
BoundNode boundOuterExpression = this.Bind(incrementalBinder, lambdaOrQuery, BindingDiagnosticBag.Discarded);
// https://github.com/dotnet/roslyn/issues/35038: We need to do a rewrite here, and create a test that can hit this.
if (!IsNullableAnalysisEnabled() && Compilation.IsNullableAnalysisEnabledAlways)
{
AnalyzeBoundNodeNullability(boundOuterExpression, incrementalBinder, diagnostics: new DiagnosticBag(), createSnapshots: false);
}
nodes = GuardedAddBoundTreeAndGetBoundNodeFromMap(lambdaOrQuery, boundOuterExpression);
}
return GetLowerBoundNode(nodes);
}
private Binder GetEnclosingBinderInLambdaOrQuery(int position, CSharpSyntaxNode node, CSharpSyntaxNode innerLambdaOrQuery, ref BoundNode boundInnerLambdaOrQuery)
{
Debug.Assert(boundInnerLambdaOrQuery != null);
Binder result;
switch (boundInnerLambdaOrQuery.Kind)
{
case BoundKind.UnboundLambda:
boundInnerLambdaOrQuery = ((UnboundLambda)boundInnerLambdaOrQuery).BindForErrorRecovery();
goto case BoundKind.Lambda;
case BoundKind.Lambda:
AssertPositionAdjusted(position);
result = GetLambdaEnclosingBinder(position, node, innerLambdaOrQuery, ((BoundLambda)boundInnerLambdaOrQuery).Binder);
break;
case BoundKind.QueryClause:
result = GetQueryEnclosingBinder(position, node, ((BoundQueryClause)boundInnerLambdaOrQuery));
break;
default:
return GetEnclosingBinderInternalWithinRoot(node, position); // Known to return non-null with BinderFlags.SemanticModel.
}
Debug.Assert(result != null);
return result.WithAdditionalFlags(GetSemanticModelBinderFlags());
}
/// <remarks>
/// Returned binder doesn't need to have <see cref="BinderFlags.SemanticModel"/> set - the caller will add it.
/// </remarks>
private static Binder GetQueryEnclosingBinder(int position, CSharpSyntaxNode startingNode, BoundQueryClause queryClause)
{
BoundExpression node = queryClause;
do
{
switch (node.Kind)
{
case BoundKind.QueryClause:
queryClause = (BoundQueryClause)node;
node = GetQueryClauseValue(queryClause);
continue;
case BoundKind.Call:
var call = (BoundCall)node;
node = GetContainingArgument(call.Arguments, position);
if (node != null)
{
continue;
}
BoundExpression receiver = call.ReceiverOpt;
// In some error scenarios, we end-up with a method group as the receiver,
// let's get to real receiver.
while (receiver?.Kind == BoundKind.MethodGroup)
{
receiver = ((BoundMethodGroup)receiver).ReceiverOpt;
}
if (receiver != null)
{
node = GetContainingExprOrQueryClause(receiver, position);
if (node != null)
{
continue;
}
}
// TODO: should we look for the "nearest" argument as a fallback?
node = call.Arguments.LastOrDefault();
continue;
case BoundKind.Conversion:
node = ((BoundConversion)node).Operand;
continue;
case BoundKind.UnboundLambda:
var unbound = (UnboundLambda)node;
return GetEnclosingBinderInternalWithinRoot(AdjustStartingNodeAccordingToNewRoot(startingNode, unbound.Syntax),
position, unbound.BindForErrorRecovery().Binder, unbound.Syntax);
case BoundKind.Lambda:
var lambda = (BoundLambda)node;
return GetEnclosingBinderInternalWithinRoot(AdjustStartingNodeAccordingToNewRoot(startingNode, lambda.Body.Syntax),
position, lambda.Binder, lambda.Body.Syntax);
default:
goto done;
}
}
while (node != null);
done:
return GetEnclosingBinderInternalWithinRoot(AdjustStartingNodeAccordingToNewRoot(startingNode, queryClause.Syntax),
position, queryClause.Binder, queryClause.Syntax);
}
// Return the argument containing the position. For query
// expressions, the span of an argument may include other
// arguments, so the argument with the smallest span is returned.
private static BoundExpression GetContainingArgument(ImmutableArray<BoundExpression> arguments, int position)
{
BoundExpression result = null;
TextSpan resultSpan = default(TextSpan);
foreach (var arg in arguments)
{
var expr = GetContainingExprOrQueryClause(arg, position);
if (expr != null)
{
var span = expr.Syntax.FullSpan;
if (result == null || resultSpan.Contains(span))
{
result = expr;
resultSpan = span;
}
}
}
return result;
}
// Returns the expr if the syntax span contains the position;
// returns the BoundQueryClause value if expr is a BoundQueryClause
// and the value contains the position; otherwise returns null.
private static BoundExpression GetContainingExprOrQueryClause(BoundExpression expr, int position)
{
if (expr.Kind == BoundKind.QueryClause)
{
var value = GetQueryClauseValue((BoundQueryClause)expr);
if (value.Syntax.FullSpan.Contains(position))
{
return value;
}
}
if (expr.Syntax.FullSpan.Contains(position))
{
return expr;
}
return null;
}
private static BoundExpression GetQueryClauseValue(BoundQueryClause queryClause)
{
return queryClause.UnoptimizedForm ?? queryClause.Value;
}
private static SyntaxNode AdjustStartingNodeAccordingToNewRoot(SyntaxNode startingNode, SyntaxNode root)
{
SyntaxNode result = startingNode.Contains(root) ? root : startingNode;
if (result != root && !root.Contains(result))
{
result = root;
}
return result;
}
/// <summary>
/// Performs the same function as GetEnclosingBinder, but is known to take place within a
/// specified lambda. Walks up the syntax hierarchy until a node with an associated binder
/// is found.
/// </summary>
/// <remarks>
/// CONSIDER: can this share code with MemberSemanticModel.GetEnclosingBinder?
///
/// Returned binder doesn't need to have <see cref="BinderFlags.SemanticModel"/> set - the caller will add it.
/// </remarks>
private static Binder GetLambdaEnclosingBinder(int position, CSharpSyntaxNode startingNode, CSharpSyntaxNode containingLambda, Binder lambdaBinder)
{
Debug.Assert(containingLambda.IsAnonymousFunction());
Debug.Assert(LookupPosition.IsInAnonymousFunctionOrQuery(position, containingLambda));
return GetEnclosingBinderInternalWithinRoot(startingNode, position, lambdaBinder, containingLambda);
}
/// <summary>
/// If we're doing nullable analysis, we need to fully bind this member, and then run
/// nullable analysis on the resulting nodes before putting them in the map. Nullable
/// analysis does not run a subset of code, so we need to fully bind the entire member
/// first
/// </summary>
protected void EnsureNullabilityAnalysisPerformedIfNecessary()
{
bool isNullableAnalysisEnabled = IsNullableAnalysisEnabled();
if (!isNullableAnalysisEnabled && !Compilation.IsNullableAnalysisEnabledAlways)
{
return;
}
// If we have a snapshot manager, then we've already done
// all the work necessary and we should avoid taking an
// unnecessary read lock.
if (_lazySnapshotManager is object)
{
return;
}
var bindableRoot = GetBindableSyntaxNode(Root);
using var upgradeableLock = _nodeMapLock.DisposableUpgradeableRead();
// If there are already nodes in the map, then we've already done work here. Since
// EnsureNullabilityAnalysis is guaranteed to have run first, that means we've
// already bound the root node and we can just exit. We can't just assert that Root
// is in the map, as there are some models for which there is no BoundNode for the
// Root elements (such as fields, where the root is a VariableDeclarator but the
// first BoundNode corresponds to the underlying EqualsValueSyntax of the initializer)
if (_guardedBoundNodeMap.Count > 0)
{
Debug.Assert(!isNullableAnalysisEnabled ||
_guardedBoundNodeMap.ContainsKey(bindableRoot) ||
_guardedBoundNodeMap.ContainsKey(bind(bindableRoot, out _).Syntax));
return;
}
upgradeableLock.EnterWrite();
NullableWalker.SnapshotManager snapshotManager;
var remappedSymbols = _parentRemappedSymbolsOpt;
Binder binder;
BoundNode boundRoot = bind(bindableRoot, out binder);
if (IsSpeculativeSemanticModel)
{
// Not all speculative models are created with existing snapshots. Attributes,
// TypeSyntaxes, and MethodBodies do not depend on existing state in a member,
// and so the SnapshotManager can be null in these cases.
if (_parentSnapshotManagerOpt is null || !isNullableAnalysisEnabled)
{
rewriteAndCache();
return;
}
boundRoot = NullableWalker.AnalyzeAndRewriteSpeculation(_speculatedPosition, boundRoot, binder, _parentSnapshotManagerOpt, out var newSnapshots, ref remappedSymbols);
GuardedAddBoundTreeForStandaloneSyntax(bindableRoot, boundRoot, newSnapshots, remappedSymbols);
}
else
{
rewriteAndCache();
}
BoundNode bind(CSharpSyntaxNode root, out Binder binder)
{
if (root is CompilationUnitSyntax)
{
// Top level statements are unique among our nodes: if there are no syntax nodes before local functions,
// then that means the start of the span of the top-level statement is the same as the start of the local
// function. Therefore, GetEnclosingBinder can't tell the difference, and it will get the binder for the
// local function, not for the CompilationUnitSyntax. This is desirable in almost all cases but this one:
// There are no locals or invocations before this, meaning there's nothing to call GetDeclaredSymbol,
// GetTypeInfo, or GetSymbolInfo on. GetDeclaredSymbol(CompilationUnitSyntax) goes down another path that
// does not need to do any binding whatsoever, so it also doesn't care about this behavior. The only place
// that actually needs to get the enclosing binding for a CompilationUnitSyntax in such a scenario is this
// method. So, if our root is the CompilationUnitSyntax, directly get the binder for it.
binder = RootBinder.GetBinder(root);
Debug.Assert(binder is SimpleProgramBinder);
}
else
{
binder = GetEnclosingBinder(GetAdjustedNodePosition(root));
}
return Bind(binder, root, BindingDiagnosticBag.Discarded);
}
void rewriteAndCache()
{
var diagnostics = DiagnosticBag.GetInstance();
#if DEBUG
if (!isNullableAnalysisEnabled)
{
Debug.Assert(Compilation.IsNullableAnalysisEnabledAlways);
AnalyzeBoundNodeNullability(boundRoot, binder, diagnostics, createSnapshots: true);
diagnostics.Free();
return;
}
#endif
boundRoot = RewriteNullableBoundNodesWithSnapshots(boundRoot, binder, diagnostics, createSnapshots: true, out snapshotManager, ref remappedSymbols);
diagnostics.Free();
GuardedAddBoundTreeForStandaloneSyntax(bindableRoot, boundRoot, snapshotManager, remappedSymbols);
}
}
#nullable enable
/// <summary>
/// Rewrites the given bound node with nullability information, and returns snapshots for later speculative analysis at positions inside this member.
/// </summary>
protected abstract BoundNode RewriteNullableBoundNodesWithSnapshots(
BoundNode boundRoot,
Binder binder,
DiagnosticBag diagnostics,
bool createSnapshots,
out NullableWalker.SnapshotManager? snapshotManager,
ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols);
/// <summary>
/// Performs the analysis step of getting nullability information for a semantic model but
/// does not actually use the results. This gives us extra verification of nullable flow analysis.
/// It is only used in contexts where nullable analysis is disabled in the compilation but requested
/// through "run-nullable-analysis=always" or when the compiler is running in DEBUG.
/// </summary>
protected abstract void AnalyzeBoundNodeNullability(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots);
protected abstract bool IsNullableAnalysisEnabled();
#nullable disable
/// <summary>
/// Get all bounds nodes associated with a node, ordered from highest to lowest in the bound tree.
/// Strictly speaking, the order is that of a pre-order traversal of the bound tree.
/// </summary>
internal ImmutableArray<BoundNode> GetBoundNodes(CSharpSyntaxNode node)
{
// If this method is called with a null parameter, that implies that the Root should be
// bound, but make sure that the Root is bindable.
if (node == null)
{
node = GetBindableSyntaxNode(Root);
}
Debug.Assert(node == GetBindableSyntaxNode(node));
EnsureNullabilityAnalysisPerformedIfNecessary();
// We have one SemanticModel for each method.
//
// The SemanticModel contains a lazily-built immutable map from scope-introducing
// syntactic statements (such as blocks) to binders, but not from lambdas to binders.
//
// The SemanticModel also contains a mutable map from syntax to bound nodes; that is
// declared here. Since the map is not thread-safe we ensure that it is guarded with a
// reader-writer lock.
//
// Have we already got the desired bound node in the mutable map? If so, return it.
ImmutableArray<BoundNode> results;
using (_nodeMapLock.DisposableRead())
{
results = GuardedGetBoundNodesFromMap(node);
}
if (!results.IsDefaultOrEmpty)
{
return results;
}
// We might not actually have been given an expression or statement even though we were
// allegedly given something that is "bindable".
// If we didn't find in the cached bound nodes, find a binding root and bind it.
// This will cache bound nodes under the binding root.
CSharpSyntaxNode nodeToBind = GetBindingRoot(node);
var statementBinder = GetEnclosingBinder(GetAdjustedNodePosition(nodeToBind));
Binder incrementalBinder = new IncrementalBinder(this, statementBinder);
using (_nodeMapLock.DisposableWrite())
{
BoundNode boundStatement = this.Bind(incrementalBinder, nodeToBind, BindingDiagnosticBag.Discarded);
results = GuardedAddBoundTreeAndGetBoundNodeFromMap(node, boundStatement);
}
if (!results.IsDefaultOrEmpty)
{
return results;
}
// If we still didn't find it, its still possible we could bind it directly.
// For example, types are usually not represented by bound nodes, and some error conditions and
// not yet implemented features do not create bound nodes for everything underneath them.
//
// In this case, however, we only add the single bound node we found to the map, not any child bound nodes,
// to avoid duplicates in the map if a parent of this node comes through this code path also.
var binder = GetEnclosingBinder(GetAdjustedNodePosition(node));
incrementalBinder = new IncrementalBinder(this, binder);
using (_nodeMapLock.DisposableRead())
{
results = GuardedGetBoundNodesFromMap(node);
}
if (results.IsDefaultOrEmpty)
{
// https://github.com/dotnet/roslyn/issues/35038: We have to run analysis on this node in some manner
using (_nodeMapLock.DisposableWrite())
{
var boundNode = this.Bind(incrementalBinder, node, BindingDiagnosticBag.Discarded);
GuardedAddBoundTreeForStandaloneSyntax(node, boundNode);
results = GuardedGetBoundNodesFromMap(node);
}
if (!results.IsDefaultOrEmpty)
{
return results;
}
}
else
{
return results;
}
return ImmutableArray<BoundNode>.Empty;
}
// some nodes don't have direct semantic meaning by themselves and so we need to bind a different node that does
protected internal virtual CSharpSyntaxNode GetBindableSyntaxNode(CSharpSyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.GlobalStatement:
case SyntaxKind.Subpattern:
return node;
case SyntaxKind.PositionalPatternClause:
return node.Parent;
}
while (true)
{
switch (node)
{
case ParenthesizedExpressionSyntax n:
node = n.Expression;
continue;
case CheckedExpressionSyntax n:
node = n.Expression;
continue;
// Simple mitigation to give a result for suppressions. Public API tracked by https://github.com/dotnet/roslyn/issues/26198
case PostfixUnaryExpressionSyntax { RawKind: (int)SyntaxKind.SuppressNullableWarningExpression } n:
node = n.Operand;
continue;
case UnsafeStatementSyntax n:
node = n.Block;
continue;
case CheckedStatementSyntax n:
node = n.Block;
continue;
}
break;
}
var parent = node.Parent;
if (parent != null && node != this.Root)
{
switch (node.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
var tmp = SyntaxFactory.GetStandaloneNode(node);
if (tmp != node)
{
return GetBindableSyntaxNode(tmp);
}
break;
case SyntaxKind.AnonymousObjectMemberDeclarator:
return GetBindableSyntaxNode(parent);
case SyntaxKind.VariableDeclarator: // declarators are mapped in SyntaxBinder
// When a local variable declaration contains a single declarator, the bound node
// is associated with the declaration, rather than with the declarator. If we
// used the declarator here, we would have enough context to bind it, but we wouldn't
// end up with an entry in the syntax-to-bound node map.
Debug.Assert(parent.Kind() == SyntaxKind.VariableDeclaration);
var grandparent = parent.Parent;
if (grandparent != null && grandparent.Kind() == SyntaxKind.LocalDeclarationStatement &&
((VariableDeclarationSyntax)parent).Variables.Count == 1)
{
return GetBindableSyntaxNode(parent);
}
break;
default:
if (node is QueryExpressionSyntax && parent is QueryContinuationSyntax ||
!(node is ExpressionSyntax) &&
!(node is StatementSyntax) &&
!(node is SelectOrGroupClauseSyntax) &&
!(node is QueryClauseSyntax) &&
!(node is OrderingSyntax) &&
!(node is JoinIntoClauseSyntax) &&
!(node is QueryContinuationSyntax) &&
!(node is ConstructorInitializerSyntax) &&
!(node is PrimaryConstructorBaseTypeSyntax) &&
!(node is ArrowExpressionClauseSyntax) &&
!(node is PatternSyntax))
{
return GetBindableSyntaxNode(parent);
}
break;
}
}
return node;
}
/// <summary>
/// If the node is an expression, return the nearest parent node
/// with semantic meaning. Otherwise return null.
/// </summary>
protected CSharpSyntaxNode GetBindableParentNode(CSharpSyntaxNode node)
{
if (!(node is ExpressionSyntax))
{
return null;
}
// The node is an expression, but its parent is null
CSharpSyntaxNode parent = node.Parent;
if (parent == null)
{
// For speculative model, expression might be the root of the syntax tree, in which case it can have a null parent.
if (this.IsSpeculativeSemanticModel && this.Root == node)
{
return null;
}
throw new ArgumentException($"The parent of {nameof(node)} must not be null unless this is a speculative semantic model.", nameof(node));
}
// skip up past parens and ref expressions, as we have no bound nodes for them.
while (true)
{
switch (parent.Kind())
{
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.RefExpression:
case SyntaxKind.RefType:
var pp = parent.Parent;
if (pp == null) break;
parent = pp;
break;
default:
goto foundParent;
}
}
foundParent:;
var bindableParent = this.GetBindableSyntaxNode(parent);
Debug.Assert(bindableParent != null);
// If the parent is a member used for a method invocation, then
// the node is the instance associated with the method invocation.
// In that case, return the invocation expression so that any conversion
// of the receiver can be included in the resulting SemanticInfo.
if ((bindableParent.Kind() == SyntaxKind.SimpleMemberAccessExpression) && (bindableParent.Parent.Kind() == SyntaxKind.InvocationExpression))
{
bindableParent = bindableParent.Parent;
}
else if (bindableParent.Kind() == SyntaxKind.ArrayType)
{
bindableParent = SyntaxFactory.GetStandaloneExpression((ArrayTypeSyntax)bindableParent);
}
return bindableParent;
}
internal override Symbol RemapSymbolIfNecessaryCore(Symbol symbol)
{
Debug.Assert(symbol is LocalSymbol or ParameterSymbol or MethodSymbol { MethodKind: MethodKind.LambdaMethod });
EnsureNullabilityAnalysisPerformedIfNecessary();
if (_lazyRemappedSymbols is null)
{
return symbol;
}
if (_lazyRemappedSymbols.TryGetValue(symbol, out var remappedSymbol))
{
return remappedSymbol;
}
else
{
return symbol;
}
}
internal sealed override Func<SyntaxNode, bool> GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol)
{
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// The incremental binder is used when binding statements. Whenever a statement
/// is bound, it checks the bound node cache to see if that statement was bound,
/// and returns it instead of rebinding it.
///
/// For example, we might have:
/// while (x > goo())
/// {
/// y = y * x;
/// z = z + y;
/// }
///
/// We might first get semantic info about "z", and thus bind just the statement
/// "z = z + y". Later, we might bind the entire While block. While binding the while
/// block, we can reuse the binding we did of "z = z + y".
/// </summary>
/// <remarks>
/// NOTE: any member overridden by this binder should follow the BuckStopsHereBinder pattern.
/// Otherwise, a subsequent binder in the chain could suppress the caching behavior.
/// </remarks>
internal class IncrementalBinder : Binder
{
private readonly MemberSemanticModel _semanticModel;
internal IncrementalBinder(MemberSemanticModel semanticModel, Binder next)
: base(next)
{
_semanticModel = semanticModel;
}
/// <summary>
/// We override GetBinder so that the BindStatement override is still
/// in effect on nested binders.
/// </summary>
internal override Binder GetBinder(SyntaxNode node)
{
Binder binder = this.Next.GetBinder(node);
if (binder != null)
{
Debug.Assert(!(binder is IncrementalBinder));
return new IncrementalBinder(_semanticModel, binder.WithAdditionalFlags(BinderFlags.SemanticModel));
}
return null;
}
public override BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics)
{
// Check the bound node cache to see if the statement was already bound.
if (node.SyntaxTree == _semanticModel.SyntaxTree)
{
BoundStatement synthesizedStatement = _semanticModel.GuardedGetSynthesizedStatementFromMap(node);
if (synthesizedStatement != null)
{
return synthesizedStatement;
}
BoundNode boundNode = TryGetBoundNodeFromMap(node);
if (boundNode != null)
{
return (BoundStatement)boundNode;
}
}
BoundStatement statement = base.BindStatement(node, diagnostics);
// Synthesized statements are not added to the _guardedNodeMap, we cache them explicitly here in
// _lazyGuardedSynthesizedStatementsMap
if (statement.WasCompilerGenerated && node.SyntaxTree == _semanticModel.SyntaxTree)
{
_semanticModel.GuardedAddSynthesizedStatementToMap(node, statement);
}
return statement;
}
internal override BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics)
{
BoundBlock block = (BoundBlock)TryGetBoundNodeFromMap(node);
if (block is object)
{
return block;
}
block = base.BindEmbeddedBlock(node, diagnostics);
Debug.Assert(!block.WasCompilerGenerated);
return block;
}
private BoundNode TryGetBoundNodeFromMap(CSharpSyntaxNode node)
{
if (node.SyntaxTree == _semanticModel.SyntaxTree)
{
ImmutableArray<BoundNode> boundNodes = _semanticModel.GuardedGetBoundNodesFromMap(node);
if (!boundNodes.IsDefaultOrEmpty)
{
// Already bound. Return the top-most bound node associated with the statement.
return boundNodes[0];
}
}
return null;
}
public override BoundNode BindMethodBody(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, bool includeInitializersInBody)
{
BoundNode boundNode = TryGetBoundNodeFromMap(node);
if (boundNode is object)
{
return boundNode;
}
boundNode = base.BindMethodBody(node, diagnostics, includeInitializersInBody);
return boundNode;
}
internal override BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax node, BindingDiagnosticBag diagnostics)
{
return (BoundExpressionStatement)TryGetBoundNodeFromMap(node) ?? base.BindConstructorInitializer(node, diagnostics);
}
internal override BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax node, BindingDiagnosticBag diagnostics)
{
return (BoundExpressionStatement)TryGetBoundNodeFromMap(node) ?? base.BindConstructorInitializer(node, diagnostics);
}
internal override BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax node, BindingDiagnosticBag diagnostics)
{
BoundBlock block = (BoundBlock)TryGetBoundNodeFromMap(node);
if (block is object)
{
return block;
}
block = base.BindExpressionBodyAsBlock(node, diagnostics);
return block;
}
}
}
}
| // 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Binding info for expressions and statements that are part of a member declaration.
/// </summary>
internal abstract partial class MemberSemanticModel : CSharpSemanticModel
{
private readonly Symbol _memberSymbol;
private readonly CSharpSyntaxNode _root;
private readonly ReaderWriterLockSlim _nodeMapLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
// The bound nodes associated with a syntax node, from highest in the tree to lowest.
private readonly Dictionary<SyntaxNode, ImmutableArray<BoundNode>> _guardedBoundNodeMap = new Dictionary<SyntaxNode, ImmutableArray<BoundNode>>();
private readonly Dictionary<SyntaxNode, IOperation> _guardedIOperationNodeMap = new Dictionary<SyntaxNode, IOperation>();
private Dictionary<SyntaxNode, BoundStatement> _lazyGuardedSynthesizedStatementsMap;
private NullableWalker.SnapshotManager _lazySnapshotManager;
private ImmutableDictionary<Symbol, Symbol> _lazyRemappedSymbols;
private readonly ImmutableDictionary<Symbol, Symbol> _parentRemappedSymbolsOpt;
/// <summary>
/// Only used when this is a speculative semantic model.
/// </summary>
private readonly NullableWalker.SnapshotManager _parentSnapshotManagerOpt;
internal readonly Binder RootBinder;
/// <summary>
/// Field specific to a non-speculative MemberSemanticModel that must have a containing semantic model.
/// </summary>
private readonly SyntaxTreeSemanticModel _containingSemanticModelOpt;
// Fields specific to a speculative MemberSemanticModel.
private readonly SyntaxTreeSemanticModel _parentSemanticModelOpt;
private readonly int _speculatedPosition;
private readonly Lazy<CSharpOperationFactory> _operationFactory;
protected MemberSemanticModel(
CSharpSyntaxNode root,
Symbol memberSymbol,
Binder rootBinder,
SyntaxTreeSemanticModel containingSemanticModelOpt,
SyntaxTreeSemanticModel parentSemanticModelOpt,
NullableWalker.SnapshotManager snapshotManagerOpt,
ImmutableDictionary<Symbol, Symbol> parentRemappedSymbolsOpt,
int speculatedPosition)
{
Debug.Assert(root != null);
Debug.Assert((object)memberSymbol != null);
Debug.Assert(parentSemanticModelOpt == null ^ containingSemanticModelOpt == null);
Debug.Assert(containingSemanticModelOpt == null || !containingSemanticModelOpt.IsSpeculativeSemanticModel);
Debug.Assert(parentSemanticModelOpt == null || !parentSemanticModelOpt.IsSpeculativeSemanticModel, CSharpResources.ChainingSpeculativeModelIsNotSupported);
Debug.Assert(snapshotManagerOpt == null || parentSemanticModelOpt != null);
_root = root;
_memberSymbol = memberSymbol;
this.RootBinder = rootBinder.WithAdditionalFlags(GetSemanticModelBinderFlags());
_containingSemanticModelOpt = containingSemanticModelOpt;
_parentSemanticModelOpt = parentSemanticModelOpt;
_parentSnapshotManagerOpt = snapshotManagerOpt;
_parentRemappedSymbolsOpt = parentRemappedSymbolsOpt;
_speculatedPosition = speculatedPosition;
_operationFactory = new Lazy<CSharpOperationFactory>(() => new CSharpOperationFactory(this));
}
public override CSharpCompilation Compilation
{
get
{
return (_containingSemanticModelOpt ?? _parentSemanticModelOpt).Compilation;
}
}
internal override CSharpSyntaxNode Root
{
get
{
return _root;
}
}
/// <summary>
/// The member symbol
/// </summary>
internal Symbol MemberSymbol
{
get
{
return _memberSymbol;
}
}
public sealed override bool IsSpeculativeSemanticModel
{
get
{
return _parentSemanticModelOpt != null;
}
}
public sealed override int OriginalPositionForSpeculation
{
get
{
return _speculatedPosition;
}
}
public sealed override CSharpSemanticModel ParentModel
{
get
{
return _parentSemanticModelOpt;
}
}
internal sealed override SemanticModel ContainingModelOrSelf
{
get
{
return _containingSemanticModelOpt ?? (SemanticModel)this;
}
}
internal override MemberSemanticModel GetMemberModel(SyntaxNode node)
{
// We do have to override this method, but should never call it because it might not do the right thing.
Debug.Assert(false);
return IsInTree(node) ? this : null;
}
/// <remarks>
/// This will cause the bound node cache to be populated if nullable semantic analysis is enabled.
/// </remarks>
protected virtual NullableWalker.SnapshotManager GetSnapshotManager()
{
EnsureNullabilityAnalysisPerformedIfNecessary();
Debug.Assert(_lazySnapshotManager is object || this is AttributeSemanticModel || !IsNullableAnalysisEnabled());
return _lazySnapshotManager;
}
internal ImmutableDictionary<Symbol, Symbol> GetRemappedSymbols()
{
EnsureNullabilityAnalysisPerformedIfNecessary();
Debug.Assert(_lazyRemappedSymbols is object || this is AttributeSemanticModel || !IsNullableAnalysisEnabled());
return _lazyRemappedSymbols;
}
internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out SemanticModel speculativeModel)
{
var expression = SyntaxFactory.GetStandaloneExpression(type);
var binder = this.GetSpeculativeBinder(position, expression, bindingOption);
if (binder != null)
{
speculativeModel = new SpeculativeMemberSemanticModel(parentModel, _memberSymbol, type, binder, GetSnapshotManager(), GetRemappedSymbols(), position);
return true;
}
speculativeModel = null;
return false;
}
internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel)
{
// crefs can never legally appear within members.
speculativeModel = null;
return false;
}
internal override BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
if (bindingOption == SpeculativeBindingOption.BindAsExpression && GetSnapshotManager() is { } snapshotManager)
{
crefSymbols = default;
position = CheckAndAdjustPosition(position);
expression = SyntaxFactory.GetStandaloneExpression(expression);
binder = GetSpeculativeBinder(position, expression, bindingOption);
var boundRoot = binder.BindExpression(expression, BindingDiagnosticBag.Discarded);
ImmutableDictionary<Symbol, Symbol> ignored = null;
return (BoundExpression)NullableWalker.AnalyzeAndRewriteSpeculation(position, boundRoot, binder, snapshotManager, newSnapshots: out _, remappedSymbols: ref ignored);
}
else
{
return GetSpeculativelyBoundExpressionWithoutNullability(position, expression, bindingOption, out binder, out crefSymbols);
}
}
private Binder GetEnclosingBinderInternalWithinRoot(SyntaxNode node, int position)
{
AssertPositionAdjusted(position);
return GetEnclosingBinderInternalWithinRoot(node, position, RootBinder, _root).WithAdditionalFlags(GetSemanticModelBinderFlags());
}
private static Binder GetEnclosingBinderInternalWithinRoot(SyntaxNode node, int position, Binder rootBinder, SyntaxNode root)
{
if (node == root)
{
return rootBinder.GetBinder(node) ?? rootBinder;
}
Debug.Assert(root.Contains(node));
ExpressionSyntax typeOfArgument = null;
LocalFunctionStatementSyntax ownerOfTypeParametersInScope = null;
Binder binder = null;
for (var current = node; binder == null; current = current.ParentOrStructuredTriviaParent)
{
Debug.Assert(current != null); // Why were we asked for an enclosing binder for a node outside our root?
StatementSyntax stmt = current as StatementSyntax;
TypeOfExpressionSyntax typeOfExpression;
SyntaxKind kind = current.Kind();
if (stmt != null)
{
if (LookupPosition.IsInStatementScope(position, stmt))
{
binder = rootBinder.GetBinder(current);
if (binder != null)
{
binder = AdjustBinderForPositionWithinStatement(position, binder, stmt);
}
else if (kind == SyntaxKind.LocalFunctionStatement)
{
Debug.Assert(ownerOfTypeParametersInScope == null);
var localFunction = (LocalFunctionStatementSyntax)stmt;
if (localFunction.TypeParameterList != null &&
!LookupPosition.IsBetweenTokens(position, localFunction.Identifier, localFunction.TypeParameterList.LessThanToken)) // Scope does not include method name.
{
ownerOfTypeParametersInScope = localFunction;
}
}
}
}
else if (kind == SyntaxKind.CatchClause)
{
if (LookupPosition.IsInCatchBlockScope(position, (CatchClauseSyntax)current))
{
binder = rootBinder.GetBinder(current);
}
}
else if (kind == SyntaxKind.CatchFilterClause)
{
if (LookupPosition.IsInCatchFilterScope(position, (CatchFilterClauseSyntax)current))
{
binder = rootBinder.GetBinder(current);
}
}
else if (current.IsAnonymousFunction())
{
if (LookupPosition.IsInAnonymousFunctionOrQuery(position, current))
{
binder = rootBinder.GetBinder(current.AnonymousFunctionBody());
Debug.Assert(binder != null);
}
}
else if (kind == SyntaxKind.TypeOfExpression &&
typeOfArgument == null &&
LookupPosition.IsBetweenTokens(
position,
(typeOfExpression = (TypeOfExpressionSyntax)current).OpenParenToken,
typeOfExpression.CloseParenToken))
{
typeOfArgument = typeOfExpression.Type;
}
else if (kind == SyntaxKind.SwitchSection)
{
if (LookupPosition.IsInSwitchSectionScope(position, (SwitchSectionSyntax)current))
{
binder = rootBinder.GetBinder(current);
}
}
else if (kind == SyntaxKind.ArgumentList)
{
var argList = (ArgumentListSyntax)current;
if (LookupPosition.IsBetweenTokens(position, argList.OpenParenToken, argList.CloseParenToken))
{
binder = rootBinder.GetBinder(current);
}
}
else if (kind == SyntaxKind.EqualsValueClause)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.Attribute)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.ArrowExpressionClause)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.ThisConstructorInitializer || kind == SyntaxKind.BaseConstructorInitializer || kind == SyntaxKind.PrimaryConstructorBaseType)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.ConstructorDeclaration)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.SwitchExpression)
{
binder = rootBinder.GetBinder(current);
}
else if (kind == SyntaxKind.SwitchExpressionArm)
{
binder = rootBinder.GetBinder(current);
}
else if ((current as ExpressionSyntax).IsValidScopeDesignator())
{
binder = rootBinder.GetBinder(current);
}
else
{
// If this ever breaks, make sure that all callers of
// CanHaveAssociatedLocalBinder are in sync.
Debug.Assert(!current.CanHaveAssociatedLocalBinder());
}
if (current == root)
{
break;
}
}
binder = binder ?? rootBinder.GetBinder(root) ?? rootBinder;
Debug.Assert(binder != null);
if (ownerOfTypeParametersInScope != null)
{
LocalFunctionSymbol function = GetDeclaredLocalFunction(binder, ownerOfTypeParametersInScope.Identifier);
if ((object)function != null)
{
binder = function.SignatureBinder;
}
}
if (typeOfArgument != null)
{
binder = new TypeofBinder(typeOfArgument, binder);
}
return binder;
}
private static Binder AdjustBinderForPositionWithinStatement(int position, Binder binder, StatementSyntax stmt)
{
switch (stmt.Kind())
{
case SyntaxKind.SwitchStatement:
var switchStmt = (SwitchStatementSyntax)stmt;
if (LookupPosition.IsBetweenTokens(position, switchStmt.SwitchKeyword, switchStmt.OpenBraceToken))
{
binder = binder.GetBinder(switchStmt.Expression);
Debug.Assert(binder != null);
}
break;
case SyntaxKind.ForStatement:
var forStmt = (ForStatementSyntax)stmt;
if (LookupPosition.IsBetweenTokens(position, forStmt.SecondSemicolonToken, forStmt.CloseParenToken) &&
forStmt.Incrementors.Count > 0)
{
binder = binder.GetBinder(forStmt.Incrementors.First());
Debug.Assert(binder != null);
}
else if (LookupPosition.IsBetweenTokens(position, forStmt.FirstSemicolonToken, LookupPosition.GetFirstExcludedToken(forStmt)) &&
forStmt.Condition != null)
{
binder = binder.GetBinder(forStmt.Condition);
Debug.Assert(binder != null);
}
break;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
var foreachStmt = (CommonForEachStatementSyntax)stmt;
var start = stmt.Kind() == SyntaxKind.ForEachVariableStatement ? foreachStmt.InKeyword : foreachStmt.OpenParenToken;
if (LookupPosition.IsBetweenTokens(position, start, foreachStmt.Statement.GetFirstToken()))
{
binder = binder.GetBinder(foreachStmt.Expression);
Debug.Assert(binder != null);
}
break;
}
return binder;
}
public override Conversion ClassifyConversion(
ExpressionSyntax expression,
ITypeSymbol destination,
bool isExplicitInSource = false)
{
if ((object)destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
TypeSymbol csdestination = destination.EnsureCSharpSymbolOrNull(nameof(destination));
if (expression.Kind() == SyntaxKind.DeclarationExpression)
{
// Conversion from a declaration is unspecified.
return Conversion.NoConversion;
}
// Special Case: We have to treat anonymous functions differently, because of the way
// they are cached in the syntax-to-bound node map. Specifically, UnboundLambda nodes
// never appear in the map - they are converted to BoundLambdas, even in error scenarios.
// Since a BoundLambda has a type, we would end up doing a conversion from the delegate
// type, rather than from the anonymous function expression. If we use the overload that
// takes a position, it considers the request speculative and does not use the map.
// Bonus: Since the other overload will always bind the anonymous function from scratch,
// we don't have to worry about it affecting the trial-binding cache in the "real"
// UnboundLambda node (DevDiv #854548).
if (expression.IsAnonymousFunction())
{
CheckSyntaxNode(expression);
return this.ClassifyConversion(expression.SpanStart, expression, destination, isExplicitInSource);
}
if (isExplicitInSource)
{
return ClassifyConversionForCast(expression, csdestination);
}
// Note that it is possible for an expression to be convertible to a type
// via both an implicit user-defined conversion and an explicit built-in conversion.
// In that case, this method chooses the implicit conversion.
CheckSyntaxNode(expression);
var binder = this.GetEnclosingBinderInternal(expression, GetAdjustedNodePosition(expression));
CSharpSyntaxNode bindableNode = this.GetBindableSyntaxNode(expression);
var boundExpression = this.GetLowerBoundNode(bindableNode) as BoundExpression;
if (binder == null || boundExpression == null)
{
return Conversion.NoConversion;
}
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return binder.Conversions.ClassifyConversionFromExpression(boundExpression, csdestination, ref discardedUseSiteInfo);
}
internal override Conversion ClassifyConversionForCast(
ExpressionSyntax expression,
TypeSymbol destination)
{
CheckSyntaxNode(expression);
if ((object)destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
var binder = this.GetEnclosingBinderInternal(expression, GetAdjustedNodePosition(expression));
CSharpSyntaxNode bindableNode = this.GetBindableSyntaxNode(expression);
var boundExpression = this.GetLowerBoundNode(bindableNode) as BoundExpression;
if (binder == null || boundExpression == null)
{
return Conversion.NoConversion;
}
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return binder.Conversions.ClassifyConversionFromExpression(boundExpression, destination, ref discardedUseSiteInfo, forCast: true);
}
/// <summary>
/// Get the bound node corresponding to the root.
/// </summary>
internal virtual BoundNode GetBoundRoot()
{
return GetUpperBoundNode(GetBindableSyntaxNode(this.Root));
}
/// <summary>
/// Get the highest bound node in the tree associated with a particular syntax node.
/// </summary>
internal BoundNode GetUpperBoundNode(CSharpSyntaxNode node, bool promoteToBindable = false)
{
if (promoteToBindable)
{
node = GetBindableSyntaxNode(node);
}
else
{
Debug.Assert(node == GetBindableSyntaxNode(node));
}
// The bound nodes are stored in the map from highest to lowest, so the first bound node is the highest.
var boundNodes = GetBoundNodes(node);
if (boundNodes.Length == 0)
{
return null;
}
else
{
return boundNodes[0];
}
}
/// <summary>
/// Get the lowest bound node in the tree associated with a particular syntax node. Lowest is defined as last
/// in a pre-order traversal of the bound tree.
/// </summary>
internal BoundNode GetLowerBoundNode(CSharpSyntaxNode node)
{
Debug.Assert(node == GetBindableSyntaxNode(node));
// The bound nodes are stored in the map from highest to lowest, so the last bound node is the lowest.
var boundNodes = GetBoundNodes(node);
if (boundNodes.Length == 0)
{
return null;
}
else
{
return GetLowerBoundNode(boundNodes);
}
}
private static BoundNode GetLowerBoundNode(ImmutableArray<BoundNode> boundNodes)
{
return boundNodes[boundNodes.Length - 1];
}
public override ImmutableArray<Diagnostic> GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotSupportedException();
}
public override ImmutableArray<Diagnostic> GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotSupportedException();
}
public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotSupportedException();
}
public override ImmutableArray<Diagnostic> GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotSupportedException();
}
public override INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't defined namespace inside a member.
return null;
}
public override INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't defined namespace inside a member.
return null;
}
public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define type inside a member.
return null;
}
public override INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define type inside a member.
return null;
}
public override IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define member inside member.
return null;
}
public override ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
return GetDeclaredLocalFunction(declarationSyntax).GetPublicSymbol();
}
public override ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define member inside member.
return null;
}
public override IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default)
{
return null;
}
public override IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define method inside member.
return null;
}
public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define property inside member.
return null;
}
public override IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define property inside member.
return null;
}
public override IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define indexer inside member.
return null;
}
public override IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define event inside member.
return null;
}
public override IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define accessor inside member.
return null;
}
public override IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define another member inside member.
return null;
}
public override ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
return GetDeclaredLocal(declarationSyntax, declarationSyntax.Identifier).GetPublicSymbol();
}
public override ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
return GetDeclaredLocal(declarationSyntax, declarationSyntax.Identifier).GetPublicSymbol();
}
private LocalSymbol GetDeclaredLocal(CSharpSyntaxNode declarationSyntax, SyntaxToken declaredIdentifier)
{
for (var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(declarationSyntax)); binder != null; binder = binder.Next)
{
foreach (var local in binder.Locals)
{
if (local.IdentifierToken == declaredIdentifier)
{
return GetAdjustedLocalSymbol((SourceLocalSymbol)local);
}
}
}
return null;
}
#nullable enable
internal override LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol local)
{
return GetRemappedSymbol<LocalSymbol>(local);
}
private LocalFunctionSymbol GetDeclaredLocalFunction(LocalFunctionStatementSyntax declarationSyntax)
{
var originalSymbol = GetDeclaredLocalFunction(this.GetEnclosingBinder(GetAdjustedNodePosition(declarationSyntax)), declarationSyntax.Identifier);
return GetRemappedSymbol(originalSymbol);
}
private T GetRemappedSymbol<T>(T originalSymbol) where T : Symbol
{
EnsureNullabilityAnalysisPerformedIfNecessary();
if (_lazyRemappedSymbols is null) return originalSymbol;
if (_lazyRemappedSymbols.TryGetValue(originalSymbol, out Symbol? remappedSymbol))
{
RoslynDebug.Assert(remappedSymbol is object);
return (T)remappedSymbol;
}
return originalSymbol;
}
#nullable disable
private static LocalFunctionSymbol GetDeclaredLocalFunction(Binder enclosingBinder, SyntaxToken declaredIdentifier)
{
for (var binder = enclosingBinder; binder != null; binder = binder.Next)
{
foreach (var localFunction in binder.LocalFunctions)
{
if (localFunction.NameToken == declaredIdentifier)
{
return localFunction;
}
}
}
return null;
}
public override ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(declarationSyntax));
while (binder != null && !binder.IsLabelsScopeBinder)
{
binder = binder.Next;
}
if (binder != null)
{
foreach (var label in binder.Labels)
{
if (label.IdentifierNodeOrToken.IsToken &&
label.IdentifierNodeOrToken.AsToken() == declarationSyntax.Identifier)
{
return label.GetPublicSymbol();
}
}
}
return null;
}
public override ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declarationSyntax);
var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(declarationSyntax));
while (binder != null && !(binder is SwitchBinder))
{
binder = binder.Next;
}
if (binder != null)
{
foreach (var label in binder.Labels)
{
if (label.IdentifierNodeOrToken.IsNode &&
label.IdentifierNodeOrToken.AsNode() == declarationSyntax)
{
return label.GetPublicSymbol();
}
}
}
return null;
}
public override IAliasSymbol GetDeclaredSymbol(UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define alias inside member.
return null;
}
public override IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define an extern alias inside a member.
return null;
}
public override IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Could be parameter of a lambda or a local function.
CheckSyntaxNode(declarationSyntax);
return GetLambdaOrLocalFunctionParameterSymbol(declarationSyntax, cancellationToken).GetPublicSymbol();
}
internal override ImmutableArray<ISymbol> GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define field inside member.
return ImmutableArray.Create<ISymbol>();
}
private ParameterSymbol GetLambdaOrLocalFunctionParameterSymbol(
ParameterSyntax parameter,
CancellationToken cancellationToken)
{
Debug.Assert(parameter != null);
var simpleLambda = parameter.Parent as SimpleLambdaExpressionSyntax;
if (simpleLambda != null)
{
return GetLambdaParameterSymbol(parameter, simpleLambda, cancellationToken);
}
var paramList = parameter.Parent as ParameterListSyntax;
if (paramList == null || paramList.Parent == null)
{
return null;
}
if (paramList.Parent.IsAnonymousFunction())
{
return GetLambdaParameterSymbol(parameter, (ExpressionSyntax)paramList.Parent, cancellationToken);
}
else if (paramList.Parent.Kind() == SyntaxKind.LocalFunctionStatement)
{
var localFunction = GetDeclaredSymbol((LocalFunctionStatementSyntax)paramList.Parent, cancellationToken).GetSymbol<MethodSymbol>();
if ((object)localFunction != null)
{
return GetParameterSymbol(localFunction.Parameters, parameter, cancellationToken);
}
}
return null;
}
private ParameterSymbol GetLambdaParameterSymbol(
ParameterSyntax parameter,
ExpressionSyntax lambda,
CancellationToken cancellationToken)
{
Debug.Assert(parameter != null);
Debug.Assert(lambda != null && lambda.IsAnonymousFunction());
// We should always be able to get at least an error binding for a lambda.
SymbolInfo symbolInfo = this.GetSymbolInfo(lambda, cancellationToken);
LambdaSymbol lambdaSymbol;
if ((object)symbolInfo.Symbol != null)
{
lambdaSymbol = symbolInfo.Symbol.GetSymbol<LambdaSymbol>();
}
else if (symbolInfo.CandidateSymbols.Length == 1)
{
lambdaSymbol = symbolInfo.CandidateSymbols.Single().GetSymbol<LambdaSymbol>();
}
else
{
Debug.Assert(this.GetMemberModel(lambda) == null, "Did not find a unique LambdaSymbol for lambda in member.");
return null;
}
return GetParameterSymbol(lambdaSymbol.Parameters, parameter, cancellationToken);
}
public override ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken))
{
// Can't define alias inside member.
return null;
}
public override IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return bound == null ? null : bound.DefinedSymbol.GetPublicSymbol();
}
public override IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax queryClause, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(queryClause);
return bound == null ? null : bound.DefinedSymbol.GetPublicSymbol();
}
public override IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return bound == null ? null : bound.DefinedSymbol.GetPublicSymbol();
}
public override AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node)
{
if (node.Kind() != SyntaxKind.AwaitExpression)
{
throw new ArgumentException("node.Kind==" + node.Kind());
}
var bound = GetLowerBoundNode(node);
BoundAwaitableInfo awaitableInfo = (((bound as BoundExpressionStatement)?.Expression ?? bound) as BoundAwaitExpression)?.AwaitableInfo;
if (awaitableInfo == null)
{
return default(AwaitExpressionInfo);
}
return new AwaitExpressionInfo(
getAwaiter: (IMethodSymbol)awaitableInfo.GetAwaiter?.ExpressionSymbol.GetPublicSymbol(),
isCompleted: awaitableInfo.IsCompleted.GetPublicSymbol(),
getResult: awaitableInfo.GetResult.GetPublicSymbol(),
isDynamic: awaitableInfo.IsDynamic);
}
public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node)
{
return GetForEachStatementInfo((CommonForEachStatementSyntax)node);
}
public override ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node)
{
BoundForEachStatement boundForEach = (BoundForEachStatement)GetUpperBoundNode(node);
if (boundForEach == null)
{
return default(ForEachStatementInfo);
}
ForEachEnumeratorInfo enumeratorInfoOpt = boundForEach.EnumeratorInfoOpt;
Debug.Assert(enumeratorInfoOpt != null || boundForEach.HasAnyErrors);
if (enumeratorInfoOpt == null)
{
return default(ForEachStatementInfo);
}
// Even though we usually pretend to be using System.Collection.IEnumerable
// for arrays, that doesn't make sense for pointer arrays since object
// (the type of System.Collections.IEnumerator.Current) isn't convertible
// to pointer types.
if (enumeratorInfoOpt.ElementType.IsPointerType())
{
Debug.Assert(!enumeratorInfoOpt.CurrentConversion.IsValid);
return default(ForEachStatementInfo);
}
// NOTE: we're going to list GetEnumerator, etc for array and string
// collections, even though we know that's not how the implementation
// actually enumerates them.
MethodSymbol disposeMethod = null;
if (enumeratorInfoOpt.NeedsDisposal)
{
if (enumeratorInfoOpt.PatternDisposeInfo is { Method: var method })
{
disposeMethod = method;
}
else
{
disposeMethod = enumeratorInfoOpt.IsAsync
? (MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_IAsyncDisposable__DisposeAsync)
: (MethodSymbol)Compilation.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose);
}
}
return new ForEachStatementInfo(
enumeratorInfoOpt.IsAsync,
enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(),
enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(),
currentProperty: ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter?.AssociatedSymbol).GetPublicSymbol(),
disposeMethod.GetPublicSymbol(),
enumeratorInfoOpt.ElementType.GetPublicSymbol(),
boundForEach.ElementConversion,
enumeratorInfoOpt.CurrentConversion);
}
public override DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node)
{
var boundDeconstruction = GetUpperBoundNode(node) as BoundDeconstructionAssignmentOperator;
if (boundDeconstruction is null)
{
return default;
}
var boundConversion = boundDeconstruction.Right;
Debug.Assert(boundConversion != null);
if (boundConversion is null)
{
return default;
}
return new DeconstructionInfo(boundConversion.Conversion);
}
public override DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node)
{
var boundForEach = (BoundForEachStatement)GetUpperBoundNode(node);
if (boundForEach is null)
{
return default;
}
var boundDeconstruction = boundForEach.DeconstructionOpt;
Debug.Assert(boundDeconstruction != null || boundForEach.HasAnyErrors);
if (boundDeconstruction is null)
{
return default;
}
return new DeconstructionInfo(boundDeconstruction.DeconstructionAssignment.Right.Conversion);
}
private BoundQueryClause GetBoundQueryClause(CSharpSyntaxNode node)
{
CheckSyntaxNode(node);
return this.GetLowerBoundNode(node) as BoundQueryClause;
}
private QueryClauseInfo GetQueryClauseInfo(BoundQueryClause bound)
{
if (bound == null) return default(QueryClauseInfo);
var castInfo = (bound.Cast == null) ? SymbolInfo.None : GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, bound.Cast, bound.Cast, boundNodeForSyntacticParent: null, binderOpt: null);
var operationInfo = GetSymbolInfoForQuery(bound);
return new QueryClauseInfo(castInfo: castInfo, operationInfo: operationInfo);
}
private SymbolInfo GetSymbolInfoForQuery(BoundQueryClause bound)
{
var call = bound?.Operation as BoundCall;
if (call == null)
{
return SymbolInfo.None;
}
var operation = call.IsDelegateCall ? call.ReceiverOpt : call;
return GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, operation, operation, boundNodeForSyntacticParent: null, binderOpt: null);
}
private CSharpTypeInfo GetTypeInfoForQuery(BoundQueryClause bound)
{
return bound == null ?
CSharpTypeInfo.None :
GetTypeInfoForNode(bound, bound, bound);
}
public override QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return GetQueryClauseInfo(bound);
}
public override IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declaratorSyntax);
var anonymousObjectCreation = (AnonymousObjectCreationExpressionSyntax)declaratorSyntax.Parent;
if (anonymousObjectCreation == null)
{
return null;
}
var bound = this.GetLowerBoundNode(anonymousObjectCreation) as BoundAnonymousObjectCreationExpression;
if (bound == null)
{
return null;
}
var anonymousType = bound.Type as NamedTypeSymbol;
if ((object)anonymousType == null)
{
return null;
}
int index = anonymousObjectCreation.Initializers.IndexOf(declaratorSyntax);
Debug.Assert(index >= 0);
Debug.Assert(index < anonymousObjectCreation.Initializers.Count);
return AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, index).GetPublicSymbol();
}
public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declaratorSyntax);
var bound = this.GetLowerBoundNode(declaratorSyntax) as BoundAnonymousObjectCreationExpression;
return (bound == null) ? null : (bound.Type as NamedTypeSymbol).GetPublicSymbol();
}
public override INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declaratorSyntax);
return GetTypeOfTupleLiteral(declaratorSyntax).GetPublicSymbol();
}
public override ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(declaratorSyntax);
var tupleLiteral = declaratorSyntax?.Parent as TupleExpressionSyntax;
// for now only arguments of a tuple literal may declare symbols
if (tupleLiteral == null)
{
return null;
}
var tupleLiteralType = GetTypeOfTupleLiteral(tupleLiteral);
if ((object)tupleLiteralType != null)
{
var elements = tupleLiteralType.TupleElements;
if (!elements.IsDefault)
{
var idx = tupleLiteral.Arguments.IndexOf(declaratorSyntax);
return elements[idx].GetPublicSymbol();
}
}
return null;
}
private NamedTypeSymbol GetTypeOfTupleLiteral(TupleExpressionSyntax declaratorSyntax)
{
var bound = this.GetLowerBoundNode(declaratorSyntax);
return (bound as BoundTupleExpression)?.Type as NamedTypeSymbol;
}
public override SyntaxTree SyntaxTree
{
get
{
return _root.SyntaxTree;
}
}
#nullable enable
internal override IOperation? GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken)
{
using (_nodeMapLock.DisposableRead())
{
if (_guardedIOperationNodeMap.Count != 0)
{
return guardedGetIOperation();
}
}
IOperation rootOperation = GetRootOperation();
using var _ = _nodeMapLock.DisposableWrite();
if (_guardedIOperationNodeMap.Count != 0)
{
return guardedGetIOperation();
}
OperationMapBuilder.AddToMap(rootOperation, _guardedIOperationNodeMap);
return guardedGetIOperation();
IOperation? guardedGetIOperation()
{
_nodeMapLock.AssertCanRead();
return _guardedIOperationNodeMap.TryGetValue(node, out var operation) ? operation : null;
}
}
#nullable disable
private CSharpSyntaxNode GetBindingRootOrInitializer(CSharpSyntaxNode node)
{
CSharpSyntaxNode bindingRoot = GetBindingRoot(node);
// if binding root is parameter, make it equal value
// we need to do this since node map doesn't contain bound node for parameter
if (bindingRoot is ParameterSyntax parameter && parameter.Default?.FullSpan.Contains(node.Span) == true)
{
return parameter.Default;
}
// if binding root is field variable declarator, make it initializer
// we need to do this since node map doesn't contain bound node for field/event variable declarator
if (bindingRoot is VariableDeclaratorSyntax variableDeclarator && variableDeclarator.Initializer?.FullSpan.Contains(node.Span) == true)
{
if (variableDeclarator.Parent?.Parent.IsKind(SyntaxKind.FieldDeclaration) == true ||
variableDeclarator.Parent?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) == true)
{
return variableDeclarator.Initializer;
}
}
// if binding root is enum member declaration, make it equal value
// we need to do this since node map doesn't contain bound node for enum member decl
if (bindingRoot is EnumMemberDeclarationSyntax enumMember && enumMember.EqualsValue?.FullSpan.Contains(node.Span) == true)
{
return enumMember.EqualsValue;
}
// if binding root is property member declaration, make it equal value
// we need to do this since node map doesn't contain bound node for property initializer
if (bindingRoot is PropertyDeclarationSyntax propertyMember && propertyMember.Initializer?.FullSpan.Contains(node.Span) == true)
{
return propertyMember.Initializer;
}
return bindingRoot;
}
#nullable enable
private IOperation GetRootOperation()
{
BoundNode highestBoundNode = GetBoundRoot();
Debug.Assert(highestBoundNode != null);
if (highestBoundNode is BoundGlobalStatementInitializer { Statement: var innerStatement })
{
// Script top-level field declarations use a BoundGlobalStatementInitializer to wrap initializers.
// We don't represent these nodes in IOperation, so skip it.
highestBoundNode = innerStatement;
}
// The CSharp operation factory assumes that UnboundLambda will be bound for error recovery and never be passed to the factory
// as the start of a tree to get operations for. This is guaranteed by the builder that populates the node map, as it will call
// UnboundLambda.BindForErrorRecovery() when it encounters an UnboundLambda node.
Debug.Assert(highestBoundNode.Kind != BoundKind.UnboundLambda);
IOperation operation = _operationFactory.Value.Create(highestBoundNode);
Operation.SetParentOperation(operation, null);
return operation;
}
#nullable disable
internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken))
{
ValidateSymbolInfoOptions(options);
CSharpSyntaxNode bindableNode;
BoundNode lowestBoundNode;
BoundNode highestBoundNode;
BoundNode boundParent;
GetBoundNodes(node, out bindableNode, out lowestBoundNode, out highestBoundNode, out boundParent);
Debug.Assert(IsInTree(node), "Since the node is in the tree, we can always recompute the binder later");
return base.GetSymbolInfoForNode(options, lowestBoundNode, highestBoundNode, boundParent, binderOpt: null);
}
internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
CSharpSyntaxNode bindableNode;
BoundNode lowestBoundNode;
BoundNode highestBoundNode;
BoundNode boundParent;
GetBoundNodes(node, out bindableNode, out lowestBoundNode, out highestBoundNode, out boundParent);
return GetTypeInfoForNode(lowestBoundNode, highestBoundNode, boundParent);
}
internal override ImmutableArray<Symbol> GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken))
{
CSharpSyntaxNode bindableNode;
BoundNode lowestBoundNode;
BoundNode highestBoundNode;
BoundNode boundParent;
GetBoundNodes(node, out bindableNode, out lowestBoundNode, out highestBoundNode, out boundParent);
Debug.Assert(IsInTree(node), "Since the node is in the tree, we can always recompute the binder later");
return base.GetMemberGroupForNode(options, lowestBoundNode, boundParent, binderOpt: null);
}
internal override ImmutableArray<IPropertySymbol> GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken))
{
CSharpSyntaxNode bindableNode;
BoundNode lowestBoundNode;
BoundNode highestBoundNode;
BoundNode boundParent;
GetBoundNodes(node, out bindableNode, out lowestBoundNode, out highestBoundNode, out boundParent);
Debug.Assert(IsInTree(node), "Since the node is in the tree, we can always recompute the binder later");
return base.GetIndexerGroupForNode(lowestBoundNode, binderOpt: null);
}
internal override Optional<object> GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken)
{
CSharpSyntaxNode bindableNode = this.GetBindableSyntaxNode(node);
BoundExpression boundExpr = this.GetLowerBoundNode(bindableNode) as BoundExpression;
if (boundExpr == null) return default(Optional<object>);
ConstantValue constantValue = boundExpr.ConstantValue;
return constantValue == null || constantValue.IsBad
? default(Optional<object>)
: new Optional<object>(constantValue.Value);
}
internal override SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var boundCollectionInitializer = GetLowerBoundNode(collectionInitializer) as BoundCollectionInitializerExpression;
if (boundCollectionInitializer != null)
{
var boundAdd = boundCollectionInitializer.Initializers[collectionInitializer.Expressions.IndexOf(node)];
return GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundAdd, boundAdd, null, binderOpt: null);
}
return SymbolInfo.None;
}
public override SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return GetSymbolInfoForQuery(bound);
}
public override SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return GetSymbolInfoForQuery(bound);
}
public override TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
var bound = GetBoundQueryClause(node);
return GetTypeInfoForQuery(bound);
}
private void GetBoundNodes(CSharpSyntaxNode node, out CSharpSyntaxNode bindableNode, out BoundNode lowestBoundNode, out BoundNode highestBoundNode, out BoundNode boundParent)
{
bindableNode = this.GetBindableSyntaxNode(node);
CSharpSyntaxNode bindableParent = this.GetBindableParentNode(bindableNode);
// Special handling for the Color Color case.
//
// Suppose we have:
// public class Color {
// public void M(int x) {}
// public static void M(params int[] x) {}
// }
// public class C {
// public void Test() {
// Color Color = new Color();
// System.Action<int> d = Color.M;
// }
// }
//
// We actually don't know how to interpret the "Color" in "Color.M" until we
// perform overload resolution on the method group. Now, if we were getting
// the semantic info for the method group, then bindableParent would be the
// variable declarator "d = Color.M" and so we would be able to pull the result
// of overload resolution out of the bound (method group) conversion. However,
// if we are getting the semantic info for just the "Color" part, then
// bindableParent will be the member access, which doesn't have enough information
// to determine which "Color" to use (since no overload resolution has been
// performed). We resolve this problem by detecting the case where we're looking
// up the LHS of a member access and calling GetBindableParentNode one more time.
// This gets us up to the level where the method group conversion occurs.
if (bindableParent != null && bindableParent.Kind() == SyntaxKind.SimpleMemberAccessExpression && ((MemberAccessExpressionSyntax)bindableParent).Expression == bindableNode)
{
bindableParent = this.GetBindableParentNode(bindableParent);
}
boundParent = bindableParent == null ? null : this.GetLowerBoundNode(bindableParent);
lowestBoundNode = this.GetLowerBoundNode(bindableNode);
highestBoundNode = this.GetUpperBoundNode(bindableNode);
}
// In lambda binding scenarios we need to know two things: First,
// what is the *innermost* lambda that contains the expression we're
// interested in? Second, what is the smallest expression that contains
// the *outermost* lambda that we can bind in order to get a sensible
// lambda binding?
//
// For example, suppose we have the statement:
//
// A().B(x=>x.C(y=>y.D().E())).F().G();
//
// and the user wants binding information about method group "D". We must know
// the bindable expression that is outside of every lambda:
//
// A().B(x=>x.C(y=>y.D().E()))
//
// By binding that we can determine the type of lambda parameters "x" and "y" and
// put that information in the bound tree. Once we know those facts then
// we can obtain the binding object associated with the innermost lambda:
//
// y=>y.D().E()
//
// And use that binding to obtain the analysis of:
//
// y.D
//
private CSharpSyntaxNode GetInnermostLambdaOrQuery(CSharpSyntaxNode node, int position, bool allowStarting = false)
{
Debug.Assert(node != null);
for (var current = node; current != this.Root; current = current.ParentOrStructuredTriviaParent)
{
// current can only become null if we somehow got past the root. The only way we
// could have gotten past the root is to have started outside of it. That's
// unexpected; the binding should only be asked to provide an opinion on syntax
// nodes that it knows about.
Debug.Assert(current != null, "Why are we being asked to find an enclosing lambda outside of our root?");
if (!(current.IsAnonymousFunction() || current.IsQuery()))
{
continue;
}
// If the position is not actually within the scope of the lambda, then keep
// looking.
if (!LookupPosition.IsInAnonymousFunctionOrQuery(position, current))
{
continue;
}
// If we were asked for the innermost lambda enclosing a lambda then don't return
// that; it's not enclosing anything. Only return the lambda if it's enclosing the
// original node.
if (!allowStarting && current == node)
{
continue;
}
return current;
}
// If we made it to the root, then we are not "inside" a lambda even if the root is a
// lambda. Remember, the point of this code is to get the binding that is associated
// with the innermost lambda; if we are already in a binding associated with the
// innermost lambda then we're done.
return null;
}
private void GuardedAddSynthesizedStatementToMap(StatementSyntax node, BoundStatement statement)
{
if (_lazyGuardedSynthesizedStatementsMap == null)
{
_lazyGuardedSynthesizedStatementsMap = new Dictionary<SyntaxNode, BoundStatement>();
}
_lazyGuardedSynthesizedStatementsMap.Add(node, statement);
}
private BoundStatement GuardedGetSynthesizedStatementFromMap(StatementSyntax node)
{
if (_lazyGuardedSynthesizedStatementsMap != null &&
_lazyGuardedSynthesizedStatementsMap.TryGetValue(node, out BoundStatement result))
{
return result;
}
return null;
}
private ImmutableArray<BoundNode> GuardedGetBoundNodesFromMap(CSharpSyntaxNode node)
{
Debug.Assert(_nodeMapLock.IsWriteLockHeld || _nodeMapLock.IsReadLockHeld);
ImmutableArray<BoundNode> result;
return _guardedBoundNodeMap.TryGetValue(node, out result) ? result : default(ImmutableArray<BoundNode>);
}
/// <summary>
/// Internal for test purposes only
/// </summary>
internal ImmutableArray<BoundNode> TestOnlyTryGetBoundNodesFromMap(CSharpSyntaxNode node)
{
ImmutableArray<BoundNode> result;
return _guardedBoundNodeMap.TryGetValue(node, out result) ? result : default(ImmutableArray<BoundNode>);
}
// Adds every syntax/bound pair in a tree rooted at the given bound node to the map, and the
// performs a lookup of the given syntax node in the map.
private ImmutableArray<BoundNode> GuardedAddBoundTreeAndGetBoundNodeFromMap(CSharpSyntaxNode syntax, BoundNode bound)
{
Debug.Assert(_nodeMapLock.IsWriteLockHeld);
bool alreadyInTree = false;
if (bound != null)
{
alreadyInTree = _guardedBoundNodeMap.ContainsKey(bound.Syntax);
}
// check if we already have node in the cache.
// this may happen if we have races and in such case we are no longer interested in adding
if (!alreadyInTree)
{
NodeMapBuilder.AddToMap(bound, _guardedBoundNodeMap, SyntaxTree);
Debug.Assert(syntax != _root || _guardedBoundNodeMap.ContainsKey(bound.Syntax));
}
ImmutableArray<BoundNode> result;
return _guardedBoundNodeMap.TryGetValue(syntax, out result) ? result : default(ImmutableArray<BoundNode>);
}
protected void UnguardedAddBoundTreeForStandaloneSyntax(SyntaxNode syntax, BoundNode bound, NullableWalker.SnapshotManager manager = null, ImmutableDictionary<Symbol, Symbol> remappedSymbols = null)
{
using (_nodeMapLock.DisposableWrite())
{
GuardedAddBoundTreeForStandaloneSyntax(syntax, bound, manager, remappedSymbols);
}
}
protected void GuardedAddBoundTreeForStandaloneSyntax(SyntaxNode syntax, BoundNode bound, NullableWalker.SnapshotManager manager = null, ImmutableDictionary<Symbol, Symbol> remappedSymbols = null)
{
Debug.Assert(_nodeMapLock.IsWriteLockHeld);
bool alreadyInTree = false;
// check if we already have node in the cache.
// this may happen if we have races and in such case we are no longer interested in adding
if (bound != null)
{
alreadyInTree = _guardedBoundNodeMap.ContainsKey(bound.Syntax);
}
if (!alreadyInTree)
{
if (syntax == _root || syntax is StatementSyntax)
{
// Note: For speculative model we want to always cache the entire bound tree.
// If syntax is a statement, we need to add all its children.
// Node cache assumes that if statement is cached, then all
// its children are cached too.
NodeMapBuilder.AddToMap(bound, _guardedBoundNodeMap, SyntaxTree);
Debug.Assert(syntax != _root || _guardedBoundNodeMap.ContainsKey(bound.Syntax));
}
else
{
// expressions can be added individually.
NodeMapBuilder.AddToMap(bound, _guardedBoundNodeMap, SyntaxTree, syntax);
}
Debug.Assert((manager is null && (!IsNullableAnalysisEnabled() || syntax != Root || syntax is TypeSyntax ||
// Supporting attributes is tracked by
// https://github.com/dotnet/roslyn/issues/36066
this is AttributeSemanticModel)) ||
(manager is object && remappedSymbols is object && syntax == Root && IsNullableAnalysisEnabled() && _lazySnapshotManager is null));
if (manager is object)
{
_lazySnapshotManager = manager;
_lazyRemappedSymbols = remappedSymbols;
}
}
}
// We might not have actually been given a bindable expression or statement; the caller can
// give us variable declaration nodes, for example. If we're not at an expression or
// statement, back up until we find one.
private CSharpSyntaxNode GetBindingRoot(CSharpSyntaxNode node)
{
Debug.Assert(node != null);
#if DEBUG
for (CSharpSyntaxNode current = node; current != this.Root; current = current.ParentOrStructuredTriviaParent)
{
// make sure we never go out of Root
Debug.Assert(current != null, "How did we get outside the root?");
}
#endif
for (CSharpSyntaxNode current = node; current != this.Root; current = current.ParentOrStructuredTriviaParent)
{
if (current is StatementSyntax)
{
return current;
}
switch (current.Kind())
{
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
case SyntaxKind.PrimaryConstructorBaseType:
return current;
case SyntaxKind.ArrowExpressionClause:
// If this is an arrow expression on a local function statement, then our bindable root is actually our parent syntax as it's
// a statement in a function. If this is returned directly in IOperation, we'll end up with a separate tree.
if (current.Parent == null || current.Parent.Kind() != SyntaxKind.LocalFunctionStatement)
{
return current;
}
break;
}
}
return this.Root;
}
// We want the binder in which this syntax node is going to be bound, NOT the binder which
// this syntax node *produces*. That is, suppose we have
//
// void M() { int x; { int y; { int z; } } }
//
// We want the enclosing binder of the syntax node for { int z; }. We do not want the binder
// that has local z, but rather the binder that has local y. The inner block is going to be
// bound in the context of its enclosing binder; it's contents are going to be bound in the
// context of its binder.
internal override Binder GetEnclosingBinderInternal(int position)
{
AssertPositionAdjusted(position);
// If we have a root binder with no tokens in it, position can be outside the span event
// after position is adjusted. If this happens, there can't be any
if (!this.Root.FullSpan.Contains(position))
return this.RootBinder;
SyntaxToken token = this.Root.FindToken(position);
CSharpSyntaxNode node = (CSharpSyntaxNode)token.Parent;
return GetEnclosingBinderInternal(node, position);
}
/// <summary>
/// This overload exists for callers who already have a node in hand
/// and don't want to search through the tree.
/// </summary>
private Binder GetEnclosingBinderInternal(CSharpSyntaxNode node, int position)
{
AssertPositionAdjusted(position);
CSharpSyntaxNode innerLambdaOrQuery = GetInnermostLambdaOrQuery(node, position, allowStarting: true);
// There are three possible scenarios here.
//
// 1) the node is outside all lambdas in this context, or
// 2) The node is an outermost lambda in this context, or
// 3) the node is inside the outermost lambda in this context.
//
// In the first case, no lambdas are involved at all so let's just fall back on the
// original enclosing binder code.
//
// In the second case, we have been asked to bind an entire lambda and we know it to be
// the outermost lambda in this context. Therefore the enclosing binder is going to be
// the enclosing binder of this expression. However, we do not simply want to say
// "here's the enclosing binder":
//
// void M() { Func<int, int> f = x=>x+1; }
//
// We should step out to the enclosing statement or expression, if there is one, and
// bind that.
if (innerLambdaOrQuery == null)
{
return GetEnclosingBinderInternalWithinRoot(node, position);
}
// In the third case, we're in a child lambda.
BoundNode boundInnerLambdaOrQuery = GetBoundLambdaOrQuery(innerLambdaOrQuery);
return GetEnclosingBinderInLambdaOrQuery(position, node, innerLambdaOrQuery, ref boundInnerLambdaOrQuery);
}
private BoundNode GetBoundLambdaOrQuery(CSharpSyntaxNode lambdaOrQuery)
{
// Have we already cached a bound node for it?
// If not, bind the outermost expression containing the lambda and then fill in the map.
ImmutableArray<BoundNode> nodes;
EnsureNullabilityAnalysisPerformedIfNecessary();
using (_nodeMapLock.DisposableRead())
{
nodes = GuardedGetBoundNodesFromMap(lambdaOrQuery);
}
if (!nodes.IsDefaultOrEmpty)
{
return GetLowerBoundNode(nodes);
}
// We probably never tried to bind an enclosing statement
// Let's do that
Binder lambdaRecoveryBinder;
CSharpSyntaxNode bindingRoot = GetBindingRoot(lambdaOrQuery);
CSharpSyntaxNode enclosingLambdaOrQuery = GetInnermostLambdaOrQuery(lambdaOrQuery, lambdaOrQuery.SpanStart, allowStarting: false);
BoundNode boundEnclosingLambdaOrQuery = null;
CSharpSyntaxNode nodeToBind;
if (enclosingLambdaOrQuery == null)
{
nodeToBind = bindingRoot;
lambdaRecoveryBinder = GetEnclosingBinderInternalWithinRoot(nodeToBind, GetAdjustedNodePosition(nodeToBind));
}
else
{
if (enclosingLambdaOrQuery == bindingRoot || !enclosingLambdaOrQuery.Contains(bindingRoot))
{
Debug.Assert(bindingRoot.Contains(enclosingLambdaOrQuery));
nodeToBind = lambdaOrQuery;
}
else
{
nodeToBind = bindingRoot;
}
boundEnclosingLambdaOrQuery = GetBoundLambdaOrQuery(enclosingLambdaOrQuery);
using (_nodeMapLock.DisposableRead())
{
nodes = GuardedGetBoundNodesFromMap(lambdaOrQuery);
}
if (!nodes.IsDefaultOrEmpty)
{
// If everything is working as expected we should end up here because binding the enclosing lambda
// should also take care of binding and caching this lambda.
return GetLowerBoundNode(nodes);
}
lambdaRecoveryBinder = GetEnclosingBinderInLambdaOrQuery(GetAdjustedNodePosition(nodeToBind), nodeToBind, enclosingLambdaOrQuery, ref boundEnclosingLambdaOrQuery);
}
Binder incrementalBinder = new IncrementalBinder(this, lambdaRecoveryBinder);
using (_nodeMapLock.DisposableWrite())
{
BoundNode boundOuterExpression = this.Bind(incrementalBinder, nodeToBind, BindingDiagnosticBag.Discarded);
// https://github.com/dotnet/roslyn/issues/35038: Rewrite the above node and add a test that hits this path with nullable
// enabled
nodes = GuardedAddBoundTreeAndGetBoundNodeFromMap(lambdaOrQuery, boundOuterExpression);
}
if (!nodes.IsDefaultOrEmpty)
{
return GetLowerBoundNode(nodes);
}
Debug.Assert(lambdaOrQuery != nodeToBind);
// If there is a bug in the binder such that we "lose" a sub-expression containing a
// lambda, and never put bound state for it into the bound tree, then the bound lambda
// that comes back from the map lookup will be null. This can occur in error recovery
// situations. Let's bind the node directly.
if (enclosingLambdaOrQuery == null)
{
lambdaRecoveryBinder = GetEnclosingBinderInternalWithinRoot(lambdaOrQuery, GetAdjustedNodePosition(lambdaOrQuery));
}
else
{
lambdaRecoveryBinder = GetEnclosingBinderInLambdaOrQuery(GetAdjustedNodePosition(lambdaOrQuery), lambdaOrQuery, enclosingLambdaOrQuery, ref boundEnclosingLambdaOrQuery);
}
incrementalBinder = new IncrementalBinder(this, lambdaRecoveryBinder);
using (_nodeMapLock.DisposableWrite())
{
BoundNode boundOuterExpression = this.Bind(incrementalBinder, lambdaOrQuery, BindingDiagnosticBag.Discarded);
// https://github.com/dotnet/roslyn/issues/35038: We need to do a rewrite here, and create a test that can hit this.
if (!IsNullableAnalysisEnabled() && Compilation.IsNullableAnalysisEnabledAlways)
{
AnalyzeBoundNodeNullability(boundOuterExpression, incrementalBinder, diagnostics: new DiagnosticBag(), createSnapshots: false);
}
nodes = GuardedAddBoundTreeAndGetBoundNodeFromMap(lambdaOrQuery, boundOuterExpression);
}
return GetLowerBoundNode(nodes);
}
private Binder GetEnclosingBinderInLambdaOrQuery(int position, CSharpSyntaxNode node, CSharpSyntaxNode innerLambdaOrQuery, ref BoundNode boundInnerLambdaOrQuery)
{
Debug.Assert(boundInnerLambdaOrQuery != null);
Binder result;
switch (boundInnerLambdaOrQuery.Kind)
{
case BoundKind.UnboundLambda:
boundInnerLambdaOrQuery = ((UnboundLambda)boundInnerLambdaOrQuery).BindForErrorRecovery();
goto case BoundKind.Lambda;
case BoundKind.Lambda:
AssertPositionAdjusted(position);
result = GetLambdaEnclosingBinder(position, node, innerLambdaOrQuery, ((BoundLambda)boundInnerLambdaOrQuery).Binder);
break;
case BoundKind.QueryClause:
result = GetQueryEnclosingBinder(position, node, ((BoundQueryClause)boundInnerLambdaOrQuery));
break;
default:
return GetEnclosingBinderInternalWithinRoot(node, position); // Known to return non-null with BinderFlags.SemanticModel.
}
Debug.Assert(result != null);
return result.WithAdditionalFlags(GetSemanticModelBinderFlags());
}
/// <remarks>
/// Returned binder doesn't need to have <see cref="BinderFlags.SemanticModel"/> set - the caller will add it.
/// </remarks>
private static Binder GetQueryEnclosingBinder(int position, CSharpSyntaxNode startingNode, BoundQueryClause queryClause)
{
BoundExpression node = queryClause;
do
{
switch (node.Kind)
{
case BoundKind.QueryClause:
queryClause = (BoundQueryClause)node;
node = GetQueryClauseValue(queryClause);
continue;
case BoundKind.Call:
var call = (BoundCall)node;
node = GetContainingArgument(call.Arguments, position);
if (node != null)
{
continue;
}
BoundExpression receiver = call.ReceiverOpt;
// In some error scenarios, we end-up with a method group as the receiver,
// let's get to real receiver.
while (receiver?.Kind == BoundKind.MethodGroup)
{
receiver = ((BoundMethodGroup)receiver).ReceiverOpt;
}
if (receiver != null)
{
node = GetContainingExprOrQueryClause(receiver, position);
if (node != null)
{
continue;
}
}
// TODO: should we look for the "nearest" argument as a fallback?
node = call.Arguments.LastOrDefault();
continue;
case BoundKind.Conversion:
node = ((BoundConversion)node).Operand;
continue;
case BoundKind.UnboundLambda:
var unbound = (UnboundLambda)node;
return GetEnclosingBinderInternalWithinRoot(AdjustStartingNodeAccordingToNewRoot(startingNode, unbound.Syntax),
position, unbound.BindForErrorRecovery().Binder, unbound.Syntax);
case BoundKind.Lambda:
var lambda = (BoundLambda)node;
return GetEnclosingBinderInternalWithinRoot(AdjustStartingNodeAccordingToNewRoot(startingNode, lambda.Body.Syntax),
position, lambda.Binder, lambda.Body.Syntax);
default:
goto done;
}
}
while (node != null);
done:
return GetEnclosingBinderInternalWithinRoot(AdjustStartingNodeAccordingToNewRoot(startingNode, queryClause.Syntax),
position, queryClause.Binder, queryClause.Syntax);
}
// Return the argument containing the position. For query
// expressions, the span of an argument may include other
// arguments, so the argument with the smallest span is returned.
private static BoundExpression GetContainingArgument(ImmutableArray<BoundExpression> arguments, int position)
{
BoundExpression result = null;
TextSpan resultSpan = default(TextSpan);
foreach (var arg in arguments)
{
var expr = GetContainingExprOrQueryClause(arg, position);
if (expr != null)
{
var span = expr.Syntax.FullSpan;
if (result == null || resultSpan.Contains(span))
{
result = expr;
resultSpan = span;
}
}
}
return result;
}
// Returns the expr if the syntax span contains the position;
// returns the BoundQueryClause value if expr is a BoundQueryClause
// and the value contains the position; otherwise returns null.
private static BoundExpression GetContainingExprOrQueryClause(BoundExpression expr, int position)
{
if (expr.Kind == BoundKind.QueryClause)
{
var value = GetQueryClauseValue((BoundQueryClause)expr);
if (value.Syntax.FullSpan.Contains(position))
{
return value;
}
}
if (expr.Syntax.FullSpan.Contains(position))
{
return expr;
}
return null;
}
private static BoundExpression GetQueryClauseValue(BoundQueryClause queryClause)
{
return queryClause.UnoptimizedForm ?? queryClause.Value;
}
private static SyntaxNode AdjustStartingNodeAccordingToNewRoot(SyntaxNode startingNode, SyntaxNode root)
{
SyntaxNode result = startingNode.Contains(root) ? root : startingNode;
if (result != root && !root.Contains(result))
{
result = root;
}
return result;
}
/// <summary>
/// Performs the same function as GetEnclosingBinder, but is known to take place within a
/// specified lambda. Walks up the syntax hierarchy until a node with an associated binder
/// is found.
/// </summary>
/// <remarks>
/// CONSIDER: can this share code with MemberSemanticModel.GetEnclosingBinder?
///
/// Returned binder doesn't need to have <see cref="BinderFlags.SemanticModel"/> set - the caller will add it.
/// </remarks>
private static Binder GetLambdaEnclosingBinder(int position, CSharpSyntaxNode startingNode, CSharpSyntaxNode containingLambda, Binder lambdaBinder)
{
Debug.Assert(containingLambda.IsAnonymousFunction());
Debug.Assert(LookupPosition.IsInAnonymousFunctionOrQuery(position, containingLambda));
return GetEnclosingBinderInternalWithinRoot(startingNode, position, lambdaBinder, containingLambda);
}
/// <summary>
/// If we're doing nullable analysis, we need to fully bind this member, and then run
/// nullable analysis on the resulting nodes before putting them in the map. Nullable
/// analysis does not run a subset of code, so we need to fully bind the entire member
/// first
/// </summary>
protected void EnsureNullabilityAnalysisPerformedIfNecessary()
{
bool isNullableAnalysisEnabled = IsNullableAnalysisEnabled();
if (!isNullableAnalysisEnabled && !Compilation.IsNullableAnalysisEnabledAlways)
{
return;
}
// If we have a snapshot manager, then we've already done
// all the work necessary and we should avoid taking an
// unnecessary read lock.
if (_lazySnapshotManager is object)
{
return;
}
var bindableRoot = GetBindableSyntaxNode(Root);
using var upgradeableLock = _nodeMapLock.DisposableUpgradeableRead();
// If there are already nodes in the map, then we've already done work here. Since
// EnsureNullabilityAnalysis is guaranteed to have run first, that means we've
// already bound the root node and we can just exit. We can't just assert that Root
// is in the map, as there are some models for which there is no BoundNode for the
// Root elements (such as fields, where the root is a VariableDeclarator but the
// first BoundNode corresponds to the underlying EqualsValueSyntax of the initializer)
if (_guardedBoundNodeMap.Count > 0)
{
Debug.Assert(!isNullableAnalysisEnabled ||
_guardedBoundNodeMap.ContainsKey(bindableRoot) ||
_guardedBoundNodeMap.ContainsKey(bind(bindableRoot, out _).Syntax));
return;
}
upgradeableLock.EnterWrite();
NullableWalker.SnapshotManager snapshotManager;
var remappedSymbols = _parentRemappedSymbolsOpt;
Binder binder;
BoundNode boundRoot = bind(bindableRoot, out binder);
if (IsSpeculativeSemanticModel)
{
// Not all speculative models are created with existing snapshots. Attributes,
// TypeSyntaxes, and MethodBodies do not depend on existing state in a member,
// and so the SnapshotManager can be null in these cases.
if (_parentSnapshotManagerOpt is null || !isNullableAnalysisEnabled)
{
rewriteAndCache();
return;
}
boundRoot = NullableWalker.AnalyzeAndRewriteSpeculation(_speculatedPosition, boundRoot, binder, _parentSnapshotManagerOpt, out var newSnapshots, ref remappedSymbols);
GuardedAddBoundTreeForStandaloneSyntax(bindableRoot, boundRoot, newSnapshots, remappedSymbols);
}
else
{
rewriteAndCache();
}
BoundNode bind(CSharpSyntaxNode root, out Binder binder)
{
if (root is CompilationUnitSyntax)
{
// Top level statements are unique among our nodes: if there are no syntax nodes before local functions,
// then that means the start of the span of the top-level statement is the same as the start of the local
// function. Therefore, GetEnclosingBinder can't tell the difference, and it will get the binder for the
// local function, not for the CompilationUnitSyntax. This is desirable in almost all cases but this one:
// There are no locals or invocations before this, meaning there's nothing to call GetDeclaredSymbol,
// GetTypeInfo, or GetSymbolInfo on. GetDeclaredSymbol(CompilationUnitSyntax) goes down another path that
// does not need to do any binding whatsoever, so it also doesn't care about this behavior. The only place
// that actually needs to get the enclosing binding for a CompilationUnitSyntax in such a scenario is this
// method. So, if our root is the CompilationUnitSyntax, directly get the binder for it.
binder = RootBinder.GetBinder(root);
Debug.Assert(binder is SimpleProgramBinder);
}
else
{
binder = GetEnclosingBinder(GetAdjustedNodePosition(root));
}
return Bind(binder, root, BindingDiagnosticBag.Discarded);
}
void rewriteAndCache()
{
var diagnostics = DiagnosticBag.GetInstance();
#if DEBUG
if (!isNullableAnalysisEnabled)
{
Debug.Assert(Compilation.IsNullableAnalysisEnabledAlways);
AnalyzeBoundNodeNullability(boundRoot, binder, diagnostics, createSnapshots: true);
diagnostics.Free();
return;
}
#endif
boundRoot = RewriteNullableBoundNodesWithSnapshots(boundRoot, binder, diagnostics, createSnapshots: true, out snapshotManager, ref remappedSymbols);
diagnostics.Free();
GuardedAddBoundTreeForStandaloneSyntax(bindableRoot, boundRoot, snapshotManager, remappedSymbols);
}
}
#nullable enable
/// <summary>
/// Rewrites the given bound node with nullability information, and returns snapshots for later speculative analysis at positions inside this member.
/// </summary>
protected abstract BoundNode RewriteNullableBoundNodesWithSnapshots(
BoundNode boundRoot,
Binder binder,
DiagnosticBag diagnostics,
bool createSnapshots,
out NullableWalker.SnapshotManager? snapshotManager,
ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols);
/// <summary>
/// Performs the analysis step of getting nullability information for a semantic model but
/// does not actually use the results. This gives us extra verification of nullable flow analysis.
/// It is only used in contexts where nullable analysis is disabled in the compilation but requested
/// through "run-nullable-analysis=always" or when the compiler is running in DEBUG.
/// </summary>
protected abstract void AnalyzeBoundNodeNullability(BoundNode boundRoot, Binder binder, DiagnosticBag diagnostics, bool createSnapshots);
protected abstract bool IsNullableAnalysisEnabled();
#nullable disable
/// <summary>
/// Get all bounds nodes associated with a node, ordered from highest to lowest in the bound tree.
/// Strictly speaking, the order is that of a pre-order traversal of the bound tree.
/// </summary>
internal ImmutableArray<BoundNode> GetBoundNodes(CSharpSyntaxNode node)
{
// If this method is called with a null parameter, that implies that the Root should be
// bound, but make sure that the Root is bindable.
if (node == null)
{
node = GetBindableSyntaxNode(Root);
}
Debug.Assert(node == GetBindableSyntaxNode(node));
EnsureNullabilityAnalysisPerformedIfNecessary();
// We have one SemanticModel for each method.
//
// The SemanticModel contains a lazily-built immutable map from scope-introducing
// syntactic statements (such as blocks) to binders, but not from lambdas to binders.
//
// The SemanticModel also contains a mutable map from syntax to bound nodes; that is
// declared here. Since the map is not thread-safe we ensure that it is guarded with a
// reader-writer lock.
//
// Have we already got the desired bound node in the mutable map? If so, return it.
ImmutableArray<BoundNode> results;
using (_nodeMapLock.DisposableRead())
{
results = GuardedGetBoundNodesFromMap(node);
}
if (!results.IsDefaultOrEmpty)
{
return results;
}
// We might not actually have been given an expression or statement even though we were
// allegedly given something that is "bindable".
// If we didn't find in the cached bound nodes, find a binding root and bind it.
// This will cache bound nodes under the binding root.
CSharpSyntaxNode nodeToBind = GetBindingRoot(node);
var statementBinder = GetEnclosingBinder(GetAdjustedNodePosition(nodeToBind));
Binder incrementalBinder = new IncrementalBinder(this, statementBinder);
using (_nodeMapLock.DisposableWrite())
{
BoundNode boundStatement = this.Bind(incrementalBinder, nodeToBind, BindingDiagnosticBag.Discarded);
results = GuardedAddBoundTreeAndGetBoundNodeFromMap(node, boundStatement);
}
if (!results.IsDefaultOrEmpty)
{
return results;
}
// If we still didn't find it, its still possible we could bind it directly.
// For example, types are usually not represented by bound nodes, and some error conditions and
// not yet implemented features do not create bound nodes for everything underneath them.
//
// In this case, however, we only add the single bound node we found to the map, not any child bound nodes,
// to avoid duplicates in the map if a parent of this node comes through this code path also.
var binder = GetEnclosingBinder(GetAdjustedNodePosition(node));
incrementalBinder = new IncrementalBinder(this, binder);
using (_nodeMapLock.DisposableRead())
{
results = GuardedGetBoundNodesFromMap(node);
}
if (results.IsDefaultOrEmpty)
{
// https://github.com/dotnet/roslyn/issues/35038: We have to run analysis on this node in some manner
using (_nodeMapLock.DisposableWrite())
{
var boundNode = this.Bind(incrementalBinder, node, BindingDiagnosticBag.Discarded);
GuardedAddBoundTreeForStandaloneSyntax(node, boundNode);
results = GuardedGetBoundNodesFromMap(node);
}
if (!results.IsDefaultOrEmpty)
{
return results;
}
}
else
{
return results;
}
return ImmutableArray<BoundNode>.Empty;
}
// some nodes don't have direct semantic meaning by themselves and so we need to bind a different node that does
protected internal virtual CSharpSyntaxNode GetBindableSyntaxNode(CSharpSyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.GlobalStatement:
case SyntaxKind.Subpattern:
return node;
case SyntaxKind.PositionalPatternClause:
return node.Parent;
}
while (true)
{
switch (node)
{
case ParenthesizedExpressionSyntax n:
node = n.Expression;
continue;
case CheckedExpressionSyntax n:
node = n.Expression;
continue;
// Simple mitigation to give a result for suppressions. Public API tracked by https://github.com/dotnet/roslyn/issues/26198
case PostfixUnaryExpressionSyntax { RawKind: (int)SyntaxKind.SuppressNullableWarningExpression } n:
node = n.Operand;
continue;
case UnsafeStatementSyntax n:
node = n.Block;
continue;
case CheckedStatementSyntax n:
node = n.Block;
continue;
}
break;
}
var parent = node.Parent;
if (parent != null && node != this.Root)
{
switch (node.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
var tmp = SyntaxFactory.GetStandaloneNode(node);
if (tmp != node)
{
return GetBindableSyntaxNode(tmp);
}
break;
case SyntaxKind.AnonymousObjectMemberDeclarator:
return GetBindableSyntaxNode(parent);
case SyntaxKind.VariableDeclarator: // declarators are mapped in SyntaxBinder
// When a local variable declaration contains a single declarator, the bound node
// is associated with the declaration, rather than with the declarator. If we
// used the declarator here, we would have enough context to bind it, but we wouldn't
// end up with an entry in the syntax-to-bound node map.
Debug.Assert(parent.Kind() == SyntaxKind.VariableDeclaration);
var grandparent = parent.Parent;
if (grandparent != null && grandparent.Kind() == SyntaxKind.LocalDeclarationStatement &&
((VariableDeclarationSyntax)parent).Variables.Count == 1)
{
return GetBindableSyntaxNode(parent);
}
break;
default:
if (node is QueryExpressionSyntax && parent is QueryContinuationSyntax ||
!(node is ExpressionSyntax) &&
!(node is StatementSyntax) &&
!(node is SelectOrGroupClauseSyntax) &&
!(node is QueryClauseSyntax) &&
!(node is OrderingSyntax) &&
!(node is JoinIntoClauseSyntax) &&
!(node is QueryContinuationSyntax) &&
!(node is ConstructorInitializerSyntax) &&
!(node is PrimaryConstructorBaseTypeSyntax) &&
!(node is ArrowExpressionClauseSyntax) &&
!(node is PatternSyntax))
{
return GetBindableSyntaxNode(parent);
}
break;
}
}
return node;
}
/// <summary>
/// If the node is an expression, return the nearest parent node
/// with semantic meaning. Otherwise return null.
/// </summary>
protected CSharpSyntaxNode GetBindableParentNode(CSharpSyntaxNode node)
{
if (!(node is ExpressionSyntax))
{
return null;
}
// The node is an expression, but its parent is null
CSharpSyntaxNode parent = node.Parent;
if (parent == null)
{
// For speculative model, expression might be the root of the syntax tree, in which case it can have a null parent.
if (this.IsSpeculativeSemanticModel && this.Root == node)
{
return null;
}
throw new ArgumentException($"The parent of {nameof(node)} must not be null unless this is a speculative semantic model.", nameof(node));
}
// skip up past parens and ref expressions, as we have no bound nodes for them.
while (true)
{
switch (parent.Kind())
{
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.RefExpression:
case SyntaxKind.RefType:
var pp = parent.Parent;
if (pp == null) break;
parent = pp;
break;
default:
goto foundParent;
}
}
foundParent:;
var bindableParent = this.GetBindableSyntaxNode(parent);
Debug.Assert(bindableParent != null);
// If the parent is a member used for a method invocation, then
// the node is the instance associated with the method invocation.
// In that case, return the invocation expression so that any conversion
// of the receiver can be included in the resulting SemanticInfo.
if ((bindableParent.Kind() == SyntaxKind.SimpleMemberAccessExpression) && (bindableParent.Parent.Kind() == SyntaxKind.InvocationExpression))
{
bindableParent = bindableParent.Parent;
}
else if (bindableParent.Kind() == SyntaxKind.ArrayType)
{
bindableParent = SyntaxFactory.GetStandaloneExpression((ArrayTypeSyntax)bindableParent);
}
return bindableParent;
}
internal override Symbol RemapSymbolIfNecessaryCore(Symbol symbol)
{
Debug.Assert(symbol is LocalSymbol or ParameterSymbol or MethodSymbol { MethodKind: MethodKind.LambdaMethod });
EnsureNullabilityAnalysisPerformedIfNecessary();
if (_lazyRemappedSymbols is null)
{
return symbol;
}
if (_lazyRemappedSymbols.TryGetValue(symbol, out var remappedSymbol))
{
return remappedSymbol;
}
else
{
return symbol;
}
}
internal sealed override Func<SyntaxNode, bool> GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol)
{
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// The incremental binder is used when binding statements. Whenever a statement
/// is bound, it checks the bound node cache to see if that statement was bound,
/// and returns it instead of rebinding it.
///
/// For example, we might have:
/// while (x > goo())
/// {
/// y = y * x;
/// z = z + y;
/// }
///
/// We might first get semantic info about "z", and thus bind just the statement
/// "z = z + y". Later, we might bind the entire While block. While binding the while
/// block, we can reuse the binding we did of "z = z + y".
/// </summary>
/// <remarks>
/// NOTE: any member overridden by this binder should follow the BuckStopsHereBinder pattern.
/// Otherwise, a subsequent binder in the chain could suppress the caching behavior.
/// </remarks>
internal class IncrementalBinder : Binder
{
private readonly MemberSemanticModel _semanticModel;
internal IncrementalBinder(MemberSemanticModel semanticModel, Binder next)
: base(next)
{
_semanticModel = semanticModel;
}
/// <summary>
/// We override GetBinder so that the BindStatement override is still
/// in effect on nested binders.
/// </summary>
internal override Binder GetBinder(SyntaxNode node)
{
Binder binder = this.Next.GetBinder(node);
if (binder != null)
{
Debug.Assert(!(binder is IncrementalBinder));
return new IncrementalBinder(_semanticModel, binder.WithAdditionalFlags(BinderFlags.SemanticModel));
}
return null;
}
public override BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics)
{
// Check the bound node cache to see if the statement was already bound.
if (node.SyntaxTree == _semanticModel.SyntaxTree)
{
BoundStatement synthesizedStatement = _semanticModel.GuardedGetSynthesizedStatementFromMap(node);
if (synthesizedStatement != null)
{
return synthesizedStatement;
}
BoundNode boundNode = TryGetBoundNodeFromMap(node);
if (boundNode != null)
{
return (BoundStatement)boundNode;
}
}
BoundStatement statement = base.BindStatement(node, diagnostics);
// Synthesized statements are not added to the _guardedNodeMap, we cache them explicitly here in
// _lazyGuardedSynthesizedStatementsMap
if (statement.WasCompilerGenerated && node.SyntaxTree == _semanticModel.SyntaxTree)
{
_semanticModel.GuardedAddSynthesizedStatementToMap(node, statement);
}
return statement;
}
internal override BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics)
{
BoundBlock block = (BoundBlock)TryGetBoundNodeFromMap(node);
if (block is object)
{
return block;
}
block = base.BindEmbeddedBlock(node, diagnostics);
Debug.Assert(!block.WasCompilerGenerated);
return block;
}
private BoundNode TryGetBoundNodeFromMap(CSharpSyntaxNode node)
{
if (node.SyntaxTree == _semanticModel.SyntaxTree)
{
ImmutableArray<BoundNode> boundNodes = _semanticModel.GuardedGetBoundNodesFromMap(node);
if (!boundNodes.IsDefaultOrEmpty)
{
// Already bound. Return the top-most bound node associated with the statement.
return boundNodes[0];
}
}
return null;
}
public override BoundNode BindMethodBody(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics, bool includeInitializersInBody)
{
BoundNode boundNode = TryGetBoundNodeFromMap(node);
if (boundNode is object)
{
return boundNode;
}
boundNode = base.BindMethodBody(node, diagnostics, includeInitializersInBody);
return boundNode;
}
internal override BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax node, BindingDiagnosticBag diagnostics)
{
return (BoundExpressionStatement)TryGetBoundNodeFromMap(node) ?? base.BindConstructorInitializer(node, diagnostics);
}
internal override BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax node, BindingDiagnosticBag diagnostics)
{
return (BoundExpressionStatement)TryGetBoundNodeFromMap(node) ?? base.BindConstructorInitializer(node, diagnostics);
}
internal override BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax node, BindingDiagnosticBag diagnostics)
{
BoundBlock block = (BoundBlock)TryGetBoundNodeFromMap(node);
if (block is object)
{
return block;
}
block = base.BindExpressionBodyAsBlock(node, diagnostics);
return block;
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Core/Portable/SourceGeneration/GeneratorState.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.Diagnostics;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents the current state of a generator
/// </summary>
internal readonly struct GeneratorState
{
/// <summary>
/// Creates a new generator state that just contains information
/// </summary>
public GeneratorState(GeneratorInfo info)
: this(info, ImmutableArray<GeneratedSyntaxTree>.Empty)
{
}
/// <summary>
/// Creates a new generator state that contains information and constant trees
/// </summary>
public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees)
: this(info, postInitTrees, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty)
{
}
/// <summary>
/// Creates a new generator state that contains information, constant trees and an execution pipeline
/// </summary>
public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes)
: this(info, postInitTrees, inputNodes, outputNodes, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<Diagnostic>.Empty, exception: null)
{
}
/// <summary>
/// Creates a new generator state that contains an exception and the associated diagnostic
/// </summary>
public GeneratorState(GeneratorInfo info, Exception e, Diagnostic error)
: this(info, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray.Create(error), exception: e)
{
}
/// <summary>
/// Creates a generator state that contains results
/// </summary>
public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics)
: this(info, postInitTrees, inputNodes, outputNodes, generatedTrees, diagnostics, exception: null)
{
}
private GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics, Exception? exception)
{
this.Initialized = true;
this.PostInitTrees = postInitTrees;
this.InputNodes = inputNodes;
this.OutputNodes = outputNodes;
this.GeneratedTrees = generatedTrees;
this.Info = info;
this.Diagnostics = diagnostics;
this.Exception = exception;
}
internal bool Initialized { get; }
internal ImmutableArray<GeneratedSyntaxTree> PostInitTrees { get; }
internal ImmutableArray<ISyntaxInputNode> InputNodes { get; }
internal ImmutableArray<IIncrementalGeneratorOutputNode> OutputNodes { get; }
internal ImmutableArray<GeneratedSyntaxTree> GeneratedTrees { get; }
internal GeneratorInfo Info { get; }
internal Exception? Exception { get; }
internal ImmutableArray<Diagnostic> Diagnostics { 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.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents the current state of a generator
/// </summary>
internal readonly struct GeneratorState
{
/// <summary>
/// Creates a new generator state that just contains information
/// </summary>
public GeneratorState(GeneratorInfo info)
: this(info, ImmutableArray<GeneratedSyntaxTree>.Empty)
{
}
/// <summary>
/// Creates a new generator state that contains information and constant trees
/// </summary>
public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees)
: this(info, postInitTrees, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty)
{
}
/// <summary>
/// Creates a new generator state that contains information, constant trees and an execution pipeline
/// </summary>
public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes)
: this(info, postInitTrees, inputNodes, outputNodes, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<Diagnostic>.Empty, exception: null)
{
}
/// <summary>
/// Creates a new generator state that contains an exception and the associated diagnostic
/// </summary>
public GeneratorState(GeneratorInfo info, Exception e, Diagnostic error)
: this(info, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray.Create(error), exception: e)
{
}
/// <summary>
/// Creates a generator state that contains results
/// </summary>
public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics)
: this(info, postInitTrees, inputNodes, outputNodes, generatedTrees, diagnostics, exception: null)
{
}
private GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics, Exception? exception)
{
this.Initialized = true;
this.PostInitTrees = postInitTrees;
this.InputNodes = inputNodes;
this.OutputNodes = outputNodes;
this.GeneratedTrees = generatedTrees;
this.Info = info;
this.Diagnostics = diagnostics;
this.Exception = exception;
}
internal bool Initialized { get; }
internal ImmutableArray<GeneratedSyntaxTree> PostInitTrees { get; }
internal ImmutableArray<ISyntaxInputNode> InputNodes { get; }
internal ImmutableArray<IIncrementalGeneratorOutputNode> OutputNodes { get; }
internal ImmutableArray<GeneratedSyntaxTree> GeneratedTrees { get; }
internal GeneratorInfo Info { get; }
internal Exception? Exception { get; }
internal ImmutableArray<Diagnostic> Diagnostics { get; }
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralOptions.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 Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral
{
internal class SplitStringLiteralOptions
{
public static PerLanguageOption2<bool> Enabled =
new(nameof(SplitStringLiteralOptions), nameof(Enabled), defaultValue: true,
storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitStringLiterals"));
}
[ExportOptionProvider(LanguageNames.CSharp), Shared]
internal class SplitStringLiteralOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SplitStringLiteralOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
SplitStringLiteralOptions.Enabled);
}
}
| // 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 Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral
{
internal class SplitStringLiteralOptions
{
public static PerLanguageOption2<bool> Enabled =
new(nameof(SplitStringLiteralOptions), nameof(Enabled), defaultValue: true,
storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitStringLiterals"));
}
[ExportOptionProvider(LanguageNames.CSharp), Shared]
internal class SplitStringLiteralOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SplitStringLiteralOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
SplitStringLiteralOptions.Enabled);
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/VisualBasic/Portable/CommentSelection/VisualBasicCommentSelectionService.vb | ' 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.
Imports System.Composition
Imports Microsoft.CodeAnalysis.CommentSelection
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.VisualBasic.CommentSelection
<ExportLanguageService(GetType(ICommentSelectionService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicCommentSelectionService
Inherits AbstractCommentSelectionService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Overrides ReadOnly Property SingleLineCommentString As String = "'"
Public Overrides ReadOnly Property SupportsBlockComment As Boolean
Public Overrides ReadOnly Property BlockCommentEndString As String
Get
Throw New NotSupportedException()
End Get
End Property
Public Overrides ReadOnly Property BlockCommentStartString As String
Get
Throw New NotSupportedException()
End Get
End Property
End Class
End Namespace
| ' 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.
Imports System.Composition
Imports Microsoft.CodeAnalysis.CommentSelection
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.VisualBasic.CommentSelection
<ExportLanguageService(GetType(ICommentSelectionService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicCommentSelectionService
Inherits AbstractCommentSelectionService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Overrides ReadOnly Property SingleLineCommentString As String = "'"
Public Overrides ReadOnly Property SupportsBlockComment As Boolean
Public Overrides ReadOnly Property BlockCommentEndString As String
Get
Throw New NotSupportedException()
End Get
End Property
Public Overrides ReadOnly Property BlockCommentStartString As String
Get
Throw New NotSupportedException()
End Get
End Property
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.ParameterSymbolKey.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;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class ParameterSymbolKey
{
public static void Create(IParameterSymbol symbol, SymbolKeyWriter visitor)
{
visitor.WriteString(symbol.MetadataName);
visitor.WriteSymbolKey(symbol.ContainingSymbol);
}
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var metadataName = reader.ReadString()!;
var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason);
if (containingSymbolFailureReason != null)
{
failureReason = $"({nameof(ParameterSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})";
return default;
}
using var result = PooledArrayBuilder<IParameterSymbol>.GetInstance();
foreach (var container in containingSymbolResolution)
{
switch (container)
{
case IMethodSymbol method:
Resolve(result, reader, metadataName, method.Parameters);
break;
case IPropertySymbol property:
Resolve(result, reader, metadataName, property.Parameters);
break;
case IEventSymbol eventSymbol:
// Parameters can be owned by events in VB. i.e. it's legal in VB to have:
//
// Public Event E(a As Integer, b As Integer);
//
// In this case it's equivalent to:
//
// Public Delegate UnutterableCompilerName(a As Integer, b As Integer)
// public Event E As UnutterableCompilerName
//
// So, in this case, to resolve the parameter, we go have to map the event,
// then find the delegate it returns, then find the parameter in the delegate's
// 'Invoke' method.
var delegateInvoke = (eventSymbol.Type as INamedTypeSymbol)?.DelegateInvokeMethod;
if (delegateInvoke != null)
{
Resolve(result, reader, metadataName, delegateInvoke.Parameters);
}
break;
}
}
return CreateResolution(result, $"({nameof(ParameterSymbolKey)} '{metadataName}' not found)", out failureReason);
}
private static void Resolve(
PooledArrayBuilder<IParameterSymbol> result, SymbolKeyReader reader,
string metadataName, ImmutableArray<IParameterSymbol> parameters)
{
foreach (var parameter in parameters)
{
if (SymbolKey.Equals(reader.Compilation, parameter.MetadataName, metadataName))
{
result.AddIfNotNull(parameter);
}
}
}
}
}
}
| // 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;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class ParameterSymbolKey
{
public static void Create(IParameterSymbol symbol, SymbolKeyWriter visitor)
{
visitor.WriteString(symbol.MetadataName);
visitor.WriteSymbolKey(symbol.ContainingSymbol);
}
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var metadataName = reader.ReadString()!;
var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason);
if (containingSymbolFailureReason != null)
{
failureReason = $"({nameof(ParameterSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})";
return default;
}
using var result = PooledArrayBuilder<IParameterSymbol>.GetInstance();
foreach (var container in containingSymbolResolution)
{
switch (container)
{
case IMethodSymbol method:
Resolve(result, reader, metadataName, method.Parameters);
break;
case IPropertySymbol property:
Resolve(result, reader, metadataName, property.Parameters);
break;
case IEventSymbol eventSymbol:
// Parameters can be owned by events in VB. i.e. it's legal in VB to have:
//
// Public Event E(a As Integer, b As Integer);
//
// In this case it's equivalent to:
//
// Public Delegate UnutterableCompilerName(a As Integer, b As Integer)
// public Event E As UnutterableCompilerName
//
// So, in this case, to resolve the parameter, we go have to map the event,
// then find the delegate it returns, then find the parameter in the delegate's
// 'Invoke' method.
var delegateInvoke = (eventSymbol.Type as INamedTypeSymbol)?.DelegateInvokeMethod;
if (delegateInvoke != null)
{
Resolve(result, reader, metadataName, delegateInvoke.Parameters);
}
break;
}
}
return CreateResolution(result, $"({nameof(ParameterSymbolKey)} '{metadataName}' not found)", out failureReason);
}
private static void Resolve(
PooledArrayBuilder<IParameterSymbol> result, SymbolKeyReader reader,
string metadataName, ImmutableArray<IParameterSymbol> parameters)
{
foreach (var parameter in parameters)
{
if (SymbolKey.Equals(reader.Compilation, parameter.MetadataName, metadataName))
{
result.AddIfNotNull(parameter);
}
}
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/MSBuild/MSBuild/VisualBasic/VisualBasicProjectFile.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 Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.MSBuild.Build;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.VisualBasic
{
internal class VisualBasicProjectFile : ProjectFile
{
public VisualBasicProjectFile(VisualBasicProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log)
: base(loader, loadedProject, buildManager, log)
{
}
protected override SourceCodeKind GetSourceCodeKind(string documentFileName)
=> SourceCodeKind.Regular;
public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
=> ".vb";
protected override IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject)
=> executedProject.GetItems(ItemNames.VbcCommandLineArgs);
protected override ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project)
=> VisualBasicCommandLineArgumentReader.Read(project);
}
}
| // 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 Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.MSBuild.Build;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.VisualBasic
{
internal class VisualBasicProjectFile : ProjectFile
{
public VisualBasicProjectFile(VisualBasicProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log)
: base(loader, loadedProject, buildManager, log)
{
}
protected override SourceCodeKind GetSourceCodeKind(string documentFileName)
=> SourceCodeKind.Regular;
public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
=> ".vb";
protected override IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject)
=> executedProject.GetItems(ItemNames.VbcCommandLineArgs);
protected override ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project)
=> VisualBasicCommandLineArgumentReader.Read(project);
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/CSharpSyntaxClassificationServiceFactory.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 Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.Classification.SyntaxClassification
{
[ExportLanguageServiceFactory(typeof(ISyntaxClassificationService), LanguageNames.CSharp), Shared]
internal class CSharpSyntaxClassificationServiceFactory : ILanguageServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpSyntaxClassificationServiceFactory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public ILanguageService CreateLanguageService(HostLanguageServices languageServices)
=> new CSharpSyntaxClassificationService(languageServices);
}
}
| // 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 Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.Classification.SyntaxClassification
{
[ExportLanguageServiceFactory(typeof(ISyntaxClassificationService), LanguageNames.CSharp), Shared]
internal class CSharpSyntaxClassificationServiceFactory : ILanguageServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpSyntaxClassificationServiceFactory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public ILanguageService CreateLanguageService(HostLanguageServices languageServices)
=> new CSharpSyntaxClassificationService(languageServices);
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Test/CommandLine/TouchedFileLoggingTests.vb | ' 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.
Imports System.Globalization
Imports System.IO
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities.SharedResourceHelpers
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests
Public Class TouchedFileLoggingTests
Inherits BasicTestBase
Private Shared ReadOnly s_libDirectory As String = Environment.GetEnvironmentVariable("LIB")
Private ReadOnly _baseDirectory As String = TempRoot.Root
Private ReadOnly _helloWorldCS As String = <text>
Imports System
Class C
Shared Sub Main(args As String())
Console.WriteLine("Hello, world")
End Sub
End Class
</text>.Value
<Fact>
Public Sub TrivialSourceFileOnlyVbc()
Dim hello = Temp.CreateFile().WriteAllText(_helloWorldCS).Path
Dim touchedDir = Temp.CreateDirectory()
Dim touchedBase = Path.Combine(touchedDir.Path, "touched")
Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory,
{"/nologo",
"/touchedfiles:" + touchedBase,
hello})
Dim outWriter = New StringWriter(CultureInfo.InvariantCulture)
Dim expectedReads As List(Of String) = Nothing
Dim expectedWrites As List(Of String) = Nothing
BuildTouchedFiles(cmd,
Path.ChangeExtension(hello, "exe"),
expectedReads,
expectedWrites)
Dim exitCode = cmd.Run(outWriter, Nothing)
Assert.Equal("", outWriter.ToString().Trim())
Assert.Equal(0, exitCode)
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase)
CleanupAllGeneratedFiles(hello)
End Sub
<Fact>
Public Sub StrongNameKeyVbc()
Dim hello = Temp.CreateFile().WriteAllText(_helloWorldCS).Path
Dim snkPath = Temp.CreateFile("TestKeyPair_", ".snk").WriteAllBytes(TestResources.General.snKey).Path
Dim touchedDir = Temp.CreateDirectory()
Dim touchedBase = Path.Combine(touchedDir.Path, "touched")
Dim outWriter = New StringWriter(CultureInfo.InvariantCulture)
Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory,
{"/nologo",
"/touchedfiles:" + touchedBase,
"/keyfile:" + snkPath,
hello})
Dim expectedReads As List(Of String) = Nothing
Dim expectedWrites As List(Of String) = Nothing
BuildTouchedFiles(cmd,
Path.ChangeExtension(hello, "exe"),
expectedReads,
expectedWrites)
expectedReads.Add(snkPath)
Dim exitCode = cmd.Run(outWriter, Nothing)
Assert.Equal(String.Empty, outWriter.ToString().Trim())
Assert.Equal(0, exitCode)
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase)
CleanupAllGeneratedFiles(hello)
CleanupAllGeneratedFiles(snkPath)
End Sub
<Fact>
Public Sub XmlDocumentFileVbc()
Dim sourcePath = Temp.CreateFile().WriteAllText(
<text><![CDATA[
''' <summary>
''' A subtype of <see cref="object" />.
''' </summary>
Public Class C
End Class
]]></text>.Value).Path
Dim xml = Temp.CreateFile()
Dim touchedDir = Temp.CreateDirectory()
Dim touchedBase = Path.Combine(touchedDir.Path, "touched")
Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory,
{"/nologo",
"/target:library",
"/doc:" + xml.Path,
"/touchedfiles:" + touchedBase,
sourcePath})
' Build touched files
Dim expectedReads As List(Of String) = Nothing
Dim expectedWrites As List(Of String) = Nothing
BuildTouchedFiles(cmd,
Path.ChangeExtension(sourcePath, "dll"),
expectedReads,
expectedWrites)
expectedWrites.Add(xml.Path)
Dim writer = New StringWriter(CultureInfo.InvariantCulture)
Dim exitCode = cmd.Run(writer, Nothing)
Assert.Equal(String.Empty, writer.ToString().Trim())
Assert.Equal(0, exitCode)
Dim expectedDoc = <![CDATA[
<?xml version="1.0"?>
<doc>
<assembly>
<name>
{0}
</name>
</assembly>
<members>
<member name="T:C">
<summary>
A subtype of <see cref="T:System.Object" />.
</summary>
</member>
</members>
</doc>]]>.Value.Trim()
expectedDoc = String.Format(expectedDoc,
Path.GetFileNameWithoutExtension(sourcePath))
expectedDoc = expectedDoc.Replace(vbLf, vbCrLf)
Assert.Equal(expectedDoc, xml.ReadAllText().Trim())
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase)
CleanupAllGeneratedFiles(sourcePath)
CleanupAllGeneratedFiles(xml.Path)
End Sub
''' <summary>
''' Builds the expected base of touched files.
''' Adds a hook for temporary file creation as well,
''' so this method must be called before the execution of
''' Vbc.Run.
''' </summary>
''' <param name="cmd"></param>
Private Shared Sub BuildTouchedFiles(cmd As VisualBasicCompiler,
outputPath As String,
<Out> ByRef expectedReads As List(Of String),
<Out> ByRef expectedWrites As List(Of String))
expectedReads = cmd.Arguments.MetadataReferences.Select(Function(r) r.Reference).ToList()
Dim coreLibrary = cmd.Arguments.DefaultCoreLibraryReference
If coreLibrary.HasValue Then
expectedReads.Add(coreLibrary.GetValueOrDefault().Reference)
End If
For Each file In cmd.Arguments.SourceFiles
expectedReads.Add(file.Path)
Next
Dim writes = New List(Of String)
writes.Add(outputPath)
expectedWrites = writes
End Sub
Private Shared Sub AssertTouchedFilesEqual(expectedReads As List(Of String),
expectedWrites As List(Of String),
touchedFilesBase As String)
Dim touchedReadPath = touchedFilesBase + ".read"
Dim touchedWritesPath = touchedFilesBase + ".write"
Dim expected = expectedReads.Select(Function(s) s.ToUpperInvariant()).OrderBy(Function(s) s)
Assert.Equal(String.Join(vbCrLf, expected),
File.ReadAllText(touchedReadPath).Trim())
expected = expectedWrites.Select(Function(s) s.ToUpperInvariant()).OrderBy(Function(s) s)
Assert.Equal(String.Join(vbCrLf, expected),
File.ReadAllText(touchedWritesPath).Trim())
End Sub
Private Class TestAnalyzerAssemblyLoader
Implements IAnalyzerAssemblyLoader
Public Sub AddDependencyLocation(fullPath As String) Implements IAnalyzerAssemblyLoader.AddDependencyLocation
Throw New NotImplementedException()
End Sub
Public Function LoadFromPath(fullPath As String) As Assembly Implements IAnalyzerAssemblyLoader.LoadFromPath
Throw New NotImplementedException()
End Function
End Class
End Class
End Namespace
| ' 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.
Imports System.Globalization
Imports System.IO
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities.SharedResourceHelpers
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests
Public Class TouchedFileLoggingTests
Inherits BasicTestBase
Private Shared ReadOnly s_libDirectory As String = Environment.GetEnvironmentVariable("LIB")
Private ReadOnly _baseDirectory As String = TempRoot.Root
Private ReadOnly _helloWorldCS As String = <text>
Imports System
Class C
Shared Sub Main(args As String())
Console.WriteLine("Hello, world")
End Sub
End Class
</text>.Value
<Fact>
Public Sub TrivialSourceFileOnlyVbc()
Dim hello = Temp.CreateFile().WriteAllText(_helloWorldCS).Path
Dim touchedDir = Temp.CreateDirectory()
Dim touchedBase = Path.Combine(touchedDir.Path, "touched")
Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory,
{"/nologo",
"/touchedfiles:" + touchedBase,
hello})
Dim outWriter = New StringWriter(CultureInfo.InvariantCulture)
Dim expectedReads As List(Of String) = Nothing
Dim expectedWrites As List(Of String) = Nothing
BuildTouchedFiles(cmd,
Path.ChangeExtension(hello, "exe"),
expectedReads,
expectedWrites)
Dim exitCode = cmd.Run(outWriter, Nothing)
Assert.Equal("", outWriter.ToString().Trim())
Assert.Equal(0, exitCode)
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase)
CleanupAllGeneratedFiles(hello)
End Sub
<Fact>
Public Sub StrongNameKeyVbc()
Dim hello = Temp.CreateFile().WriteAllText(_helloWorldCS).Path
Dim snkPath = Temp.CreateFile("TestKeyPair_", ".snk").WriteAllBytes(TestResources.General.snKey).Path
Dim touchedDir = Temp.CreateDirectory()
Dim touchedBase = Path.Combine(touchedDir.Path, "touched")
Dim outWriter = New StringWriter(CultureInfo.InvariantCulture)
Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory,
{"/nologo",
"/touchedfiles:" + touchedBase,
"/keyfile:" + snkPath,
hello})
Dim expectedReads As List(Of String) = Nothing
Dim expectedWrites As List(Of String) = Nothing
BuildTouchedFiles(cmd,
Path.ChangeExtension(hello, "exe"),
expectedReads,
expectedWrites)
expectedReads.Add(snkPath)
Dim exitCode = cmd.Run(outWriter, Nothing)
Assert.Equal(String.Empty, outWriter.ToString().Trim())
Assert.Equal(0, exitCode)
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase)
CleanupAllGeneratedFiles(hello)
CleanupAllGeneratedFiles(snkPath)
End Sub
<Fact>
Public Sub XmlDocumentFileVbc()
Dim sourcePath = Temp.CreateFile().WriteAllText(
<text><![CDATA[
''' <summary>
''' A subtype of <see cref="object" />.
''' </summary>
Public Class C
End Class
]]></text>.Value).Path
Dim xml = Temp.CreateFile()
Dim touchedDir = Temp.CreateDirectory()
Dim touchedBase = Path.Combine(touchedDir.Path, "touched")
Dim cmd = New MockVisualBasicCompiler(Nothing, _baseDirectory,
{"/nologo",
"/target:library",
"/doc:" + xml.Path,
"/touchedfiles:" + touchedBase,
sourcePath})
' Build touched files
Dim expectedReads As List(Of String) = Nothing
Dim expectedWrites As List(Of String) = Nothing
BuildTouchedFiles(cmd,
Path.ChangeExtension(sourcePath, "dll"),
expectedReads,
expectedWrites)
expectedWrites.Add(xml.Path)
Dim writer = New StringWriter(CultureInfo.InvariantCulture)
Dim exitCode = cmd.Run(writer, Nothing)
Assert.Equal(String.Empty, writer.ToString().Trim())
Assert.Equal(0, exitCode)
Dim expectedDoc = <![CDATA[
<?xml version="1.0"?>
<doc>
<assembly>
<name>
{0}
</name>
</assembly>
<members>
<member name="T:C">
<summary>
A subtype of <see cref="T:System.Object" />.
</summary>
</member>
</members>
</doc>]]>.Value.Trim()
expectedDoc = String.Format(expectedDoc,
Path.GetFileNameWithoutExtension(sourcePath))
expectedDoc = expectedDoc.Replace(vbLf, vbCrLf)
Assert.Equal(expectedDoc, xml.ReadAllText().Trim())
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase)
CleanupAllGeneratedFiles(sourcePath)
CleanupAllGeneratedFiles(xml.Path)
End Sub
''' <summary>
''' Builds the expected base of touched files.
''' Adds a hook for temporary file creation as well,
''' so this method must be called before the execution of
''' Vbc.Run.
''' </summary>
''' <param name="cmd"></param>
Private Shared Sub BuildTouchedFiles(cmd As VisualBasicCompiler,
outputPath As String,
<Out> ByRef expectedReads As List(Of String),
<Out> ByRef expectedWrites As List(Of String))
expectedReads = cmd.Arguments.MetadataReferences.Select(Function(r) r.Reference).ToList()
Dim coreLibrary = cmd.Arguments.DefaultCoreLibraryReference
If coreLibrary.HasValue Then
expectedReads.Add(coreLibrary.GetValueOrDefault().Reference)
End If
For Each file In cmd.Arguments.SourceFiles
expectedReads.Add(file.Path)
Next
Dim writes = New List(Of String)
writes.Add(outputPath)
expectedWrites = writes
End Sub
Private Shared Sub AssertTouchedFilesEqual(expectedReads As List(Of String),
expectedWrites As List(Of String),
touchedFilesBase As String)
Dim touchedReadPath = touchedFilesBase + ".read"
Dim touchedWritesPath = touchedFilesBase + ".write"
Dim expected = expectedReads.Select(Function(s) s.ToUpperInvariant()).OrderBy(Function(s) s)
Assert.Equal(String.Join(vbCrLf, expected),
File.ReadAllText(touchedReadPath).Trim())
expected = expectedWrites.Select(Function(s) s.ToUpperInvariant()).OrderBy(Function(s) s)
Assert.Equal(String.Join(vbCrLf, expected),
File.ReadAllText(touchedWritesPath).Trim())
End Sub
Private Class TestAnalyzerAssemblyLoader
Implements IAnalyzerAssemblyLoader
Public Sub AddDependencyLocation(fullPath As String) Implements IAnalyzerAssemblyLoader.AddDependencyLocation
Throw New NotImplementedException()
End Sub
Public Function LoadFromPath(fullPath As String) As Assembly Implements IAnalyzerAssemblyLoader.LoadFromPath
Throw New NotImplementedException()
End Function
End Class
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigFileGenerator.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.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.Options
{
internal static partial class EditorConfigFileGenerator
{
public static string Generate(
ImmutableArray<(string feature, ImmutableArray<IOption> options)> groupedOptions,
OptionSet optionSet,
string language)
{
var editorconfig = new StringBuilder();
editorconfig.AppendLine($"# {WorkspacesResources.Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories}");
editorconfig.AppendLine("root = true");
editorconfig.AppendLine();
if (language == LanguageNames.CSharp)
{
editorconfig.AppendLine($"# {WorkspacesResources.CSharp_files}");
editorconfig.AppendLine("[*.cs]");
}
else if (language == LanguageNames.VisualBasic)
{
editorconfig.AppendLine($"# {WorkspacesResources.Visual_Basic_files}");
editorconfig.AppendLine("[*.vb]");
}
editorconfig.AppendLine();
foreach ((var feature, var options) in groupedOptions)
{
AppendOptionsToEditorConfig(optionSet, feature, options, language, editorconfig);
}
var namingStylePreferences = optionSet.GetOption(NamingStyleOptions.NamingPreferences, language);
AppendNamingStylePreferencesToEditorConfig(namingStylePreferences, language, editorconfig);
return editorconfig.ToString();
}
private static void AppendOptionsToEditorConfig(OptionSet optionSet, string feature, ImmutableArray<IOption> options, string language, StringBuilder editorconfig)
{
editorconfig.AppendLine($"#### {feature} ####");
editorconfig.AppendLine();
foreach (var optionGrouping in options
.Where(o => o.StorageLocations.Any(l => l is IEditorConfigStorageLocation2))
.GroupBy(o => (o as IOptionWithGroup)?.Group ?? OptionGroup.Default)
.OrderBy(g => g.Key.Priority))
{
editorconfig.AppendLine($"# {optionGrouping.Key.Description}");
var optionsAndEditorConfigLocations = optionGrouping.Select(o => (o, o.StorageLocations.OfType<IEditorConfigStorageLocation2>().First()));
var uniqueEntries = new SortedSet<string>();
foreach ((var option, var editorConfigLocation) in optionsAndEditorConfigLocations)
{
var editorConfigString = GetEditorConfigString(option, editorConfigLocation);
uniqueEntries.Add(editorConfigString);
}
foreach (var entry in uniqueEntries)
{
editorconfig.AppendLine(entry);
}
editorconfig.AppendLine();
}
string GetEditorConfigString(IOption option, IEditorConfigStorageLocation2 editorConfigLocation)
{
var optionKey = new OptionKey(option, option.IsPerLanguage ? language : null);
var value = optionSet.GetOption(optionKey);
var editorConfigString = editorConfigLocation.GetEditorConfigString(value, optionSet);
Debug.Assert(!string.IsNullOrEmpty(editorConfigString));
return editorConfigString;
}
}
}
}
| // 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.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.Options
{
internal static partial class EditorConfigFileGenerator
{
public static string Generate(
ImmutableArray<(string feature, ImmutableArray<IOption> options)> groupedOptions,
OptionSet optionSet,
string language)
{
var editorconfig = new StringBuilder();
editorconfig.AppendLine($"# {WorkspacesResources.Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories}");
editorconfig.AppendLine("root = true");
editorconfig.AppendLine();
if (language == LanguageNames.CSharp)
{
editorconfig.AppendLine($"# {WorkspacesResources.CSharp_files}");
editorconfig.AppendLine("[*.cs]");
}
else if (language == LanguageNames.VisualBasic)
{
editorconfig.AppendLine($"# {WorkspacesResources.Visual_Basic_files}");
editorconfig.AppendLine("[*.vb]");
}
editorconfig.AppendLine();
foreach ((var feature, var options) in groupedOptions)
{
AppendOptionsToEditorConfig(optionSet, feature, options, language, editorconfig);
}
var namingStylePreferences = optionSet.GetOption(NamingStyleOptions.NamingPreferences, language);
AppendNamingStylePreferencesToEditorConfig(namingStylePreferences, language, editorconfig);
return editorconfig.ToString();
}
private static void AppendOptionsToEditorConfig(OptionSet optionSet, string feature, ImmutableArray<IOption> options, string language, StringBuilder editorconfig)
{
editorconfig.AppendLine($"#### {feature} ####");
editorconfig.AppendLine();
foreach (var optionGrouping in options
.Where(o => o.StorageLocations.Any(l => l is IEditorConfigStorageLocation2))
.GroupBy(o => (o as IOptionWithGroup)?.Group ?? OptionGroup.Default)
.OrderBy(g => g.Key.Priority))
{
editorconfig.AppendLine($"# {optionGrouping.Key.Description}");
var optionsAndEditorConfigLocations = optionGrouping.Select(o => (o, o.StorageLocations.OfType<IEditorConfigStorageLocation2>().First()));
var uniqueEntries = new SortedSet<string>();
foreach ((var option, var editorConfigLocation) in optionsAndEditorConfigLocations)
{
var editorConfigString = GetEditorConfigString(option, editorConfigLocation);
uniqueEntries.Add(editorConfigString);
}
foreach (var entry in uniqueEntries)
{
editorconfig.AppendLine(entry);
}
editorconfig.AppendLine();
}
string GetEditorConfigString(IOption option, IEditorConfigStorageLocation2 editorConfigLocation)
{
var optionKey = new OptionKey(option, option.IsPerLanguage ? language : null);
var value = optionSet.GetOption(optionKey);
var editorConfigString = editorConfigLocation.GetEditorConfigString(value, optionSet);
Debug.Assert(!string.IsNullOrEmpty(editorConfigString));
return editorConfigString;
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/ExtractMethod/ExtractMethodOptionsProvider.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.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
[ExportOptionProvider, Shared]
internal class ExtractMethodOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ExtractMethodOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
ExtractMethodOptions.AllowBestEffort,
ExtractMethodOptions.DontPutOutOrRefOnStruct);
}
}
| // 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.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
[ExportOptionProvider, Shared]
internal class ExtractMethodOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ExtractMethodOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
ExtractMethodOptions.AllowBestEffort,
ExtractMethodOptions.DontPutOutOrRefOnStruct);
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | 2021-08-27T16:47:40Z | 2021-08-27T19:59:35Z | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./eng/common/templates/job/execute-sdl.yml | parameters:
enable: 'false' # Whether the SDL validation job should execute or not
overrideParameters: '' # Optional: to override values for parameters.
additionalParameters: '' # Optional: parameters that need user specific values eg: '-SourceToolsList @("abc","def") -ArtifactToolsList @("ghi","jkl")'
# Optional: if specified, restore and use this version of Guardian instead of the default.
overrideGuardianVersion: ''
# Optional: if true, publish the '.gdn' folder as a pipeline artifact. This can help with in-depth
# diagnosis of problems with specific tool configurations.
publishGuardianDirectoryToPipeline: false
# The script to run to execute all SDL tools. Use this if you want to use a script to define SDL
# parameters rather than relying on YAML. It may be better to use a local script, because you can
# reproduce results locally without piecing together a command based on the YAML.
executeAllSdlToolsScript: 'eng/common/sdl/execute-all-sdl-tools.ps1'
# There is some sort of bug (has been reported) in Azure DevOps where if this parameter is named
# 'continueOnError', the parameter value is not correctly picked up.
# This can also be remedied by the caller (post-build.yml) if it does not use a nested parameter
sdlContinueOnError: false # optional: determines whether to continue the build if the step errors;
# optional: determines if build artifacts should be downloaded.
downloadArtifacts: true
# optional: determines if this job should search the directory of downloaded artifacts for
# 'tar.gz' and 'zip' archive files and extract them before running SDL validation tasks.
extractArchiveArtifacts: false
dependsOn: '' # Optional: dependencies of the job
artifactNames: '' # Optional: patterns supplied to DownloadBuildArtifacts
# Usage:
# artifactNames:
# - 'BlobArtifacts'
# - 'Artifacts_Windows_NT_Release'
# Optional: download a list of pipeline artifacts. 'downloadArtifacts' controls build artifacts,
# not pipeline artifacts, so doesn't affect the use of this parameter.
pipelineArtifactNames: []
# Optional: location and ID of the AzDO build that the build/pipeline artifacts should be
# downloaded from. By default, uses runtime expressions to decide based on the variables set by
# the 'setupMaestroVars' dependency. Overriding this parameter is necessary if SDL tasks are
# running without Maestro++/BAR involved, or to download artifacts from a specific existing build
# to iterate quickly on SDL changes.
AzDOProjectName: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ]
AzDOPipelineId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ]
AzDOBuildId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ]
jobs:
- job: Run_SDL
dependsOn: ${{ parameters.dependsOn }}
displayName: Run SDL tool
condition: eq( ${{ parameters.enable }}, 'true')
variables:
- group: DotNet-VSTS-Bot
- name: AzDOProjectName
value: ${{ parameters.AzDOProjectName }}
- name: AzDOPipelineId
value: ${{ parameters.AzDOPipelineId }}
- name: AzDOBuildId
value: ${{ parameters.AzDOBuildId }}
# The Guardian version specified in 'eng/common/sdl/packages.config'. This value must be kept in
# sync with the packages.config file.
- name: DefaultGuardianVersion
value: 0.53.3
- name: GuardianVersion
value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }}
- name: GuardianPackagesConfigFile
value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config
pool:
# To extract archives (.tar.gz, .zip), we need access to "tar", added in Windows 10/2019.
${{ if eq(parameters.extractArchiveArtifacts, 'false') }}:
name: Hosted VS2017
${{ if ne(parameters.extractArchiveArtifacts, 'false') }}:
vmImage: windows-2019
steps:
- checkout: self
clean: true
- ${{ if ne(parameters.downloadArtifacts, 'false')}}:
- ${{ if ne(parameters.artifactNames, '') }}:
- ${{ each artifactName in parameters.artifactNames }}:
- task: DownloadBuildArtifacts@0
displayName: Download Build Artifacts
inputs:
buildType: specific
buildVersionToDownload: specific
project: $(AzDOProjectName)
pipeline: $(AzDOPipelineId)
buildId: $(AzDOBuildId)
artifactName: ${{ artifactName }}
downloadPath: $(Build.ArtifactStagingDirectory)\artifacts
checkDownloadedFiles: true
- ${{ if eq(parameters.artifactNames, '') }}:
- task: DownloadBuildArtifacts@0
displayName: Download Build Artifacts
inputs:
buildType: specific
buildVersionToDownload: specific
project: $(AzDOProjectName)
pipeline: $(AzDOPipelineId)
buildId: $(AzDOBuildId)
downloadType: specific files
itemPattern: "**"
downloadPath: $(Build.ArtifactStagingDirectory)\artifacts
checkDownloadedFiles: true
- ${{ each artifactName in parameters.pipelineArtifactNames }}:
- task: DownloadPipelineArtifact@2
displayName: Download Pipeline Artifacts
inputs:
buildType: specific
buildVersionToDownload: specific
project: $(AzDOProjectName)
pipeline: $(AzDOPipelineId)
buildId: $(AzDOBuildId)
artifactName: ${{ artifactName }}
downloadPath: $(Build.ArtifactStagingDirectory)\artifacts
checkDownloadedFiles: true
- powershell: eng/common/sdl/extract-artifact-packages.ps1
-InputPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts
-ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts
displayName: Extract Blob Artifacts
continueOnError: ${{ parameters.sdlContinueOnError }}
- powershell: eng/common/sdl/extract-artifact-packages.ps1
-InputPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts
-ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts
displayName: Extract Package Artifacts
continueOnError: ${{ parameters.sdlContinueOnError }}
- ${{ if ne(parameters.extractArchiveArtifacts, 'false') }}:
- powershell: eng/common/sdl/extract-artifact-archives.ps1
-InputPath $(Build.ArtifactStagingDirectory)\artifacts
-ExtractPath $(Build.ArtifactStagingDirectory)\artifacts
displayName: Extract Archive Artifacts
continueOnError: ${{ parameters.sdlContinueOnError }}
- ${{ if ne(parameters.overrideGuardianVersion, '') }}:
- powershell: |
$content = Get-Content $(GuardianPackagesConfigFile)
Write-Host "packages.config content was:`n$content"
$content = $content.Replace('$(DefaultGuardianVersion)', '$(GuardianVersion)')
$content | Set-Content $(GuardianPackagesConfigFile)
Write-Host "packages.config content updated to:`n$content"
displayName: Use overridden Guardian version ${{ parameters.overrideGuardianVersion }}
- task: NuGetToolInstaller@1
displayName: 'Install NuGet.exe'
- task: NuGetCommand@2
displayName: 'Install Guardian'
inputs:
restoreSolution: $(Build.SourcesDirectory)\eng\common\sdl\packages.config
feedsToUse: config
nugetConfigPath: $(Build.SourcesDirectory)\eng\common\sdl\NuGet.config
externalFeedCredentials: GuardianConnect
restoreDirectory: $(Build.SourcesDirectory)\.packages
- ${{ if ne(parameters.overrideParameters, '') }}:
- powershell: ${{ parameters.executeAllSdlToolsScript }} ${{ parameters.overrideParameters }}
displayName: Execute SDL
continueOnError: ${{ parameters.sdlContinueOnError }}
- ${{ if eq(parameters.overrideParameters, '') }}:
- powershell: ${{ parameters.executeAllSdlToolsScript }}
-GuardianPackageName Microsoft.Guardian.Cli.$(GuardianVersion)
-NugetPackageDirectory $(Build.SourcesDirectory)\.packages
-AzureDevOpsAccessToken $(dn-bot-dotnet-build-rw-code-rw)
${{ parameters.additionalParameters }}
displayName: Execute SDL
continueOnError: ${{ parameters.sdlContinueOnError }}
- ${{ if ne(parameters.publishGuardianDirectoryToPipeline, 'false') }}:
# We want to publish the Guardian results and configuration for easy diagnosis. However, the
# '.gdn' dir is a mix of configuration, results, extracted dependencies, and Guardian default
# tooling files. Some of these files are large and aren't useful during an investigation, so
# exclude them by simply deleting them before publishing. (As of writing, there is no documented
# way to selectively exclude a dir from the pipeline artifact publish task.)
- task: DeleteFiles@1
displayName: Delete Guardian dependencies to avoid uploading
inputs:
SourceFolder: $(Agent.BuildDirectory)/.gdn
Contents: |
c
i
condition: succeededOrFailed()
- publish: $(Agent.BuildDirectory)/.gdn
artifact: GuardianConfiguration
displayName: Publish GuardianConfiguration
condition: succeededOrFailed()
| parameters:
enable: 'false' # Whether the SDL validation job should execute or not
overrideParameters: '' # Optional: to override values for parameters.
additionalParameters: '' # Optional: parameters that need user specific values eg: '-SourceToolsList @("abc","def") -ArtifactToolsList @("ghi","jkl")'
# Optional: if specified, restore and use this version of Guardian instead of the default.
overrideGuardianVersion: ''
# Optional: if true, publish the '.gdn' folder as a pipeline artifact. This can help with in-depth
# diagnosis of problems with specific tool configurations.
publishGuardianDirectoryToPipeline: false
# The script to run to execute all SDL tools. Use this if you want to use a script to define SDL
# parameters rather than relying on YAML. It may be better to use a local script, because you can
# reproduce results locally without piecing together a command based on the YAML.
executeAllSdlToolsScript: 'eng/common/sdl/execute-all-sdl-tools.ps1'
# There is some sort of bug (has been reported) in Azure DevOps where if this parameter is named
# 'continueOnError', the parameter value is not correctly picked up.
# This can also be remedied by the caller (post-build.yml) if it does not use a nested parameter
sdlContinueOnError: false # optional: determines whether to continue the build if the step errors;
# optional: determines if build artifacts should be downloaded.
downloadArtifacts: true
# optional: determines if this job should search the directory of downloaded artifacts for
# 'tar.gz' and 'zip' archive files and extract them before running SDL validation tasks.
extractArchiveArtifacts: false
dependsOn: '' # Optional: dependencies of the job
artifactNames: '' # Optional: patterns supplied to DownloadBuildArtifacts
# Usage:
# artifactNames:
# - 'BlobArtifacts'
# - 'Artifacts_Windows_NT_Release'
# Optional: download a list of pipeline artifacts. 'downloadArtifacts' controls build artifacts,
# not pipeline artifacts, so doesn't affect the use of this parameter.
pipelineArtifactNames: []
# Optional: location and ID of the AzDO build that the build/pipeline artifacts should be
# downloaded from. By default, uses runtime expressions to decide based on the variables set by
# the 'setupMaestroVars' dependency. Overriding this parameter is necessary if SDL tasks are
# running without Maestro++/BAR involved, or to download artifacts from a specific existing build
# to iterate quickly on SDL changes.
AzDOProjectName: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ]
AzDOPipelineId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ]
AzDOBuildId: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ]
jobs:
- job: Run_SDL
dependsOn: ${{ parameters.dependsOn }}
displayName: Run SDL tool
condition: eq( ${{ parameters.enable }}, 'true')
variables:
- group: DotNet-VSTS-Bot
- name: AzDOProjectName
value: ${{ parameters.AzDOProjectName }}
- name: AzDOPipelineId
value: ${{ parameters.AzDOPipelineId }}
- name: AzDOBuildId
value: ${{ parameters.AzDOBuildId }}
# The Guardian version specified in 'eng/common/sdl/packages.config'. This value must be kept in
# sync with the packages.config file.
- name: DefaultGuardianVersion
value: 0.53.3
- name: GuardianVersion
value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }}
- name: GuardianPackagesConfigFile
value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config
pool:
# To extract archives (.tar.gz, .zip), we need access to "tar", added in Windows 10/2019.
${{ if eq(parameters.extractArchiveArtifacts, 'false') }}:
name: Hosted VS2017
${{ if ne(parameters.extractArchiveArtifacts, 'false') }}:
vmImage: windows-2019
steps:
- checkout: self
clean: true
- ${{ if ne(parameters.downloadArtifacts, 'false')}}:
- ${{ if ne(parameters.artifactNames, '') }}:
- ${{ each artifactName in parameters.artifactNames }}:
- task: DownloadBuildArtifacts@0
displayName: Download Build Artifacts
inputs:
buildType: specific
buildVersionToDownload: specific
project: $(AzDOProjectName)
pipeline: $(AzDOPipelineId)
buildId: $(AzDOBuildId)
artifactName: ${{ artifactName }}
downloadPath: $(Build.ArtifactStagingDirectory)\artifacts
checkDownloadedFiles: true
- ${{ if eq(parameters.artifactNames, '') }}:
- task: DownloadBuildArtifacts@0
displayName: Download Build Artifacts
inputs:
buildType: specific
buildVersionToDownload: specific
project: $(AzDOProjectName)
pipeline: $(AzDOPipelineId)
buildId: $(AzDOBuildId)
downloadType: specific files
itemPattern: "**"
downloadPath: $(Build.ArtifactStagingDirectory)\artifacts
checkDownloadedFiles: true
- ${{ each artifactName in parameters.pipelineArtifactNames }}:
- task: DownloadPipelineArtifact@2
displayName: Download Pipeline Artifacts
inputs:
buildType: specific
buildVersionToDownload: specific
project: $(AzDOProjectName)
pipeline: $(AzDOPipelineId)
buildId: $(AzDOBuildId)
artifactName: ${{ artifactName }}
downloadPath: $(Build.ArtifactStagingDirectory)\artifacts
checkDownloadedFiles: true
- powershell: eng/common/sdl/extract-artifact-packages.ps1
-InputPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts
-ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts
displayName: Extract Blob Artifacts
continueOnError: ${{ parameters.sdlContinueOnError }}
- powershell: eng/common/sdl/extract-artifact-packages.ps1
-InputPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts
-ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts
displayName: Extract Package Artifacts
continueOnError: ${{ parameters.sdlContinueOnError }}
- ${{ if ne(parameters.extractArchiveArtifacts, 'false') }}:
- powershell: eng/common/sdl/extract-artifact-archives.ps1
-InputPath $(Build.ArtifactStagingDirectory)\artifacts
-ExtractPath $(Build.ArtifactStagingDirectory)\artifacts
displayName: Extract Archive Artifacts
continueOnError: ${{ parameters.sdlContinueOnError }}
- ${{ if ne(parameters.overrideGuardianVersion, '') }}:
- powershell: |
$content = Get-Content $(GuardianPackagesConfigFile)
Write-Host "packages.config content was:`n$content"
$content = $content.Replace('$(DefaultGuardianVersion)', '$(GuardianVersion)')
$content | Set-Content $(GuardianPackagesConfigFile)
Write-Host "packages.config content updated to:`n$content"
displayName: Use overridden Guardian version ${{ parameters.overrideGuardianVersion }}
- task: NuGetToolInstaller@1
displayName: 'Install NuGet.exe'
- task: NuGetCommand@2
displayName: 'Install Guardian'
inputs:
restoreSolution: $(Build.SourcesDirectory)\eng\common\sdl\packages.config
feedsToUse: config
nugetConfigPath: $(Build.SourcesDirectory)\eng\common\sdl\NuGet.config
externalFeedCredentials: GuardianConnect
restoreDirectory: $(Build.SourcesDirectory)\.packages
- ${{ if ne(parameters.overrideParameters, '') }}:
- powershell: ${{ parameters.executeAllSdlToolsScript }} ${{ parameters.overrideParameters }}
displayName: Execute SDL
continueOnError: ${{ parameters.sdlContinueOnError }}
- ${{ if eq(parameters.overrideParameters, '') }}:
- powershell: ${{ parameters.executeAllSdlToolsScript }}
-GuardianPackageName Microsoft.Guardian.Cli.$(GuardianVersion)
-NugetPackageDirectory $(Build.SourcesDirectory)\.packages
-AzureDevOpsAccessToken $(dn-bot-dotnet-build-rw-code-rw)
${{ parameters.additionalParameters }}
displayName: Execute SDL
continueOnError: ${{ parameters.sdlContinueOnError }}
- ${{ if ne(parameters.publishGuardianDirectoryToPipeline, 'false') }}:
# We want to publish the Guardian results and configuration for easy diagnosis. However, the
# '.gdn' dir is a mix of configuration, results, extracted dependencies, and Guardian default
# tooling files. Some of these files are large and aren't useful during an investigation, so
# exclude them by simply deleting them before publishing. (As of writing, there is no documented
# way to selectively exclude a dir from the pipeline artifact publish task.)
- task: DeleteFiles@1
displayName: Delete Guardian dependencies to avoid uploading
inputs:
SourceFolder: $(Agent.BuildDirectory)/.gdn
Contents: |
c
i
condition: succeededOrFailed()
- publish: $(Agent.BuildDirectory)/.gdn
artifact: GuardianConfiguration
displayName: Publish GuardianConfiguration
condition: succeededOrFailed()
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/local-functions.test.md | # Interaction with other language features:
General concerns:
- [ ] Error handling/recovery
- [ ] Errors in parsing
- [ ] Error handling for semantic errors (e.g. ambiguous lookup, inaccessible lookup, wrong kind of thing found, instance vs static thing found, wrong type for the context, value vs variable)
- [ ] Public interface of compiler APIs, backcompat scenarios
- [ ] Determinism
- [ ] Atomicity
- [ ] Edit-and-continue
- [ ] Completeness of the specification as a guide for testing (e.g. is the spec complete enough to suggest what the compiler should do in each scenario?)
- [ ] Other external documentation
- [ ] Performance
Types and members:
- [ ] Access modifiers (public, protected, internal, protected internal, private), static modifier
- [ ] Parameter modifiers (ref, out, params)
- [ ] Attributes (including security attribute)
- [ ] Generics (type arguments, constraints, variance)
- [ ] default value
- [ ] partial classes
- [ ] literals
- [ ] enum (implicit vs. explicit underlying type)
- [ ] expression trees
- [ ] Iterators
- [ ] Initializers (object, collection, dictionary)
- [ ] array (single- or multi-dimensional, jagged, initilalizer)
- [ ] Expression-bodied methods/properties/...
- [ ] Extension methods
- [ ] Partial method
- [ ] Named and optional parameters
- [ ] String interpolation
- [ ] Properties (read-write, read-only, write-only, auto-property, expression-bodied)
- [ ] Interfaces (implicit vs. explicit interface member implementation)
- [ ] delegates
- [ ] Multi-declaration
Code:
- [ ] Operators (see Eric's list)
- [ ] Operator overloading
- [ ] Lvalues: the synthesized fields are mutable
- [ ] Ref / out parameters
- [ ] Compound operators (+=, /=, etc ..)
- [ ] Assignment exprs
- [ ] lambdas (capture of parameters or locals, target typing)
- [ ] execution order
- [ ] Target typing (var, lambdas, integrals)
- [ ] Type inference
- [ ] Conversions
- [ ] Implicit (identity, implicit numeric, implicit enumeration, implicit nullable, null litaral, implicit reference, boxing, implicit dynamic, implicit constant, user-defined implicit conversion, anonymous function, method group)
- [ ] Explicit (numeric, enumeration, nullable, reference, unboxing, dynamic, user-defined)
- [ ] Anonymous functions
- [ ] nullable (wrapping, unwrapping)
- [ ] OHI
- [ ] inheritance (virtual, override, abstract, new)
- [ ] overload resolution
- [ ] Anonymous types
- [ ] Unsafe code
- [ ] LINQ
- [ ] constructors, properties, indexers, events, operators, and destructors.
- [X] Async
- [X] Var
Misc:
- [ ] reserved keywords (sometimes contextual)
- [ ] pre-processing directives
- [ ] COM interop
| # Interaction with other language features:
General concerns:
- [ ] Error handling/recovery
- [ ] Errors in parsing
- [ ] Error handling for semantic errors (e.g. ambiguous lookup, inaccessible lookup, wrong kind of thing found, instance vs static thing found, wrong type for the context, value vs variable)
- [ ] Public interface of compiler APIs, backcompat scenarios
- [ ] Determinism
- [ ] Atomicity
- [ ] Edit-and-continue
- [ ] Completeness of the specification as a guide for testing (e.g. is the spec complete enough to suggest what the compiler should do in each scenario?)
- [ ] Other external documentation
- [ ] Performance
Types and members:
- [ ] Access modifiers (public, protected, internal, protected internal, private), static modifier
- [ ] Parameter modifiers (ref, out, params)
- [ ] Attributes (including security attribute)
- [ ] Generics (type arguments, constraints, variance)
- [ ] default value
- [ ] partial classes
- [ ] literals
- [ ] enum (implicit vs. explicit underlying type)
- [ ] expression trees
- [ ] Iterators
- [ ] Initializers (object, collection, dictionary)
- [ ] array (single- or multi-dimensional, jagged, initilalizer)
- [ ] Expression-bodied methods/properties/...
- [ ] Extension methods
- [ ] Partial method
- [ ] Named and optional parameters
- [ ] String interpolation
- [ ] Properties (read-write, read-only, write-only, auto-property, expression-bodied)
- [ ] Interfaces (implicit vs. explicit interface member implementation)
- [ ] delegates
- [ ] Multi-declaration
Code:
- [ ] Operators (see Eric's list)
- [ ] Operator overloading
- [ ] Lvalues: the synthesized fields are mutable
- [ ] Ref / out parameters
- [ ] Compound operators (+=, /=, etc ..)
- [ ] Assignment exprs
- [ ] lambdas (capture of parameters or locals, target typing)
- [ ] execution order
- [ ] Target typing (var, lambdas, integrals)
- [ ] Type inference
- [ ] Conversions
- [ ] Implicit (identity, implicit numeric, implicit enumeration, implicit nullable, null literal, implicit reference, boxing, implicit dynamic, implicit constant, user-defined implicit conversion, anonymous function, method group)
- [ ] Explicit (numeric, enumeration, nullable, reference, unboxing, dynamic, user-defined)
- [ ] Anonymous functions
- [ ] nullable (wrapping, unwrapping)
- [ ] OHI
- [ ] inheritance (virtual, override, abstract, new)
- [ ] overload resolution
- [ ] Anonymous types
- [ ] Unsafe code
- [ ] LINQ
- [ ] constructors, properties, indexers, events, operators, and destructors.
- [X] Async
- [X] Var
Misc:
- [ ] reserved keywords (sometimes contextual)
- [ ] pre-processing directives
- [ ] COM interop
| 1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/local-functions.work.md | Local Function Status
=====================
This is a checklist for current and outstanding work on the local functions
feature, as spec'd in [local-functions.md](./local-functions.md).
--------------------
Known issues
============
Compiler:
- [ ] Parser builds nodes for local functions when feature not enabled (#9940)
- [ ] Compiler crash: base call to state machine method, in state machine
method (#9872)
- [ ] Need custom warning for unused local function (#9661)
- [ ] Generate quick action does not offer to generate local (#9352)
- [ ] Parser ambiguity research (#10388)
- [ ] Dynamic support (#10389)
- [ ] Referring to local function in expression tree (#10390)
- [ ] Resolve definite assignment rules (#10391)
- [ ] Remove support for `var` return type (#10392)
- [ ] Update error messages (#10393)
IDE:
- [ ] Some selections around local functions fail extract method refactoring
[ ] (#8719)
- [ ] Extracting local function passed to an Action introduces compiler error
[ ] (#8718)
- [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717)
- [ ] Inline temp introductes compiler error (#8716)
- [ ] Call hierarchy search never terminates on local functions (#8654)
- [ ] Nav bar doesn't support local functions (#8648)
- [ ] No outlining for local functions (#8647)
- [ ] Squiggles all over the place when using an unsupported modifier (#8645)
- [ ] Peek definition errors out on local function (#8644)
- [ ] Void keyword not recommended while declaring local function (#8616)
- [ ] Change signature doesn't update the signature of the local function (#8539)
Feature Completeness Progress
=============================
- [x] N-level nested local functions
- [x] Capture
- Works alongside lambdas and behaves very similarly in fallback cases
- Has zero-allocation closures (struct frames by ref) on functions never
converted to a delegate and are not an iterator/async
- [x] Standard parameter features
- params
- ref/out
- named/optional
- [x] Visibility
- May revisit design (currently shadows, may do overloads)
- [x] Generics
- Nongeneric local functions in generic methods (same as lambdas).
- Generic local functions in nongeneric methods.
- Generic local functions in generic methods.
- Arbitrary nesting of generic local functions.
- Generic local functions with constraints.
- [x] Inferred return type
- [x] Iterators
- [x] Async
| Local Function Status
=====================
This is a checklist for current and outstanding work on the local functions
feature, as spec'd in [local-functions.md](./local-functions.md).
--------------------
Known issues
============
Compiler:
- [ ] Parser builds nodes for local functions when feature not enabled (#9940)
- [ ] Compiler crash: base call to state machine method, in state machine
method (#9872)
- [ ] Need custom warning for unused local function (#9661)
- [ ] Generate quick action does not offer to generate local (#9352)
- [ ] Parser ambiguity research (#10388)
- [ ] Dynamic support (#10389)
- [ ] Referring to local function in expression tree (#10390)
- [ ] Resolve definite assignment rules (#10391)
- [ ] Remove support for `var` return type (#10392)
- [ ] Update error messages (#10393)
IDE:
- [ ] Some selections around local functions fail extract method refactoring
[ ] (#8719)
- [ ] Extracting local function passed to an Action introduces compiler error
[ ] (#8718)
- [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717)
- [ ] Inline temp introduces compiler error (#8716)
- [ ] Call hierarchy search never terminates on local functions (#8654)
- [ ] Nav bar doesn't support local functions (#8648)
- [ ] No outlining for local functions (#8647)
- [ ] Squiggles all over the place when using an unsupported modifier (#8645)
- [ ] Peek definition errors out on local function (#8644)
- [ ] Void keyword not recommended while declaring local function (#8616)
- [ ] Change signature doesn't update the signature of the local function (#8539)
Feature Completeness Progress
=============================
- [x] N-level nested local functions
- [x] Capture
- Works alongside lambdas and behaves very similarly in fallback cases
- Has zero-allocation closures (struct frames by ref) on functions never
converted to a delegate and are not an iterator/async
- [x] Standard parameter features
- params
- ref/out
- named/optional
- [x] Visibility
- May revisit design (currently shadows, may do overloads)
- [x] Generics
- Nongeneric local functions in generic methods (same as lambdas).
- Generic local functions in nongeneric methods.
- Generic local functions in generic methods.
- Arbitrary nesting of generic local functions.
- Generic local functions with constraints.
- [x] Inferred return type
- [x] Iterators
- [x] Async
| 1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/pdb-compilation-options.md | # Embedding Compilation options in Portable PDBs
Prior to this feature the compiler did not emit all information that's necessary to reconstruct the original compilation to the output binaries.
It is desirable to include such information in order to support scenarios such as validation that given binaries can be reproduced from their original sources, [post-build source analysis](https://github.com/dotnet/roslyn/issues/41395), etc.
The goal of this feature is to be able to construct a compilation that is exactly the same as an initial compilation as long as it meets the conditions outlined in the assumptions below.
This document is restricted to the following assumptions:
1. The full benefit is for builds with `-deterministic` and published to the symbol server. That said the compiler embeds compilation options and references to all Portable PDBs.
2. Source generator and analyzer references are not needed for this task. They may be useful, but are out of scope for this feature.
3. Any storage capacity used for PDBs and source should not impact this feature, such as compression algorithm.
4. Only Portable PDB files will be included for this spec. This feature can be expanded past these once it is implemented and proven needed elsewhere.
This document will provide the expanded specification to the Portable PDB format. Any additions to that format will be ported to expand documentation provided in [dotnet-runtime](https://github.com/dotnet/runtime/blob/main/docs/design/specs/PortablePdb-Metadata.md).
## PDB Format Additions
#### Compilation Metadata References custom debug information
Symbol server uses a [key](https://github.com/dotnet/symstore/blob/main/docs/specs/SSQP_Key_Conventions.md#pe-timestamp-filesize) computed from the COFF header in the PE image:
Timestamp: 4 byte integer
Size of image: 4 byte integer
Example:
File name: `example.exe`
COFF header Timestamp field: `0x542d5742`
COFF header SizeOfImage field: `0x32000`
Lookup key: `example.exe/542d574232000/example.exe`
To fully support metadata references, a user will need to be able to find the exact PE image that was used in the compilation. This will be done by storing the parts that make up the symbol server key. The MVID of a reference will be stored since it's a GUID that represents the symbol. This is to future proof the information for reference lookup.
At this time, only external references for the compilation will be included. Any other references may be added later in a separate blob.
Metadata references are stored as binary. The binary encoding will be as follows (order matters):
Name: A UTF-8 string (null terminated)
Aliases: UTF-8 Comma (, ) separated list of aliases (null terminated). May be empty
MetadataImageKind: byte value representing Microsoft. CodeAnalysis. MetadataImageKind
EmbedInteropTypes/MetadataImageKind: byte, reads as binary values starting in order from right to left
MetadataImageKind: 1 if Assembly, 0 if Module
EmbedInteropTypes: 1 if true
Examples:
0b11, MetadataImageKind.Assembly and EmbedInteropTypes = true
0b01, MetadataImageKind.Module and EmbedInteropTypes = true
Timestamp: 4 byte integer
File Size: 4 byte integer
MVID: 16 byte integer (GUID)
#### Retriving Metadata References
Metadata references are stored in the CustomDebugInformation in a PDB using the GUID `7E4D4708-096E-4C5C-AEDA-CB10BA6A740D` .
Example how to retrieve and read this information using `System.Reflection.Metadata` :
``` csharp
var metadataReferencesGuid = new Guid("7E4D4708-096E-4C5C-AEDA-CB10BA6A740D");
var path = "path/to/pdb";
using var stream = File.OpenRead(path);
using var metadataReaderProvider = MetadataReaderProvider.FromPortablePdbStream(stream);
var metadataReader = metadataReaderProvider.GetMetadataReader();
foreach (var handle in metadataReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition))
{
var customDebugInformation = metadataReader.GetCustomDebugInformation(handle);
if (metadataReader.GetGuid(customDebugInformation.Kind) == metadataReferencesGuid)
{
var blobReader = metadataReader.GetBlobReader(customDebugInformation.Value);
// Each loop is one reference
while (blobReader.RemainingBytes > 0)
{
// Order of information
// File name (null terminated string): A.exe
// Extern Alias (null terminated string): a1,a2,a3
// EmbedInteropTypes/MetadataImageKind (byte)
// COFF header Timestamp field (4 byte int)
// COFF header SizeOfImage field (4 byte int)
// MVID (Guid, 24 bytes)
var terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var name = blobReader.ReadUTF8(terminatorIndex);
// Skip the null terminator
blobReader.ReadByte();
terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var externAliases = blobReader.ReadUTF8(terminatorIndex);
// Skip the null terminator
blobReader.ReadByte();
var embedInteropTypesAndKind = blobReader.ReadByte();
var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10;
var kind = (embedInteropTypesAndKind & 0b1) == 0b1
? MetadataImageKind.Assembly
: MetadataImageKind.Module;
var timestamp = blobReader.ReadInt32();
var imageSize = blobReader.ReadInt32();
var mvid = blobReader.ReadGuid();
Console.WriteLine(name);
Console.WriteLine($"Extern Aliases: \"{externAliases}\"");
Console.WriteLine($"Embed Interop Types: {embedInteropTypes}");
Console.WriteLine($"Metadata Image Kind: {kind}");
Console.WriteLine($"Timestamp: {timestamp}");
Console.WriteLine($"Image Size: {imageSize}");
Console.WriteLine($"MVID: {mvid}");
Console.WriteLine();
}
}
}
```
### Compiler Options custom debug information
The remaining values will be stored as key value pairs in the pdb. The storage format will be UTF8 encoded key value pairs that are null terminated. Order is not guaranteed. Any values left out can be assumed to be the default for the type. Keys may be different for Visual Basic and CSharp. They are serialized to reflect the command line arguments representing the same values
Example:
`compilerversion\01.2.3-example-sha\0sourceencoding\0utf-8\0checked\01\0unsafe\01\0langversion\0latest\0nullable\0Enable`
## List of Compiler Flags
#### CSharp Flags That Can Be Derived From PDB or Assembly
* baseaddress
* checksumalgorithm
* debug
* deterministic
* embed
* filealign
* highentropyva
* link
- Represented by a metadata reference with `EmbededInteropTypes=true`
* linkresource
- Will be represented in metadata reference embedded in pdb
* main
- Already stored in PDB as the entry point token
* moduleassemblyname
* modulename
* nostdlib
- Will be represented in metadata reference embedded in pdb
* nowin32manifest
* pdb
* platform
* publicsign
* resource
- Will be represented in metadata reference embedded in pdb
* subsystemversion
* win32icon
* win32manifest
* win32res
#### CSharp Flags Not Included
* bugreport
* delaysign
* doc
* errorendlocation
* errorlog
* errorreport
* fullpaths
* incremental
* keycontainer
* keyfile
* noconfig
* nologo
* nowarn
* out
* parallel
* pathmap
* preferreduilang
* recurse
* refout
* refonly
* reportanalyzer
* ruleset
* utf8output
* version
* warn
* warnaserror
#### Visual Basic Flags That Can Be Derived From PDB or Assembly
* baseaddress
* checksumalgorithm
* debug
* filealign
* highentropyva
* linkresource
- Will be represented in metadata reference embedded in pdb
* main
* nostdlib
- Will be represented in metadata reference embedded in pdb
* platform
* resource
- Will be represented in metadata reference embedded in pdb
* subsystemversion
* win32icon
* win32manifest
* win32resource
#### Visual Basic Flags Not Included
* bugreport
* delaysign
* doc
* errorreport
* help
* keycontainer
* keyfile
* libpath
* moduleassemblyname
* modulename
* netcf
* noconfig
* nologo
* nowarn
* nowin32manifest
* optioncompare
* optionexplicit
* optioninfer
* out
* parallel
* preferreduilang
* quiet
* recurse
* refonly
* refout
* rootnamespace
* ruleset
* sdkpath
* utf8output
* vbruntime
* verbose
* warnaserror
#### Shared Options for CSharp and Visual Basic
| PDB Key | Format | Default | Description |
| ---------------------- | --------------------------------------- | --------- | ------------ |
| language | `CSharp\|Visual Basic` | required | Language name. |
| compiler-version | [SemVer2](https://semver.org/spec/v2.0.0.html) string | required | Full version with SHA |
| runtime-version | [SemVer2](https://semver.org/spec/v2.0.0.html) string | required | [runtime version](#runtime-version) |
| source-file-count | int32 | required | Count of files in the document table that are source files |
| optimization | `(debug\|debug-plus\|release\|release-debug-plus)` | `'debug'` | [optimization](#optimization) |
| portability-policy | `(0\|1\|2\|3)` | `0` | [portability policy](#portability-policy) |
| default-encoding | string | none | [file encoding](#file-encoding) |
| fallback-encoding | string | none | [file encoding](#file-encoding) |
| output-kind | string | require | The value passed to `/target` |
| platform | string | require | The value passed to `/platform` |
#### Options For CSharp
See [compiler options](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/listed-alphabetically) documentation
| PDB Key | Format | Default | Description |
| ---------------------- | --------------------------------------- | --------- | ------------ |
| language-version | `[0-9]+(\.[0-9]+)?` | required | [langversion](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/langversion-compiler-option) |
| define | `,`-separated identifier list | empty | [define](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/define-compiler-option) |
| checked | `(True\|False)` | `False` | [checked](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/checked-compiler-option) |
| nullable | `(Disable\|Warnings\|Annotations\|Enable)` | `Disable` | [nullable](https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references) |
| unsafe | `(True\|False)` | `False` | [unsafe](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/unsafe-compiler-option) |
#### Options For Visual Basic
See [compiler options](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/compiler-options-listed-alphabetically) documentation
| PDB Key | Format | Default | Description |
| ---------------------- | ------------------------------------------ | -------- | ----------- |
| language-version | `[0-9]+(\.[0-9]+)?` | required | [langversion](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/langversion) |
| define | `,`-separated list of name `=` value pairs | empty | [define](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/define) |
| checked | `(True\|False)` | `False` | Opposite of [removeintchecks](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/removeintchecks) |
| option-strict | `(Off\|Custom\|On)` | required | [option strict](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/optionstrict) |
| option-infer | `(True\|False)` | required | [option infer](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/optioninfer) |
| option-compare-text | `(True\|False)` | required | [option compare](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/optioncompare) |
| option-explicit | `(True\|False)` | required | [option explicit](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/optionexplicit) |
| embed-runtime | `(True\|False)` | required | Whether or not the VB runtime was embedded into the PE |
| global-namespaces | `,` -separated identifier list | empty | [imports](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/imports)
| root-namespace | string | empty | [root namespace](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/rootnamespace)
#### Portability Policy
Portability policy is derived from the [appconfig command option](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/appconfig-compiler-option).
Since appconfig is a pointer to a file not embedded in the PDB or PE, information that will directly impact the compilation is extracted. This is stored in a flag called `portability-policy` with a numeric value from \[0-3\]. This value directly correlates to reconstructing the [AssemblyPortabilityPolicy](https://github.com/dotnet/roslyn/blob/bdb3ece74c85892709f5e42ae7d67248999ecc3b/src/Compilers/Core/Portable/Desktop/AssemblyPortabilityPolicy.cs).
* 0 -> SuppressSilverlightPlatformAssembliesPortability = false, SuppressSilverlightLibraryAssembliesPortability = false
* 1 -> SuppressSilverlightPlatformAssembliesPortability = true, SuppressSilverlightLibraryAssembliesPortability = false
* 2 -> SuppressSilverlightPlatformAssembliesPortability = false, SuppressSilverlightLibraryAssembliesPortability = true
* 3 -> SuppressSilverlightPlatformAssembliesPortability = true, SuppressSilverlightLibraryAssembliesPortability = true
#### File Encoding
Encoding will be stored in two keys: "default-encoding" and "fallback-encoding".
If `default-encoding` is present, it represents the forced encoding used, such as by passing in "codepage" to the command line. All files without a Byte Order Mark (BOM) should be decoded using this encoding.
If `fallback-encoding` is present, it means that no default encoding was specified but an encoding was detected and used. The compiler [has logic](https://github.com/dotnet/roslyn/blob/462eac607741023e5c2d518ac1045f4c6dabd501/src/Compilers/Core/Portable/EncodedStringText.cs#L32) to determine an encoding is none is specified, so the value that was computed is stored so it can be reused in future compilations.
Both values are written as [WebName](https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.webname?view=netcore-3.1) values for an encoding.
#### Optimization
Optimization level can be specified from the command line with [optimize](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/optimize-compiler-option). It gets translated to the [OptimizationLevel](https://github.com/dotnet/roslyn/blob/e704ca635bd6de70a0250e34c4567c7a28fa9f6d/src/Compilers/Core/Portable/Compilation/OptimizationLevel.cs) that is emitted to the PDB.
There are three possible values:
* `debug` -> `OptimizationLevel.Debug` and DebugPlusMode is false
* `debug-plus` -> `OptimizationLevel.Debug` and DebugPlusMode is true
* `release` -> `OptimizationLevel.Release` and DebugPlusMode is false (ignored)
#### Runtime Version
The runtime version used that the compiler was running in when generating the PE. This is stored as [informational version](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assemblyinformationalversionattribute.informationalversion?view=netcore-3.1#System_Reflection_AssemblyInformationalVersionAttribute_InformationalVersion).
Runtime version is stored since it can impact the unicode character interpretation and decimla arithmetics, which both play a role in how code is compiled from source. There may also be future variations where the different versions of the runtime impact compilation.
### Retriving Compiler Flags
Compiler flags are stored in the CustomDebugInformation in a PDB using the GUID `B5FEEC05-8CD0-4A83-96DA-466284BB4BD8` .
Example how to retrieve and read this information using `System.Reflection.Metadata` :
``` csharp
var compilationOptionsGuid = new Guid("B5FEEC05-8CD0-4A83-96DA-466284BB4BD8");
var path = "path/to/pdb";
using var stream = File.OpenRead(path);
using var metadataReaderProvider = MetadataReaderProvider.FromPortablePdbStream(stream);
var metadataReader = metadataReaderProvider.GetMetadataReader();
foreach (var handle in metadataReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition))
{
var customDebugInformation = metadataReader.GetCustomDebugInformation(handle);
if (metadataReader.GetGuid(customDebugInformation.Kind) == compilationOptionsGuid)
{
var blobReader = metadataReader.GetBlobReader(customDebugInformation.Value);
// Compiler flag bytes are UTF-8 null-terminated key-value pairs
var nullIndex = blobReader.IndexOf(0);
while (nullIndex >= 0)
{
var key = blobReader.ReadUTF8(nullIndex);
// Skip the null terminator
blobReader.ReadByte();
nullIndex = blobReader.IndexOf(0);
var value = blobReader.ReadUTF8(nullIndex);
// Skip the null terminator
blobReader.ReadByte();
nullIndex = blobReader.IndexOf(0);
// key and value now have strings containing serialized compiler flag information
Console.WriteLine($"{key} = {value}");
}
}
}
```
| # Embedding Compilation options in Portable PDBs
Prior to this feature the compiler did not emit all information that's necessary to reconstruct the original compilation to the output binaries.
It is desirable to include such information in order to support scenarios such as validation that given binaries can be reproduced from their original sources, [post-build source analysis](https://github.com/dotnet/roslyn/issues/41395), etc.
The goal of this feature is to be able to construct a compilation that is exactly the same as an initial compilation as long as it meets the conditions outlined in the assumptions below.
This document is restricted to the following assumptions:
1. The full benefit is for builds with `-deterministic` and published to the symbol server. That said the compiler embeds compilation options and references to all Portable PDBs.
2. Source generator and analyzer references are not needed for this task. They may be useful, but are out of scope for this feature.
3. Any storage capacity used for PDBs and source should not impact this feature, such as compression algorithm.
4. Only Portable PDB files will be included for this spec. This feature can be expanded past these once it is implemented and proven needed elsewhere.
This document will provide the expanded specification to the Portable PDB format. Any additions to that format will be ported to expand documentation provided in [dotnet-runtime](https://github.com/dotnet/runtime/blob/main/docs/design/specs/PortablePdb-Metadata.md).
## PDB Format Additions
#### Compilation Metadata References custom debug information
Symbol server uses a [key](https://github.com/dotnet/symstore/blob/main/docs/specs/SSQP_Key_Conventions.md#pe-timestamp-filesize) computed from the COFF header in the PE image:
Timestamp: 4 byte integer
Size of image: 4 byte integer
Example:
File name: `example.exe`
COFF header Timestamp field: `0x542d5742`
COFF header SizeOfImage field: `0x32000`
Lookup key: `example.exe/542d574232000/example.exe`
To fully support metadata references, a user will need to be able to find the exact PE image that was used in the compilation. This will be done by storing the parts that make up the symbol server key. The MVID of a reference will be stored since it's a GUID that represents the symbol. This is to future proof the information for reference lookup.
At this time, only external references for the compilation will be included. Any other references may be added later in a separate blob.
Metadata references are stored as binary. The binary encoding will be as follows (order matters):
Name: A UTF-8 string (null terminated)
Aliases: UTF-8 Comma (, ) separated list of aliases (null terminated). May be empty
MetadataImageKind: byte value representing Microsoft. CodeAnalysis. MetadataImageKind
EmbedInteropTypes/MetadataImageKind: byte, reads as binary values starting in order from right to left
MetadataImageKind: 1 if Assembly, 0 if Module
EmbedInteropTypes: 1 if true
Examples:
0b11, MetadataImageKind.Assembly and EmbedInteropTypes = true
0b01, MetadataImageKind.Module and EmbedInteropTypes = true
Timestamp: 4 byte integer
File Size: 4 byte integer
MVID: 16 byte integer (GUID)
#### Retrieving Metadata References
Metadata references are stored in the CustomDebugInformation in a PDB using the GUID `7E4D4708-096E-4C5C-AEDA-CB10BA6A740D` .
Example how to retrieve and read this information using `System.Reflection.Metadata` :
``` csharp
var metadataReferencesGuid = new Guid("7E4D4708-096E-4C5C-AEDA-CB10BA6A740D");
var path = "path/to/pdb";
using var stream = File.OpenRead(path);
using var metadataReaderProvider = MetadataReaderProvider.FromPortablePdbStream(stream);
var metadataReader = metadataReaderProvider.GetMetadataReader();
foreach (var handle in metadataReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition))
{
var customDebugInformation = metadataReader.GetCustomDebugInformation(handle);
if (metadataReader.GetGuid(customDebugInformation.Kind) == metadataReferencesGuid)
{
var blobReader = metadataReader.GetBlobReader(customDebugInformation.Value);
// Each loop is one reference
while (blobReader.RemainingBytes > 0)
{
// Order of information
// File name (null terminated string): A.exe
// Extern Alias (null terminated string): a1,a2,a3
// EmbedInteropTypes/MetadataImageKind (byte)
// COFF header Timestamp field (4 byte int)
// COFF header SizeOfImage field (4 byte int)
// MVID (Guid, 24 bytes)
var terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var name = blobReader.ReadUTF8(terminatorIndex);
// Skip the null terminator
blobReader.ReadByte();
terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var externAliases = blobReader.ReadUTF8(terminatorIndex);
// Skip the null terminator
blobReader.ReadByte();
var embedInteropTypesAndKind = blobReader.ReadByte();
var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10;
var kind = (embedInteropTypesAndKind & 0b1) == 0b1
? MetadataImageKind.Assembly
: MetadataImageKind.Module;
var timestamp = blobReader.ReadInt32();
var imageSize = blobReader.ReadInt32();
var mvid = blobReader.ReadGuid();
Console.WriteLine(name);
Console.WriteLine($"Extern Aliases: \"{externAliases}\"");
Console.WriteLine($"Embed Interop Types: {embedInteropTypes}");
Console.WriteLine($"Metadata Image Kind: {kind}");
Console.WriteLine($"Timestamp: {timestamp}");
Console.WriteLine($"Image Size: {imageSize}");
Console.WriteLine($"MVID: {mvid}");
Console.WriteLine();
}
}
}
```
### Compiler Options custom debug information
The remaining values will be stored as key value pairs in the pdb. The storage format will be UTF8 encoded key value pairs that are null terminated. Order is not guaranteed. Any values left out can be assumed to be the default for the type. Keys may be different for Visual Basic and CSharp. They are serialized to reflect the command line arguments representing the same values
Example:
`compilerversion\01.2.3-example-sha\0sourceencoding\0utf-8\0checked\01\0unsafe\01\0langversion\0latest\0nullable\0Enable`
## List of Compiler Flags
#### CSharp Flags That Can Be Derived From PDB or Assembly
* baseaddress
* checksumalgorithm
* debug
* deterministic
* embed
* filealign
* highentropyva
* link
- Represented by a metadata reference with `EmbededInteropTypes=true`
* linkresource
- Will be represented in metadata reference embedded in pdb
* main
- Already stored in PDB as the entry point token
* moduleassemblyname
* modulename
* nostdlib
- Will be represented in metadata reference embedded in pdb
* nowin32manifest
* pdb
* platform
* publicsign
* resource
- Will be represented in metadata reference embedded in pdb
* subsystemversion
* win32icon
* win32manifest
* win32res
#### CSharp Flags Not Included
* bugreport
* delaysign
* doc
* errorendlocation
* errorlog
* errorreport
* fullpaths
* incremental
* keycontainer
* keyfile
* noconfig
* nologo
* nowarn
* out
* parallel
* pathmap
* preferreduilang
* recurse
* refout
* refonly
* reportanalyzer
* ruleset
* utf8output
* version
* warn
* warnaserror
#### Visual Basic Flags That Can Be Derived From PDB or Assembly
* baseaddress
* checksumalgorithm
* debug
* filealign
* highentropyva
* linkresource
- Will be represented in metadata reference embedded in pdb
* main
* nostdlib
- Will be represented in metadata reference embedded in pdb
* platform
* resource
- Will be represented in metadata reference embedded in pdb
* subsystemversion
* win32icon
* win32manifest
* win32resource
#### Visual Basic Flags Not Included
* bugreport
* delaysign
* doc
* errorreport
* help
* keycontainer
* keyfile
* libpath
* moduleassemblyname
* modulename
* netcf
* noconfig
* nologo
* nowarn
* nowin32manifest
* optioncompare
* optionexplicit
* optioninfer
* out
* parallel
* preferreduilang
* quiet
* recurse
* refonly
* refout
* rootnamespace
* ruleset
* sdkpath
* utf8output
* vbruntime
* verbose
* warnaserror
#### Shared Options for CSharp and Visual Basic
| PDB Key | Format | Default | Description |
| ---------------------- | --------------------------------------- | --------- | ------------ |
| language | `CSharp\|Visual Basic` | required | Language name. |
| compiler-version | [SemVer2](https://semver.org/spec/v2.0.0.html) string | required | Full version with SHA |
| runtime-version | [SemVer2](https://semver.org/spec/v2.0.0.html) string | required | [runtime version](#runtime-version) |
| source-file-count | int32 | required | Count of files in the document table that are source files |
| optimization | `(debug\|debug-plus\|release\|release-debug-plus)` | `'debug'` | [optimization](#optimization) |
| portability-policy | `(0\|1\|2\|3)` | `0` | [portability policy](#portability-policy) |
| default-encoding | string | none | [file encoding](#file-encoding) |
| fallback-encoding | string | none | [file encoding](#file-encoding) |
| output-kind | string | require | The value passed to `/target` |
| platform | string | require | The value passed to `/platform` |
#### Options For CSharp
See [compiler options](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/listed-alphabetically) documentation
| PDB Key | Format | Default | Description |
| ---------------------- | --------------------------------------- | --------- | ------------ |
| language-version | `[0-9]+(\.[0-9]+)?` | required | [langversion](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/langversion-compiler-option) |
| define | `,`-separated identifier list | empty | [define](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/define-compiler-option) |
| checked | `(True\|False)` | `False` | [checked](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/checked-compiler-option) |
| nullable | `(Disable\|Warnings\|Annotations\|Enable)` | `Disable` | [nullable](https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references) |
| unsafe | `(True\|False)` | `False` | [unsafe](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/unsafe-compiler-option) |
#### Options For Visual Basic
See [compiler options](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/compiler-options-listed-alphabetically) documentation
| PDB Key | Format | Default | Description |
| ---------------------- | ------------------------------------------ | -------- | ----------- |
| language-version | `[0-9]+(\.[0-9]+)?` | required | [langversion](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/langversion) |
| define | `,`-separated list of name `=` value pairs | empty | [define](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/define) |
| checked | `(True\|False)` | `False` | Opposite of [removeintchecks](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/removeintchecks) |
| option-strict | `(Off\|Custom\|On)` | required | [option strict](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/optionstrict) |
| option-infer | `(True\|False)` | required | [option infer](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/optioninfer) |
| option-compare-text | `(True\|False)` | required | [option compare](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/optioncompare) |
| option-explicit | `(True\|False)` | required | [option explicit](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/optionexplicit) |
| embed-runtime | `(True\|False)` | required | Whether or not the VB runtime was embedded into the PE |
| global-namespaces | `,` -separated identifier list | empty | [imports](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/imports)
| root-namespace | string | empty | [root namespace](https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/rootnamespace)
#### Portability Policy
Portability policy is derived from the [appconfig command option](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/appconfig-compiler-option).
Since appconfig is a pointer to a file not embedded in the PDB or PE, information that will directly impact the compilation is extracted. This is stored in a flag called `portability-policy` with a numeric value from \[0-3\]. This value directly correlates to reconstructing the [AssemblyPortabilityPolicy](https://github.com/dotnet/roslyn/blob/bdb3ece74c85892709f5e42ae7d67248999ecc3b/src/Compilers/Core/Portable/Desktop/AssemblyPortabilityPolicy.cs).
* 0 -> SuppressSilverlightPlatformAssembliesPortability = false, SuppressSilverlightLibraryAssembliesPortability = false
* 1 -> SuppressSilverlightPlatformAssembliesPortability = true, SuppressSilverlightLibraryAssembliesPortability = false
* 2 -> SuppressSilverlightPlatformAssembliesPortability = false, SuppressSilverlightLibraryAssembliesPortability = true
* 3 -> SuppressSilverlightPlatformAssembliesPortability = true, SuppressSilverlightLibraryAssembliesPortability = true
#### File Encoding
Encoding will be stored in two keys: "default-encoding" and "fallback-encoding".
If `default-encoding` is present, it represents the forced encoding used, such as by passing in "codepage" to the command line. All files without a Byte Order Mark (BOM) should be decoded using this encoding.
If `fallback-encoding` is present, it means that no default encoding was specified but an encoding was detected and used. The compiler [has logic](https://github.com/dotnet/roslyn/blob/462eac607741023e5c2d518ac1045f4c6dabd501/src/Compilers/Core/Portable/EncodedStringText.cs#L32) to determine an encoding is none is specified, so the value that was computed is stored so it can be reused in future compilations.
Both values are written as [WebName](https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.webname?view=netcore-3.1) values for an encoding.
#### Optimization
Optimization level can be specified from the command line with [optimize](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/optimize-compiler-option). It gets translated to the [OptimizationLevel](https://github.com/dotnet/roslyn/blob/e704ca635bd6de70a0250e34c4567c7a28fa9f6d/src/Compilers/Core/Portable/Compilation/OptimizationLevel.cs) that is emitted to the PDB.
There are three possible values:
* `debug` -> `OptimizationLevel.Debug` and DebugPlusMode is false
* `debug-plus` -> `OptimizationLevel.Debug` and DebugPlusMode is true
* `release` -> `OptimizationLevel.Release` and DebugPlusMode is false (ignored)
#### Runtime Version
The runtime version used that the compiler was running in when generating the PE. This is stored as [informational version](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assemblyinformationalversionattribute.informationalversion?view=netcore-3.1#System_Reflection_AssemblyInformationalVersionAttribute_InformationalVersion).
Runtime version is stored since it can impact the unicode character interpretation and decimal arithmetics, which both play a role in how code is compiled from source. There may also be future variations where the different versions of the runtime impact compilation.
### Retriving Compiler Flags
Compiler flags are stored in the CustomDebugInformation in a PDB using the GUID `B5FEEC05-8CD0-4A83-96DA-466284BB4BD8` .
Example how to retrieve and read this information using `System.Reflection.Metadata` :
``` csharp
var compilationOptionsGuid = new Guid("B5FEEC05-8CD0-4A83-96DA-466284BB4BD8");
var path = "path/to/pdb";
using var stream = File.OpenRead(path);
using var metadataReaderProvider = MetadataReaderProvider.FromPortablePdbStream(stream);
var metadataReader = metadataReaderProvider.GetMetadataReader();
foreach (var handle in metadataReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition))
{
var customDebugInformation = metadataReader.GetCustomDebugInformation(handle);
if (metadataReader.GetGuid(customDebugInformation.Kind) == compilationOptionsGuid)
{
var blobReader = metadataReader.GetBlobReader(customDebugInformation.Value);
// Compiler flag bytes are UTF-8 null-terminated key-value pairs
var nullIndex = blobReader.IndexOf(0);
while (nullIndex >= 0)
{
var key = blobReader.ReadUTF8(nullIndex);
// Skip the null terminator
blobReader.ReadByte();
nullIndex = blobReader.IndexOf(0);
var value = blobReader.ReadUTF8(nullIndex);
// Skip the null terminator
blobReader.ReadByte();
nullIndex = blobReader.IndexOf(0);
// key and value now have strings containing serialized compiler flag information
Console.WriteLine($"{key} = {value}");
}
}
}
```
| 1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/records.md | Records for C#
==============
Records are a new, simplified declaration form for C# class and struct types that combine the benefits of a number of simpler features. We describe the new features (caller-receiver parameters and *with-expression*s), give the syntax and semantics for record declarations, and then provide some examples.
# caller-receiver parameters
Currently a method parameter's *default-argument* must be
- a *constant-expression*; or
- an expression of the form `new S()` where `S` is a value type; or
- an expression of the form `default(S)` where `S` is a value type
We extend this to add the following
- an expression of the form `this.Identifier`
This new form is called a *caller-receiver default-argument*, and is allowed only if all of the following are satisfied
- The method in which it appears is an instance method; and
- The expression `this.Identifier` binds to an instance member of the enclosing type, which must be either a field or a property; and
- The member to which it binds (and the `get` accessor, if it is a property) is at least as accessible as the method; and
- The type of `this.Identifier` is implicitly convertible by an identity or nullable conversion to the type of the parameter (this is an existing constraint on *default-argument*).
When an argument is omitted from an invocation of a function member for a corresponding optional parameter with a *caller-receiver default-argument*, the value of the receiver's member is implicitly passed.
> **Design Notes**: the main reason for the caller-receiver parameter is to support the *with-expression*. The idea is that you can declare a method like this
> ```cs
> class Point
> {
> public readonly int X;
> public readonly int Y;
> public Point With(int x = this.X, int y = this.Y) => new Point(x, y);
> // etc
> }
> ```
> and then use it like this
> ```cs
> Point p = new Point(3, 4);
> p = p.With(x: 1);
> ```
> To create a new `Point` just like an existing `Point` but with the value of `X` changed.
>
> It is an open question whether or not the syntactic form of the *with-expression* is worth adding once we have support for caller-receiver parameters, so it is possible we would do this *instead of* rather than *in addition to* the *with-expression*.
- [ ] **Open issue**: What is the order in which a *caller-receiver default-argument* is evaluated with respect to other arguments? Should we say that it is unspecified?
# with-expressions
A new expression form is proposed:
```antlr
primary_expression
: with_expression
;
with_expression
: primary_expression 'with' '{' with_initializer_list '}'
;
with_initializer_list
: with_initializer
| with_initializer ',' with_initializer_list
;
with_initializer
: identifier '=' expression
;
```
The token `with` is a new context-sensitive keyword.
Each *identifier* on the left of a *with_initilaizer* must bind to an accessible instance field or property of the type of the *primary_expression* of the *with_expression*. There may be no duplicated name among these identifiers of a given *with_expression*.
A *with_expression* of the form
> *e1* `with` `{` *identifier* = *e2*, ... `}`
is treated as an invocation of the form
> *e1*`.With(`*identifier2*`:` *e2*, ...`)`
Where, for each method named `With` that is an accessible instance member of *e1*, we select *identifier2* as the name of the first parameter in that method that has a caller-receiver parameter that is the same member as the instance field or property bound to *identifier*. If no such parameter can be identified that method is eliminated from consideration. The method to be invoked is selected from among the remaining candidates by overload resolution.
> **Design Notes**: Given caller-receiver parameters, many of the benefits of the *with-expression* are available without this special syntax form. We are therefore considering whether or not it is needed. Its main benefit is allowing one to program in terms of the names of fields and properties, rather than in terms of the names of parameters. In this way we improve both readability and the quality of tooling (e.g. go-to-definition on the identifier of a *with_expression* would navigate to the property rather than to a method parameter).
- [ ] **Open issue**: This description should be modified to support extension methods.
- [ ] **Open issue**: Does this syntactic sugar actually pay for itself?
# pattern-matching
See the [Pattern Matching Specification](patterns.md) for a specification of `operator is` and its relationship to pattern-matching.
> **Design Notes**: By virtue of the compiler-generated `operator is` as specified herein, and the specification for pattern-matching, a record declaration
> ```cs
> public class Point(int X, int Y);
> ```
> will support positional pattern-matching as follows
> ```cs
> Point p = new Point(3, 4);
> if (p is Point(3, var y)) { // if X is 3
> Console.WriteLine(y); // print Y
> }
> ```
# record type declarations
The syntax for a `class` or `struct` declaration is extended to support value parameters; the parameters become properties of the type:
```antlr
class_declaration
: attributes? class_modifiers? 'partial'? 'class' identifier type_parameter_list?
record_parameters? record_class_base? type_parameter_constraints_clauses? class_body
;
struct_declaration
: attributes? struct_modifiers? 'partial'? 'struct' identifier type_parameter_list?
record_parameters? struct_interfaces? type_parameter_constraints_clauses? struct_body
;
record_class_base
: class_type record_base_arguments?
| interface_type_list
| class_type record_base_arguments? ',' interface_type_list
;
record_base_arguments
: '(' argument_list? ')'
;
record_parameters
: '(' record_parameter_list? ')'
;
record_parameter_list
: record_parameter
| record_parameter record_parameter_list
;
record_parameter
: attributes? type identifier record_property_name? default_argument?
;
record_property_name
: ':' identifier
;
class_body
: '{' class_member_declarations? '}'
| ';'
;
struct_body
: '{' struct_members_declarations? '}'
| ';'
;
```
> **Design Notes**: Because record types are often useful without the need for any members explicitly declared in a class-body, we modify the syntax of the declaration to allow a body to be simply a semicolon.
A class (struct) declared with the *record-parameters* is called a *record class* (*record struct*), either of which is a *record type*.
- [ ] **Open issue**: We need to include *primary_constructor_body* in the grammar so that it can appear inside a record type declaration.
- [ ] **Open issue**: What are the name conflict rules for the parameter names? Presumably one is not allowed to conflict with a type parameter or another *record-parameter*.
- [ ] **Open issue**: We need to specify the scope of the record-parameters. Where can they be used? Presumably within instance field initializers and *primary_constructor_body* at least.
- [ ] **Open issue**: Can a record type declaration be partial? If so, must the parameters be repeated on each part?
### Members of a record type
In addition to the members declared in the *class-body*, a record type has the following additional members:
#### Primary Constructor
A record type has a `public` constructor whose signature corresponds to the value parameters of the type declaration. This is called the *primary constructor* for the type, and causes the implicitly declared *default constructor* to be suppressed.
At runtime the primary constructor
* initializes compiler-generated backing fields for the properties corresponding to the value parameters (if these properties are compiler-provided; [see 1.1.2](#1.1.2)); then
* executes the instance field initializers appearing in the *class-body*; and then
* invokes a base class constructor:
* If there are arguments in the *record_base_arguments*, a base constructor selected by overload resolution with these arguments is invoked;
* Otherwise a base constructor is invoked with no arguments.
* executes the body of each *primary_constructor_body*, if any, in source order.
- [ ] **Open issue**: We need to specify that order, particularly across compilation units for partials.
- [ ] **Open Issue**: We need to specify that every explicitly declared constructor must chain to the primry constructor.
- [ ] **Open issue**: Should it be allowed to change the access modifier on the primary constructor?
- [ ] **Open issue**: In a record struct, it is an error for there to be no record parameters?
#### Primary constructor body
```antlr
primary_constructor_body
: attributes? constructor_modifiers? identifier block
;
```
A *primary_constructor_body* may only be used within a record type declaration. The *identifier* of a *primary_constructor_body* shall name the record type in which it is declared.
The *primary_constructor_body* does not declare a member on its own, but is a way for the programmer to provide attributes for, and specify the access of, a record type's primary constructor. It also enables the programmer to provide additional code that will be executed when an instance of the record type is constructed.
- [ ] **Open issue**: We should note that a struct default constructor bypasses this.
- [ ] **Open issue**: We should specify the execution order of initialization.
- [ ] **Open issue**: Should we allow something like a *primary_constructor_body* (presumably without attributes and modifiers) in a non-record type declaration, and treat it like we would the code of an instance field initializer?
#### Properties
For each record parameter of a record type declaration there is a corresponding `public` property member whose name and type are taken from the value parameter declaration. Its name is the *identifier* of the *record_property_name*, if present, or the *identifier* of the *record_parameter* otherwise. If no concrete (i.e. non-abstract) public property with a `get` accessor and with this name and type is explicitly declared or inherited, it is produced by the compiler as follows:
* For a *record struct* or a `sealed` *record class*:
* A `private` `readonly` field is produced as a backing field for a `readonly` property. Its value is initialized during construction with the value of the corresponding primary constructor parameter.
* The property's `get` accessor is implemented to return the value of the backing field.
* Each "matching" inherited virtual property's `get` accessor is overridden.
> **Design notes**: In other words, if you extend a base class or implement an interface that declares a public abstract property with the same name and type as a record parameter, that property is overridden or implemented.
- [ ] **Open issue**: Should it be possible to change the access modifier on a property when it is explicitly declared?
- [ ] **Open issue**: Should it be possible to substitute a field for a property?
#### Object Methods
For a *record struct* or a `sealed` *record class*, implementations of the methods `object.GetHashCode()` and `object.Equals(object)` are produced by the compiler unless provided by the user.
- [ ] **Open issue**: We should precisely specify their implementation.
- [ ] **Open issue**: We should also add the interface `IEquatable<T>` for the record type and specify that implementations are provided.
- [ ] **Open issue**: We should also specify that we implement every `IEquatable<T>.Equals`.
- [ ] **Open issue**: We should specify precisely how we solve the problem of Equals in the face of record inheritance: specifically how we generate equality methods such that they are symmetric, transitive, reflexive, etc.
- [ ] **Open issue**: It has been proposed that we implement `operator ==` and `operator !=` for record types.
- [ ] **Open issue**: Should we auto-generate an implementation of `object.ToString`?
#### `operator is`
A record type has a compiler-generated `public static void operator is` unless one with any signature is provided by the user. Its first parameter is the enclosing record type, and each subsequent parameter is an `out` parameter of the same name and type as the corresponding parameter of the record type. The compiler-provided implementation of this method shall assign each `out` parameter with the value of the corresponding property.
See [the pattern-matching specification](patterns.md) for the semantics of `operator is`.
#### `With` method
Unless there is a user-declared member named `With` declared, a record type has a compiler-provided method named `With` whose return type is the record type itself, and containing one value parameter corresponding to each *record-parameter* in the same order that these parameters appear in the record type declaration. Each parameter shall have a *caller-receiver default-argument* of the corresponding property.
In an `abstract` record class, the compiler-provided `With` method is abstract. In a record struct, or a sealed record class, the compiler-provided `With` method is `sealed`. Otherwise the compiler-provided `With` method is `virtual and its implementation shall return a new instance produced by invoking the the primary constructor with the parameters as arguments to create a new instance from the parameters, and return that new instance.
- [ ] **Open issue**: We should also specify under what conditions we override or implement inherited virtual `With` methods or `With` methods from implemented interfaces.
- [ ] **Open issue**: We should say what happens when we inherit a non-virtual `With` method.
> **Design notes**: Because record types are by default immutable, the `With` method provides a way of creating a new instance that is the same as an existing instance but with selected properties given new values. For example, given
> ```cs
> public class Point(int X, int Y);
> ```
> there is a compiler-provided member
> ```cs
> public virtual Point With(int X = this.X, int Y = this.Y) => new Point(X, Y);
> ```
> Which enables an variable of the record type
> ```cs
> var p = new Point(3, 4);
> ```
> to be replaced with an instance that has one or more properties different
> ```cs
> p = p.With(X: 5);
> ```
> This can also be expressed using the *with_expression*:
> ```cs
> p = p with { X = 5 };
> ```
# 5. Examples
### record struct example
This record struct
```cs
public struct Pair(object First, object Second);
```
is translated to this code
```cs
public struct Pair : IEquatable<Pair>
{
public object First { get; }
public object Second { get; }
public Pair(object First, object Second)
{
this.First = First;
this.Second = Second;
}
public bool Equals(Pair other) // for IEquatable<Pair>
{
return Equals(First, other.First) && Equals(Second, other.Second);
}
public override bool Equals(object other)
{
return (other as Pair)?.Equals(this) == true;
}
public override GetHashCode()
{
return (First?.GetHashCode()*17 + Second?.GetHashCode()).GetValueOrDefault();
}
public Pair With(object First = this.First, object Second = this.Second) => new Pair(First, Second);
public static void operator is(Pair self, out object First, out object Second)
{
First = self.First;
Second = self.Second;
}
}
```
- [ ] **Open issue**: should the implementation of Equals(Pair other) be a public member of Pair?
- [ ] **Open issue**: This implementation of `Equals` is not symmetric in the face of inheritance.
> **Design notes**: Because one record type can inherit from another, and this implementation of `Equals` would not be symmetric in that case, it is not correct. We propose to implement equality this way:
> ```cs
> public bool Equals(Pair other) // for IEquatable<Pair>
> {
> return other != null && EqualityContract == other.EqualityContract &&
> Equals(First, other.First) && Equals(Second, other.Second);
> }
> protected virtual Type EqualityContract => typeof(Pair);
> ```
> Derived records would `override EqualityContract`. The less attractive alternative is to restrict inheritance.
### sealed record example
This sealed record class
```cs
public sealed class Student(string Name, decimal Gpa);
```
is translated into this code
```cs
public sealed class Student : IEquatable<Student>
{
public string Name { get; }
public decimal Gpa { get; }
public Student(string Name, decimal Gpa)
{
this.Name = Name;
this.Gpa = Gpa;
}
public bool Equals(Student other) // for IEquatable<Student>
{
return other != null && Equals(Name, other.Name) && Equals(Gpa, other.Gpa);
}
public override bool Equals(object other)
{
return this.Equals(other as Student);
}
public override int GetHashCode()
{
return (Name?.GetHashCode()*17 + Gpa?.GetHashCode()).GetValueOrDefault();
}
public Student With(string Name = this.Name, decimal Gpa = this.Gpa) => new Student(Name, Gpa);
public static void operator is(Student self, out string Name, out decimal Gpa)
{
Name = self.Name;
Gpa = self.Gpa;
}
}
```
### abstract record class example
This abstract record class
```cs
public abstract class Person(string Name);
```
is translated into this code
```cs
public abstract class Person : IEquatable<Person>
{
public string Name { get; }
public Person(string Name)
{
this.Name = Name;
}
public bool Equals(Person other)
{
return other != null && Equals(Name, other.Name);
}
public override Equals(object other)
{
return Equals(other as Person);
}
public override int GetHashCode()
{
return (Name?.GetHashCode()).GetValueOrDefault();
}
public abstract Person With(string Name = this.Name);
public static void operator is(Person self, out string Name)
{
Name = self.Name;
}
}
```
### combining abstract and sealed records
Given the abstract record class `Person` above, this sealed record class
```cs
public sealed class Student(string Name, decimal Gpa) : Person(Name);
```
is translated into this code
```cs
public sealed class Student : Person, IEquatable<Student>
{
public override string Name { get; }
public decimal Gpa { get; }
public Student(string Name, decimal Gpa) : base(Name)
{
this.Name = Name;
this.Gpa = Gpa;
}
public override bool Equals(Student other) // for IEquatable<Student>
{
return Equals(Name, other.Name) && Equals(Gpa, other.Gpa);
}
public bool Equals(Person other) // for IEquatable<Person>
{
return (other as Student)?.Equals(this) == true;
}
public override bool Equals(object other)
{
return (other as Student)?.Equals(this) == true;
}
public override int GetHashCode()
{
return (Name?.GetHashCode()*17 + Gpa.GetHashCode()).GetValueOrDefault();
}
public Student With(string Name = this.Name, decimal Gpa = this.Gpa) => new Student(Name, Gpa);
public override Person With(string Name = this.Name) => new Student(Name, Gpa);
public static void operator is(Student self, out string Name, out decimal Gpa)
{
Name = self.Name;
Gpa = self.Gpa;
}
}
```
| Records for C#
==============
Records are a new, simplified declaration form for C# class and struct types that combine the benefits of a number of simpler features. We describe the new features (caller-receiver parameters and *with-expression*s), give the syntax and semantics for record declarations, and then provide some examples.
# caller-receiver parameters
Currently a method parameter's *default-argument* must be
- a *constant-expression*; or
- an expression of the form `new S()` where `S` is a value type; or
- an expression of the form `default(S)` where `S` is a value type
We extend this to add the following
- an expression of the form `this.Identifier`
This new form is called a *caller-receiver default-argument*, and is allowed only if all of the following are satisfied
- The method in which it appears is an instance method; and
- The expression `this.Identifier` binds to an instance member of the enclosing type, which must be either a field or a property; and
- The member to which it binds (and the `get` accessor, if it is a property) is at least as accessible as the method; and
- The type of `this.Identifier` is implicitly convertible by an identity or nullable conversion to the type of the parameter (this is an existing constraint on *default-argument*).
When an argument is omitted from an invocation of a function member for a corresponding optional parameter with a *caller-receiver default-argument*, the value of the receiver's member is implicitly passed.
> **Design Notes**: the main reason for the caller-receiver parameter is to support the *with-expression*. The idea is that you can declare a method like this
> ```cs
> class Point
> {
> public readonly int X;
> public readonly int Y;
> public Point With(int x = this.X, int y = this.Y) => new Point(x, y);
> // etc
> }
> ```
> and then use it like this
> ```cs
> Point p = new Point(3, 4);
> p = p.With(x: 1);
> ```
> To create a new `Point` just like an existing `Point` but with the value of `X` changed.
>
> It is an open question whether or not the syntactic form of the *with-expression* is worth adding once we have support for caller-receiver parameters, so it is possible we would do this *instead of* rather than *in addition to* the *with-expression*.
- [ ] **Open issue**: What is the order in which a *caller-receiver default-argument* is evaluated with respect to other arguments? Should we say that it is unspecified?
# with-expressions
A new expression form is proposed:
```antlr
primary_expression
: with_expression
;
with_expression
: primary_expression 'with' '{' with_initializer_list '}'
;
with_initializer_list
: with_initializer
| with_initializer ',' with_initializer_list
;
with_initializer
: identifier '=' expression
;
```
The token `with` is a new context-sensitive keyword.
Each *identifier* on the left of a *with_initilaizer* must bind to an accessible instance field or property of the type of the *primary_expression* of the *with_expression*. There may be no duplicated name among these identifiers of a given *with_expression*.
A *with_expression* of the form
> *e1* `with` `{` *identifier* = *e2*, ... `}`
is treated as an invocation of the form
> *e1*`.With(`*identifier2*`:` *e2*, ...`)`
Where, for each method named `With` that is an accessible instance member of *e1*, we select *identifier2* as the name of the first parameter in that method that has a caller-receiver parameter that is the same member as the instance field or property bound to *identifier*. If no such parameter can be identified that method is eliminated from consideration. The method to be invoked is selected from among the remaining candidates by overload resolution.
> **Design Notes**: Given caller-receiver parameters, many of the benefits of the *with-expression* are available without this special syntax form. We are therefore considering whether or not it is needed. Its main benefit is allowing one to program in terms of the names of fields and properties, rather than in terms of the names of parameters. In this way we improve both readability and the quality of tooling (e.g. go-to-definition on the identifier of a *with_expression* would navigate to the property rather than to a method parameter).
- [ ] **Open issue**: This description should be modified to support extension methods.
- [ ] **Open issue**: Does this syntactic sugar actually pay for itself?
# pattern-matching
See the [Pattern Matching Specification](patterns.md) for a specification of `operator is` and its relationship to pattern-matching.
> **Design Notes**: By virtue of the compiler-generated `operator is` as specified herein, and the specification for pattern-matching, a record declaration
> ```cs
> public class Point(int X, int Y);
> ```
> will support positional pattern-matching as follows
> ```cs
> Point p = new Point(3, 4);
> if (p is Point(3, var y)) { // if X is 3
> Console.WriteLine(y); // print Y
> }
> ```
# record type declarations
The syntax for a `class` or `struct` declaration is extended to support value parameters; the parameters become properties of the type:
```antlr
class_declaration
: attributes? class_modifiers? 'partial'? 'class' identifier type_parameter_list?
record_parameters? record_class_base? type_parameter_constraints_clauses? class_body
;
struct_declaration
: attributes? struct_modifiers? 'partial'? 'struct' identifier type_parameter_list?
record_parameters? struct_interfaces? type_parameter_constraints_clauses? struct_body
;
record_class_base
: class_type record_base_arguments?
| interface_type_list
| class_type record_base_arguments? ',' interface_type_list
;
record_base_arguments
: '(' argument_list? ')'
;
record_parameters
: '(' record_parameter_list? ')'
;
record_parameter_list
: record_parameter
| record_parameter record_parameter_list
;
record_parameter
: attributes? type identifier record_property_name? default_argument?
;
record_property_name
: ':' identifier
;
class_body
: '{' class_member_declarations? '}'
| ';'
;
struct_body
: '{' struct_members_declarations? '}'
| ';'
;
```
> **Design Notes**: Because record types are often useful without the need for any members explicitly declared in a class-body, we modify the syntax of the declaration to allow a body to be simply a semicolon.
A class (struct) declared with the *record-parameters* is called a *record class* (*record struct*), either of which is a *record type*.
- [ ] **Open issue**: We need to include *primary_constructor_body* in the grammar so that it can appear inside a record type declaration.
- [ ] **Open issue**: What are the name conflict rules for the parameter names? Presumably one is not allowed to conflict with a type parameter or another *record-parameter*.
- [ ] **Open issue**: We need to specify the scope of the record-parameters. Where can they be used? Presumably within instance field initializers and *primary_constructor_body* at least.
- [ ] **Open issue**: Can a record type declaration be partial? If so, must the parameters be repeated on each part?
### Members of a record type
In addition to the members declared in the *class-body*, a record type has the following additional members:
#### Primary Constructor
A record type has a `public` constructor whose signature corresponds to the value parameters of the type declaration. This is called the *primary constructor* for the type, and causes the implicitly declared *default constructor* to be suppressed.
At runtime the primary constructor
* initializes compiler-generated backing fields for the properties corresponding to the value parameters (if these properties are compiler-provided; [see 1.1.2](#1.1.2)); then
* executes the instance field initializers appearing in the *class-body*; and then
* invokes a base class constructor:
* If there are arguments in the *record_base_arguments*, a base constructor selected by overload resolution with these arguments is invoked;
* Otherwise a base constructor is invoked with no arguments.
* executes the body of each *primary_constructor_body*, if any, in source order.
- [ ] **Open issue**: We need to specify that order, particularly across compilation units for partials.
- [ ] **Open Issue**: We need to specify that every explicitly declared constructor must chain to the primary constructor.
- [ ] **Open issue**: Should it be allowed to change the access modifier on the primary constructor?
- [ ] **Open issue**: In a record struct, it is an error for there to be no record parameters?
#### Primary constructor body
```antlr
primary_constructor_body
: attributes? constructor_modifiers? identifier block
;
```
A *primary_constructor_body* may only be used within a record type declaration. The *identifier* of a *primary_constructor_body* shall name the record type in which it is declared.
The *primary_constructor_body* does not declare a member on its own, but is a way for the programmer to provide attributes for, and specify the access of, a record type's primary constructor. It also enables the programmer to provide additional code that will be executed when an instance of the record type is constructed.
- [ ] **Open issue**: We should note that a struct default constructor bypasses this.
- [ ] **Open issue**: We should specify the execution order of initialization.
- [ ] **Open issue**: Should we allow something like a *primary_constructor_body* (presumably without attributes and modifiers) in a non-record type declaration, and treat it like we would the code of an instance field initializer?
#### Properties
For each record parameter of a record type declaration there is a corresponding `public` property member whose name and type are taken from the value parameter declaration. Its name is the *identifier* of the *record_property_name*, if present, or the *identifier* of the *record_parameter* otherwise. If no concrete (i.e. non-abstract) public property with a `get` accessor and with this name and type is explicitly declared or inherited, it is produced by the compiler as follows:
* For a *record struct* or a `sealed` *record class*:
* A `private` `readonly` field is produced as a backing field for a `readonly` property. Its value is initialized during construction with the value of the corresponding primary constructor parameter.
* The property's `get` accessor is implemented to return the value of the backing field.
* Each "matching" inherited virtual property's `get` accessor is overridden.
> **Design notes**: In other words, if you extend a base class or implement an interface that declares a public abstract property with the same name and type as a record parameter, that property is overridden or implemented.
- [ ] **Open issue**: Should it be possible to change the access modifier on a property when it is explicitly declared?
- [ ] **Open issue**: Should it be possible to substitute a field for a property?
#### Object Methods
For a *record struct* or a `sealed` *record class*, implementations of the methods `object.GetHashCode()` and `object.Equals(object)` are produced by the compiler unless provided by the user.
- [ ] **Open issue**: We should precisely specify their implementation.
- [ ] **Open issue**: We should also add the interface `IEquatable<T>` for the record type and specify that implementations are provided.
- [ ] **Open issue**: We should also specify that we implement every `IEquatable<T>.Equals`.
- [ ] **Open issue**: We should specify precisely how we solve the problem of Equals in the face of record inheritance: specifically how we generate equality methods such that they are symmetric, transitive, reflexive, etc.
- [ ] **Open issue**: It has been proposed that we implement `operator ==` and `operator !=` for record types.
- [ ] **Open issue**: Should we auto-generate an implementation of `object.ToString`?
#### `operator is`
A record type has a compiler-generated `public static void operator is` unless one with any signature is provided by the user. Its first parameter is the enclosing record type, and each subsequent parameter is an `out` parameter of the same name and type as the corresponding parameter of the record type. The compiler-provided implementation of this method shall assign each `out` parameter with the value of the corresponding property.
See [the pattern-matching specification](patterns.md) for the semantics of `operator is`.
#### `With` method
Unless there is a user-declared member named `With` declared, a record type has a compiler-provided method named `With` whose return type is the record type itself, and containing one value parameter corresponding to each *record-parameter* in the same order that these parameters appear in the record type declaration. Each parameter shall have a *caller-receiver default-argument* of the corresponding property.
In an `abstract` record class, the compiler-provided `With` method is abstract. In a record struct, or a sealed record class, the compiler-provided `With` method is `sealed`. Otherwise the compiler-provided `With` method is `virtual and its implementation shall return a new instance produced by invoking the the primary constructor with the parameters as arguments to create a new instance from the parameters, and return that new instance.
- [ ] **Open issue**: We should also specify under what conditions we override or implement inherited virtual `With` methods or `With` methods from implemented interfaces.
- [ ] **Open issue**: We should say what happens when we inherit a non-virtual `With` method.
> **Design notes**: Because record types are by default immutable, the `With` method provides a way of creating a new instance that is the same as an existing instance but with selected properties given new values. For example, given
> ```cs
> public class Point(int X, int Y);
> ```
> there is a compiler-provided member
> ```cs
> public virtual Point With(int X = this.X, int Y = this.Y) => new Point(X, Y);
> ```
> Which enables an variable of the record type
> ```cs
> var p = new Point(3, 4);
> ```
> to be replaced with an instance that has one or more properties different
> ```cs
> p = p.With(X: 5);
> ```
> This can also be expressed using the *with_expression*:
> ```cs
> p = p with { X = 5 };
> ```
# 5. Examples
### record struct example
This record struct
```cs
public struct Pair(object First, object Second);
```
is translated to this code
```cs
public struct Pair : IEquatable<Pair>
{
public object First { get; }
public object Second { get; }
public Pair(object First, object Second)
{
this.First = First;
this.Second = Second;
}
public bool Equals(Pair other) // for IEquatable<Pair>
{
return Equals(First, other.First) && Equals(Second, other.Second);
}
public override bool Equals(object other)
{
return (other as Pair)?.Equals(this) == true;
}
public override GetHashCode()
{
return (First?.GetHashCode()*17 + Second?.GetHashCode()).GetValueOrDefault();
}
public Pair With(object First = this.First, object Second = this.Second) => new Pair(First, Second);
public static void operator is(Pair self, out object First, out object Second)
{
First = self.First;
Second = self.Second;
}
}
```
- [ ] **Open issue**: should the implementation of Equals(Pair other) be a public member of Pair?
- [ ] **Open issue**: This implementation of `Equals` is not symmetric in the face of inheritance.
> **Design notes**: Because one record type can inherit from another, and this implementation of `Equals` would not be symmetric in that case, it is not correct. We propose to implement equality this way:
> ```cs
> public bool Equals(Pair other) // for IEquatable<Pair>
> {
> return other != null && EqualityContract == other.EqualityContract &&
> Equals(First, other.First) && Equals(Second, other.Second);
> }
> protected virtual Type EqualityContract => typeof(Pair);
> ```
> Derived records would `override EqualityContract`. The less attractive alternative is to restrict inheritance.
### sealed record example
This sealed record class
```cs
public sealed class Student(string Name, decimal Gpa);
```
is translated into this code
```cs
public sealed class Student : IEquatable<Student>
{
public string Name { get; }
public decimal Gpa { get; }
public Student(string Name, decimal Gpa)
{
this.Name = Name;
this.Gpa = Gpa;
}
public bool Equals(Student other) // for IEquatable<Student>
{
return other != null && Equals(Name, other.Name) && Equals(Gpa, other.Gpa);
}
public override bool Equals(object other)
{
return this.Equals(other as Student);
}
public override int GetHashCode()
{
return (Name?.GetHashCode()*17 + Gpa?.GetHashCode()).GetValueOrDefault();
}
public Student With(string Name = this.Name, decimal Gpa = this.Gpa) => new Student(Name, Gpa);
public static void operator is(Student self, out string Name, out decimal Gpa)
{
Name = self.Name;
Gpa = self.Gpa;
}
}
```
### abstract record class example
This abstract record class
```cs
public abstract class Person(string Name);
```
is translated into this code
```cs
public abstract class Person : IEquatable<Person>
{
public string Name { get; }
public Person(string Name)
{
this.Name = Name;
}
public bool Equals(Person other)
{
return other != null && Equals(Name, other.Name);
}
public override Equals(object other)
{
return Equals(other as Person);
}
public override int GetHashCode()
{
return (Name?.GetHashCode()).GetValueOrDefault();
}
public abstract Person With(string Name = this.Name);
public static void operator is(Person self, out string Name)
{
Name = self.Name;
}
}
```
### combining abstract and sealed records
Given the abstract record class `Person` above, this sealed record class
```cs
public sealed class Student(string Name, decimal Gpa) : Person(Name);
```
is translated into this code
```cs
public sealed class Student : Person, IEquatable<Student>
{
public override string Name { get; }
public decimal Gpa { get; }
public Student(string Name, decimal Gpa) : base(Name)
{
this.Name = Name;
this.Gpa = Gpa;
}
public override bool Equals(Student other) // for IEquatable<Student>
{
return Equals(Name, other.Name) && Equals(Gpa, other.Gpa);
}
public bool Equals(Person other) // for IEquatable<Person>
{
return (other as Student)?.Equals(this) == true;
}
public override bool Equals(object other)
{
return (other as Student)?.Equals(this) == true;
}
public override int GetHashCode()
{
return (Name?.GetHashCode()*17 + Gpa.GetHashCode()).GetValueOrDefault();
}
public Student With(string Name = this.Name, decimal Gpa = this.Gpa) => new Student(Name, Gpa);
public override Person With(string Name = this.Name) => new Student(Name, Gpa);
public static void operator is(Student self, out string Name, out decimal Gpa)
{
Name = self.Name;
Gpa = self.Gpa;
}
}
```
| 1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/ref-reassignment.md |
Ref Local and Parameter Reassignment
====================================
In C# 7.2, `ref` locals and parameters cannot be assigned new references,
only assigned values which reassign the underlying storage to the given value.
C# 7.3 introduces a new type of expression, a ref-assignment expression.
The syntax is as follows
```
ref_assignment
: identifier '=' 'ref' expression
```
The identifier on the left-hand side of a *ref_assignment* must be a `ref` or
`ref readonly` local variable, or an `in`, `ref`, or `out` paramater. Ref
assignments allow ref local variables or parameters, which represent
references to storage locations, to be assigned different references. This does
not include the `this` reference, even in structs.
The expression on the right-hand side must have a storage location, i.e. it must
be an "l-value." This l-value must be "ref-compatible" with the variable being
ref-assigned, where ref-compatible means:
* The type of left-hand side and the type of the right-hand side must have an
identity conversion between them.
* Writeable ref variables cannot be assigned read-only l-values. Readonly ref
variables can be assigned either read-only or writeable l-values.
The result of the ref-assignment expression is itself an "l-value" and the
resulting storage location is read-only if and only if the left-hand side of
the assignment is a read-only ref variable.
The storage location for the right-hand side must be definitely assigned
before it can be used in a ref-assignment expression. In addition, the
storage location referenced by an `out` parameter must be definitely assigned
before the `out` parameter is ref-reassigned to a new reference.
The lifetime for a `ref` local or parameter is fixed on declaration and
cannot be reassigned with ref-reassignment. The lifetime requirements for the
right-hand expression are the same as for the right-hand expression in a
variable assignment, identical to the lifetime for Span<T> assignments.
|
Ref Local and Parameter Reassignment
====================================
In C# 7.2, `ref` locals and parameters cannot be assigned new references,
only assigned values which reassign the underlying storage to the given value.
C# 7.3 introduces a new type of expression, a ref-assignment expression.
The syntax is as follows
```
ref_assignment
: identifier '=' 'ref' expression
```
The identifier on the left-hand side of a *ref_assignment* must be a `ref` or
`ref readonly` local variable, or an `in`, `ref`, or `out` parameter. Ref
assignments allow ref local variables or parameters, which represent
references to storage locations, to be assigned different references. This does
not include the `this` reference, even in structs.
The expression on the right-hand side must have a storage location, i.e. it must
be an "l-value." This l-value must be "ref-compatible" with the variable being
ref-assigned, where ref-compatible means:
* The type of left-hand side and the type of the right-hand side must have an
identity conversion between them.
* Writeable ref variables cannot be assigned read-only l-values. Readonly ref
variables can be assigned either read-only or writeable l-values.
The result of the ref-assignment expression is itself an "l-value" and the
resulting storage location is read-only if and only if the left-hand side of
the assignment is a read-only ref variable.
The storage location for the right-hand side must be definitely assigned
before it can be used in a ref-assignment expression. In addition, the
storage location referenced by an `out` parameter must be definitely assigned
before the `out` parameter is ref-reassigned to a new reference.
The lifetime for a `ref` local or parameter is fixed on declaration and
cannot be reassigned with ref-reassignment. The lifetime requirements for the
right-hand expression are the same as for the right-hand expression in a
variable assignment, identical to the lifetime for Span<T> assignments.
| 1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/sdk.md | Moving dotnet/roslyn to the new SDK
=============
# Overview
This document tracks our progress in moving Roslyn to the new SDK and project system. The goal of
this initial push is explicitly to remove the use of project.json from our code base. In doing
many of our projects will move to target the new SDK, but not all. Once this change is merged
we will do further cleanup to move everything to the new SDK.
The projects in our repo that need to be converted break down into the following categories:
- PCL: This will be converted to the new SDK and Project System
- Desktop 4.6: Package consumption will change to PackageReference
- Desktop 2.0: Package consumption will change to PackageReference
The conversion of our projects is being almost entirely automated with the [ConvertPackageRef Tool](https://github.com/jaredpar/ConvertPackageRef).
This automation is always checked in as a single commit titled "Generated code". It is frequently
replaced via a rebase as the tool improves.
# Branch State
All deliberately disabled features are marked with the comment "DO NOT MERGE". These entries will
be removed + fixed before merging
## Working
- Developer work flow: Restore.cmd, Build.cmd, Test.cmd
- Editing in Visual Studio
## Jenkins Legs
This set of Jenkins legs is considered functional and must pass on every merge:
- Unit tests debug / release on x86 / amd64
- Build correctness
- Microbuild
- CoreClr
- Linux
- Integration Tests
## Big Items
These are the big items that are broken and need some wokr
- RepoUtil: needs to understand PackageReference and can be massively simplified now
- Delete the DeployCompilerGeneratorToolsRuntime project. Not neeeded anymor
| Moving dotnet/roslyn to the new SDK
=============
# Overview
This document tracks our progress in moving Roslyn to the new SDK and project system. The goal of
this initial push is explicitly to remove the use of project.json from our code base. In doing
many of our projects will move to target the new SDK, but not all. Once this change is merged
we will do further cleanup to move everything to the new SDK.
The projects in our repo that need to be converted break down into the following categories:
- PCL: This will be converted to the new SDK and Project System
- Desktop 4.6: Package consumption will change to PackageReference
- Desktop 2.0: Package consumption will change to PackageReference
The conversion of our projects is being almost entirely automated with the [ConvertPackageRef Tool](https://github.com/jaredpar/ConvertPackageRef).
This automation is always checked in as a single commit titled "Generated code". It is frequently
replaced via a rebase as the tool improves.
# Branch State
All deliberately disabled features are marked with the comment "DO NOT MERGE". These entries will
be removed + fixed before merging
## Working
- Developer work flow: Restore.cmd, Build.cmd, Test.cmd
- Editing in Visual Studio
## Jenkins Legs
This set of Jenkins legs is considered functional and must pass on every merge:
- Unit tests debug / release on x86 / amd64
- Build correctness
- Microbuild
- CoreClr
- Linux
- Integration Tests
## Big Items
These are the big items that are broken and need some work
- RepoUtil: needs to understand PackageReference and can be massively simplified now
- Delete the DeployCompilerGeneratorToolsRuntime project. Not needed anymore
| 1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/wiki/Manual-Testing.md | # Purpose of this document
This document is meant to be a comprehensive list of Roslyn features for use in several kinds of testing.
- [**Routine Product Testing**](#routineproducttesting)
- [**Release Testing**](#releasetesting)
- [**New Language Feature Testing**](#newlanguagefeaturetesting)
## <a name="routineproducttesting">Routine Product Testing</a>
- Primarily focused on features marked with a :mag:
## <a name="releasetesting">Release Testing</a>
- Test all product features in all languages
## <a name="newlanguagefeaturetesting">New Language Feature Testing</a>
- Test phases
- **Merge Signoff**: Can the language feature be merged?
- Critical IDE features in the areas of **Typing**, **Navigating**, and **Viewing** must function as expected. Any non-trivial issues in these areas block language feature merging.
- These are marked with a :fast_forward:.
- All product features have been considered/tested are free of crashes, asserts, and hangs.
-All issues discovered (even non-crash/non-blocking) must be filed and linked here.
- _All feature descriptions and testing suggestions are merely examples. Each language feature should be carefully considered independently against each IDE feature to find interesting intersections_
- **Feature Signoff**: Per-feature signoff with links to non-blocking issues.
- **Feature Suggestions**: What can we add to the product to make the new language feature delightful to use?
- Testing approaches
- Read the **feature specification** and related conversations
- Think about how the new language feature **interacts with each product feature**
- Are new keywords visualized appropriately?
- Do refactorings and fixes produce correct code utilizing the new language feature?
- How do IDE error recovery scenarios work?
- Do things work well across languages?
- How is perf on large/medium/small solutions? Are features properly cancellable?
- Etc.
- **Brainstorm ideas** for new features to enhance the language feature
- Should existing code be refactored to some new pattern?
- Should users be able to easily switch between two equivalent forms?
- Do we need to make the flow of this feature easier to visualize?
- Etc.
# Testing tags
- :mag: = Scenarios that are regularly tested against internal builds
- :fast_forward: = Scenarios that must work as expected before new language features are merged
When doing a test pass, copy this page and consider using these status indicators:
- :white_check_mark: = Tested & Approved (possibly with linked bugs)
- :x: = Merge blocking
- :construction: = Non-blocking bugs
- :ok: = Issue has been fixed
- :free: = No expected impact
- :question: = Open question
<a name="testfootnote1"><sup>1</sup></a> Feature updated by compiler team, with appropriate unit tests.
<a name="testfootnote2"><sup>2</sup></a> Feature requires more complete testing by IDE team.
# Product Features
### Core Scenarios in Editing, Navigating, and Viewing
| Category | Feature/Description | C# Signoff/Notes | VB Signoff/Notes | F# Signoff/Notes |
| --- | --- | --- | --- | --- |
| **Enable/Disable** | :fast_forward: **Feature Flags** <br />To completely enables/disable new compiler features in the compiler & IDE | | | N/A |
| **Typing** | :fast_forward: **General Typing**<br />- Type and paste new constructs<br />- Nothing interferes with verbatim typing | | | |
| | :mag: :fast_forward: **Completion**<br />- Typing new keyword/construct names<br />- Dotting off of new constructs<br />- Matching part of the identifier is highlighted (including word prefix matches) [Visual Studio 2015 Update 1]<br />- Target type preselection [Visual Studio 2017]<br />IntelliSense filtering [Visual Studio 2017] | | | |
| | :fast_forward: **Formatting** <br />- Spacing in and around new constructs<br />- Spacing options<br />- Format Document command<br /> `Tools > Options` settings should be respected | | | |
| | :fast_forward: **Automatic Brace Completion** (*C# only*) <br />- Auto-insert close brace<br />- Shift+Enter commit of IntelliSense and any pending brace completion sessions (Currently C# only: https://github.com/dotnet/roslyn/issues/18065) | | | N/A |
| | :fast_forward: **Indentation** <br />- Typing `Enter` in an unfinished statement indents the next line | | | |
| **Navigating** | :mag: :fast_forward: **Go To Definition** <br />- F12 from callsites to definition<br />- Ctrl+click [Visual Studio 2017 version 15.4] | | | |
| | :fast_forward: **Go To Implementation** <br />- Ctrl+F12 to jump from virtual members to their implementations<br />- Jump from inheritable types to their implementations | | | N/A |
| | :mag: :fast_forward: **Find All References** <br />- Lists references to a symbol in "Find Symbol Results" window<br />- Shows results in hierarchy grouped by definition [Visual Studio 2015]<br />- Results should be groupable/filterable/classified appropriately [Visual Studio 2017] <br />- Find All References on literals [Visual Studio 2017 version 15.3] | | | |
| **Viewing** | :mag: :fast_forward: **Colorization** <br />- Keywords, literals, and identifiers colored appropriately in code<br />- Colors should theme appropriately<br />- The "Blue Theme (Additional Contrast)" should have sufficiently dark colors | | | |
| | :fast_forward: **Error Squiggles** <br />- Squiggles appear as expected on reasonable spans | | | |
### Code Transformations
| Category | Feature/Description | C# Signoff/Notes | VB Signoff/Notes | F# Signoff/Notes |
| --- | --- | --- | --- | --- |
| **Refactoring with UI** | :mag: **Inline Rename (with UI)**<br />- Dashboard shows correct information<br />- Highlighted spans are updated appropriately<br />- Rename operation updates the correct set of symbols | | | |
| | :mag: **Change Signature (with UI)**<br />- Updates all direct & cascaded definitions/callsites<br />- Shows appropriate signature & parameter previews in UI<br />- Reorder and Remove in the same session [Visual Studio 2015] | | | N/A |
| | :mag: **Extract Interface (with UI)**<br />- Generated Interface has expected shape<br />- UI shows appropriate method previews | | | N/A |
| | **Generate Type (with UI)**<br />- Dialog gives all valid options<br /> | | | N/A |
| | **Generate Overrides** [Visual Studio 2017 version 15.3] | | | N/A |
| **Refactorings** | **Rename Tracking**<br />- Tracking span tracks & dismisses as expected<br />- Invokable from references [Visual Studio 2015] | | | N/A |
| | :mag: **Extract Method**<br />- Extracted method has the expected signature<br />- All arguments/return values handled correctly<br />- Extracted code block is reasonable<br />- Automatically starts Inline Rename | | | N/A |
| | **Introduce Variable**<br />- Introduced variable has the expected signature and initializer expression<br />- "Introduce for All" correctly finds dupes | | | N/A |
| | **Inline Temporary Variable**<br />- Inlined values are appropriately expanded/reduced | | | N/A |
| | **Organize Usings**<br />- Honors "Place 'System' namespace first" option | | | N/A |
| | **Convert `Get*` Methods to Properties**<br />*Add Description* | | | N/A |
| | :mag: **Encapsulate Field**<br />- Select a field and convert it to a property backed by the field<br />- Try selecting multiple fields at once | | | N/A |
| | **Modifier Ordering** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Convert `ReferenceEquals` to `is null`** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Add Missing Modifiers** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Convert Lambda to Local Function** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Move Declaration Near Reference** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Introduce Pattern Matching** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Simplify Inferred Tuple Names** [Visual Studio 2017 version 15.5] | _Requires C# 7.1 or greater_ | | N/A |
| | **Convert keyword and symbol references to doc comment tags** [Visual Studio 2017 version 15.5] | | | N/A |
| **Fixes** | **Add Using**<br />- Triggers on appropriate constructs<br />- Including NuGet references<br />- Including Referenced Assemblies<br />- Includes spelling fixes | | | |
| | **Generate Local**<br />- Select an expression and introduce a local variable to represent it<br />- This should start an Inline Rename session | | | N/A |
| | **Generate Field**<br />- Select an expression and introduce a field to represent it<br />- This should start an Inline Rename session | | | N/A |
| | **Generate Method/Constructor**<br />- Call a nonexistent method or constructor to generate it from its usage<br />- Generated method has the expected signature and accessibility<br />- Add parameter to existing constructor from callsite [Visual Studio 2017 version 15.3] | | | N/A |
| | **Generate Constructor from members**<br />- Select fields/properties to generate a constructor accepting corresponding arguments<br />- Generated constructor has the expected signature and accessibility | | | N/A |
| | **Implement Interface**<br />- Only missing methods added<br />- All added methods have the expected signature and accessibility | | | N/A |
| | **Implement IDisposable**<br />- Implement IDisposable and you should see a large block of code properly implementing that particular interface | | | N/A |
| | **Implement Abstract Class**<br />- Inherit from an abstract class, and you should be able to auto-generate all of the missing members | | | N/A |
| | **Remove Unused Variables** [Visual Studio 2017 version 15.3]| | | N/A |
| | **Remove Unused Usings** | | | |
| | **Sort Usings** | | | N/A |
| | **Convert Get Methods to Properties**<br />- Name a method `GetStuff` and convert it to a property called `Stuff` | | | N/A |
| | **Make Method Async/Sync**<br />- Add an `await` to a synchronous method, you should be offered to add the async keyword<br />- Remove all `await` keywords from an async method, you should be offered to remove the async keyword | | | N/A |
| | **Use Object Initializer Over Property Assignment**<br />- Create a new instance of a type and then assign each of its properties on subsequent lines<br />- You should be offered to convert that to an object initializer | | | N/A |
| | **Insert Digit Separators** [Visual Studio 2017 version 15.3] | | | N/A |
| **Code Gen** | :mag: **Snippets**<br />- Tab completion, presence in completion list<br />- Insertion via Snippet Picker UI (Ctrl + K, Ctrl + X) or (Ctrl + K, Ctrl + S)<br />- (VB) Snippet Picker UI via `?<Tab>`<br />- (VB) Special snippet completion list (`p?<esc><tab>`) | | | N/A |
| | **Event Hookup on Tab** (*C# only*)<br />- Type "+=" after an event name and QuickInfo shows<br />- Invoking should pick good name & launch Inline Rename | | N/A | N/A |
| | **End Construct Generation** (*VB only*)<br />- Type `Sub Test()` and hit enter, the `End Sub` should be generated automatically | N/A | | N/A |
| | **Automatic End Construct Update** (*VB only*)<br />- Type `Sub Test()` and `End Sub`, changing `Sub` to `Function` in either one should update the other | N/A | | N/A |
| | **Spell checking**<br />- Type a name that's close to a variable name but off by a character or two<br />- Lightbulb should have option to fix up the spelling<br />- Includes type names that will require a using | | | N/A |
| | **Move type to file**<br />- Lightbulb to move type to another file when the type name doesn't match the filename<br />- Option to change the file name if the type doesn't match the file name | | | N/A |
| | **Convert between properties and Get methods** <br />- Offers to change a method named `GetStuff` to a property named `Stuff` | | | N/A |
| | **Convert auto property to full property** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Add missing cases**<br />Use a `switch` on a strict subset of an Enum's members<br />- It should offer to generate the rest of the cases | | | N/A |
| | **Add null checks for parameters** [Visual Studio 2017 version 15.3] | | | N/A |
| | **Change base for numeric literals** [Visual Studio 2017 version 15.3] | | | N/A |
| | **Convert if to switch** [Visual Studio 2017 version 15.3] | | | N/A |
| | **Resolve git merge conflicts** [Visual Studio 2017 version 15.3] | | | N/A |
| | **Add argument name** [Visual Studio 2017 version 15.3 | | | N/A |
| | **Fade and remove unreachable code** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Add missing file banner** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Deconstruct tuple declaration** [Visual Studio 2017 version 15.4] | | | N/A |
### IDE Features
| Category | Feature/Description | C# Signoff/Notes | VB Signoff/Notes | F# Signoff/Notes |
| --- | --- | --- | --- | --- |
| **General** | **Signature Help**<br />- Overloads shown with appropriate, colorized signature | | | |
| | **Quick Info**<br />- Hover on identifiers<br />- On completion list items | | | |
| | :mag: **Outlining**<br />- Make sure outlining is enabled under options<br />- Define a method and expect to see a collapsible region around the method definition<br />- Make sure collapse and expand work | | | |
| | **Brace Matching** (*C# only*)<br />- Highlights matching brace token, if caret is on an open or close brace.<br />- Hovering on a close brace shows the code around the open brace | | N/A | N/A |
| | **Highlight References**<br />- Ensure "Highlight references to symbol under cursor" is enabled in options<br />- If caret is on an identifier, all references to that identifier in the active document should be highlighted<br />- We also show related keywords, so placing the caret on a return should show the other returns, if should show elses, try shows catches and finallys, etc.<br />- Should be able to navigate between highlighted references with Ctrl+Shift+Up/Down | | | |
| | :mag: **Peek**<br />Press Alt + F12 after placing the cursor on a predefined Type or predefined member and expect to see to a temporary window showing the appropriate definition | | | |
| | :mag: **Navigation Bars**<br />- Open some existing source files, make sure you can navigate around the file choosing classes or methods.<br />- Switch between project contexts<br />- In VB, the NavBar can do code generation for events and for New/Finalize methods | | | |
| | **Metadata As Source**<br />- Press F12 on a predefined type and expect the cursor to move the predefined type definition inside a Metadata-As-Source Generated document.<br />- Expect to see the xml doc comments collapsed above the method. | | | N/A |
| | **Navigate to Decompiled Source** [Visual Studio 2017 version 15.6 Preview 2]<br />- Set the option at `Tools -> Options -> Text Editor -> C# -> Advanced -> Enable navigation to decompiled sources (experimental)` <br />- F12 on a type defined in metadata<br />- You should see decompiled method bodies, not just declarations | | | N/A |
| | :mag: **Navigate To**<br />- Place caret on a user defined Type reference and press "ctrl + ,"<br />- This should list the User Defined Type in the drop down on the Upper Right corner of the editor and selecting this item will move the cursor to the User Reference Definition<br />- Filters per kind of symbol [Visual Studio 2017]<br />- Results should be sorted as follows: [Visual Studio 2017 version 15.6 Preview 4]<br /><details><summary>Expand for details</summary>TODO</details> | | | |
| | **Go to Next/Previous Method**<br />- `Edit.NextMethod` and `Edit.PreviousMethod` should work<br />- You may need to set up keyboard bindings for these commands under `Tools > Options > Environment > Keyboard` | | | N/A |
| | **Solution Explorer Pivots**<br />- Define a Type and some members in a sample Document.<br />- Expand the Document listed in the Solution Explorer window and expect to see the Type and Members defined<br />- Right-click types and try Base Types / Derived Types / Is Used By / Implements<br /> - Right-click methods and try Calls / Is Called By / Is Used By / Implements | | | N/A |
| | **Call Hierarchy**<br />- Place the caret over a method, right click & select View Hierarchy<br />- This should open the "Call Hierarchy window" listing the methods that call the original method and also the callsites within each calling method. | | | N/A |
| | :mag: **Code Lens**<br />- Make sure Code Lens is enabled from the options. Look for an adornment on top of each method declaration with lists the number of references for that method, last time someone modified the method, who modified the method and other information | | | N/A |
| | **Project System**<br />- Open/close a project<br />- Add/remove references<br />- Unload/reload projects<br />- Source Control integration (adding references checks out projects, etc.) | | | |
| | **Debugger IntelliSense**<br />- Hit a breakpoint (or step) and verify that there's IntelliSense in the Immediate Window (C#, VB)<br />- Type an expression, and hit enter. Verify it's evaluated. Type another expression. IntelliSense should still work.<br />- (VB) there should be IntelliSense if you type "?" followed by an expression (eg, the text of the line in the window is "?foo")<br />- Hit a breakpoint (or step) and verify that there's IntelliSense in the Watch Window<br />- Hit a breakpoint (or step) and verify that there's IntelliSense in the Quick Watch Window<br /> - Verify intellisense in the Conditional Breakpoint view<br />- Verify each of the above scenarios after hitting f5 and hitting another breakpoint, and after stepping | | | |
| | **Breakpoint Spans**<br />- The span highlighted when a breakpoint is set should be logical | | | |
| | **Code Model / Class Designer**<br />- Right click a file in Solution Explorer & choose View Class Diagram.<br />- This shows the "Class Details" window where you can add/remove members, change their type/accessibility/name, parameter info, etc. | | | N/A |
| | **Object Browser / Class View**<br />- Open object browser and classview and verify that project contents are represented live.<br />- Should be able to invoke find all references, navigate to the definition, and do searches. | | | N/A |
| | **Lightbulb**<br />- Should work with `Ctrl+.` and the right-click menu<br />- Should include a diff view<br />- Should include options to fix all in Document/Project/Solution, and to Preview Changes<br />Varying icons for lightbulb items [Visual Studio 2017 version 15.4] | | | |
| | **Line Separators**<br />- Turn the option on under `Tools > Options`<br />- Ensure there's a line between methods. | | | N/A |
| | **Indent Guides**<br />- Vertical dotted lines appear between braces for declaration-level things<br />- Hovering on the line shows context | | | |
| **Code Style** | **Naming Rules** | | | N/A |
| | **Use this./me.** | | | N/A |
| | **Use predefined type** | | | N/A |
| | **Prefer object/collection initializer** | | | N/A |
| | **Prefer explicit tuple name** | | | N/A |
| | **Prefer coalesce expression over null check** | | | N/A |
| | **Prefer null propagation over null check** | | | N/A |
| | **var preferences** (*C# only*) | | N/A | N/A |
| | **Prefer braces** (*C# only*) | | N/A | N/A |
| | **Prefer pattern matching over is/as checks** (*C# only*) | | N/A | N/A |
| | **Use expression body** (*C# only*) | | N/A | N/A |
| | **Prefer inlined variable declaration** (*C# only*) | | N/A | N/A |
| | **Prefer throw expression** (*C# only*) | | N/A | N/A |
| | **Prefer conditional delegate call** (*C# only*) | | N/A | N/A |
### Project System & External Integration
(Any changes to the runtime will require much more testing in this category)
*All feature descriptions and testing suggestions are merely examples. Each language feature should be carefully considered independently against each IDE feature to find interesting intersections*
| Category | Integration | Signoff/Notes |
| --- | --- | --- |
| **Projection Buffers** | **Razor** (web)<br />- Verify expression and block contexts<br />- Test on projection boundaries<br /> - Emphasis on rename and formatting | |
| | **Venus**<br />- Verify expression and block contexts<br />- Test on projection boundaries<br /> - Emphasis on rename and formatting | |
| **Designers** | **WPF**<br />- Event generation from designer to code<br />- Designer consumption of new types of members<br />- Cross language features (Go to definition, find references, rename) | |
| | **WinForms**<br />- Create a project, add some controls to the form<br />- Verify that simple changes to InitializeComponent round-trip to the designer.<br />- Verify that double clicking a control generates or navigates to an event handler for its default event | |
| **Project System Interactions** | **Linked Files (all flavors)**<br />- Regular linked files<br />- Shared Projects<br />- Multitargeted .NET Core Apps | |
## Interaction with other new language features in the IDE
Verify IDE handling of the new language feature in conjunction with other new/unreleased language features
| Feature | C# Signoff/Notes | VB Signoff/Notes | F# Signoff/Notes |
| --- | --- | --- | --- |
| **\<New Language Feature 1\>** | | | |
| **\<New Language Feature 2\>** | | | |
## <a name="featuresuggestions">New Feature Suggestions</a>
What refactorings, fixes, code transformations, or other in-editor experiences would enhance this language feature?
| Feature Name | Description |
| --- | --- |
| ? | ? |
| ? | ? |
| # Purpose of this document
This document is meant to be a comprehensive list of Roslyn features for use in several kinds of testing.
- [**Routine Product Testing**](#routineproducttesting)
- [**Release Testing**](#releasetesting)
- [**New Language Feature Testing**](#newlanguagefeaturetesting)
## <a name="routineproducttesting">Routine Product Testing</a>
- Primarily focused on features marked with a :mag:
## <a name="releasetesting">Release Testing</a>
- Test all product features in all languages
## <a name="newlanguagefeaturetesting">New Language Feature Testing</a>
- Test phases
- **Merge Signoff**: Can the language feature be merged?
- Critical IDE features in the areas of **Typing**, **Navigating**, and **Viewing** must function as expected. Any non-trivial issues in these areas block language feature merging.
- These are marked with a :fast_forward:.
- All product features have been considered/tested are free of crashes, asserts, and hangs.
-All issues discovered (even non-crash/non-blocking) must be filed and linked here.
- _All feature descriptions and testing suggestions are merely examples. Each language feature should be carefully considered independently against each IDE feature to find interesting intersections_
- **Feature Signoff**: Per-feature signoff with links to non-blocking issues.
- **Feature Suggestions**: What can we add to the product to make the new language feature delightful to use?
- Testing approaches
- Read the **feature specification** and related conversations
- Think about how the new language feature **interacts with each product feature**
- Are new keywords visualized appropriately?
- Do refactorings and fixes produce correct code utilizing the new language feature?
- How do IDE error recovery scenarios work?
- Do things work well across languages?
- How is perf on large/medium/small solutions? Are features properly cancellable?
- Etc.
- **Brainstorm ideas** for new features to enhance the language feature
- Should existing code be refactored to some new pattern?
- Should users be able to easily switch between two equivalent forms?
- Do we need to make the flow of this feature easier to visualize?
- Etc.
# Testing tags
- :mag: = Scenarios that are regularly tested against internal builds
- :fast_forward: = Scenarios that must work as expected before new language features are merged
When doing a test pass, copy this page and consider using these status indicators:
- :white_check_mark: = Tested & Approved (possibly with linked bugs)
- :x: = Merge blocking
- :construction: = Non-blocking bugs
- :ok: = Issue has been fixed
- :free: = No expected impact
- :question: = Open question
<a name="testfootnote1"><sup>1</sup></a> Feature updated by compiler team, with appropriate unit tests.
<a name="testfootnote2"><sup>2</sup></a> Feature requires more complete testing by IDE team.
# Product Features
### Core Scenarios in Editing, Navigating, and Viewing
| Category | Feature/Description | C# Signoff/Notes | VB Signoff/Notes | F# Signoff/Notes |
| --- | --- | --- | --- | --- |
| **Enable/Disable** | :fast_forward: **Feature Flags** <br />To completely enables/disable new compiler features in the compiler & IDE | | | N/A |
| **Typing** | :fast_forward: **General Typing**<br />- Type and paste new constructs<br />- Nothing interferes with verbatim typing | | | |
| | :mag: :fast_forward: **Completion**<br />- Typing new keyword/construct names<br />- Dotting off of new constructs<br />- Matching part of the identifier is highlighted (including word prefix matches) [Visual Studio 2015 Update 1]<br />- Target type preselection [Visual Studio 2017]<br />IntelliSense filtering [Visual Studio 2017] | | | |
| | :fast_forward: **Formatting** <br />- Spacing in and around new constructs<br />- Spacing options<br />- Format Document command<br /> `Tools > Options` settings should be respected | | | |
| | :fast_forward: **Automatic Brace Completion** (*C# only*) <br />- Auto-insert close brace<br />- Shift+Enter commit of IntelliSense and any pending brace completion sessions (Currently C# only: https://github.com/dotnet/roslyn/issues/18065) | | | N/A |
| | :fast_forward: **Indentation** <br />- Typing `Enter` in an unfinished statement indents the next line | | | |
| **Navigating** | :mag: :fast_forward: **Go To Definition** <br />- F12 from callsites to definition<br />- Ctrl+click [Visual Studio 2017 version 15.4] | | | |
| | :fast_forward: **Go To Implementation** <br />- Ctrl+F12 to jump from virtual members to their implementations<br />- Jump from inheritable types to their implementations | | | N/A |
| | :mag: :fast_forward: **Find All References** <br />- Lists references to a symbol in "Find Symbol Results" window<br />- Shows results in hierarchy grouped by definition [Visual Studio 2015]<br />- Results should be groupable/filterable/classified appropriately [Visual Studio 2017] <br />- Find All References on literals [Visual Studio 2017 version 15.3] | | | |
| **Viewing** | :mag: :fast_forward: **Colorization** <br />- Keywords, literals, and identifiers colored appropriately in code<br />- Colors should theme appropriately<br />- The "Blue Theme (Additional Contrast)" should have sufficiently dark colors | | | |
| | :fast_forward: **Error Squiggles** <br />- Squiggles appear as expected on reasonable spans | | | |
### Code Transformations
| Category | Feature/Description | C# Signoff/Notes | VB Signoff/Notes | F# Signoff/Notes |
| --- | --- | --- | --- | --- |
| **Refactoring with UI** | :mag: **Inline Rename (with UI)**<br />- Dashboard shows correct information<br />- Highlighted spans are updated appropriately<br />- Rename operation updates the correct set of symbols | | | |
| | :mag: **Change Signature (with UI)**<br />- Updates all direct & cascaded definitions/callsites<br />- Shows appropriate signature & parameter previews in UI<br />- Reorder and Remove in the same session [Visual Studio 2015] | | | N/A |
| | :mag: **Extract Interface (with UI)**<br />- Generated Interface has expected shape<br />- UI shows appropriate method previews | | | N/A |
| | **Generate Type (with UI)**<br />- Dialog gives all valid options<br /> | | | N/A |
| | **Generate Overrides** [Visual Studio 2017 version 15.3] | | | N/A |
| **Refactorings** | **Rename Tracking**<br />- Tracking span tracks & dismisses as expected<br />- Invokable from references [Visual Studio 2015] | | | N/A |
| | :mag: **Extract Method**<br />- Extracted method has the expected signature<br />- All arguments/return values handled correctly<br />- Extracted code block is reasonable<br />- Automatically starts Inline Rename | | | N/A |
| | **Introduce Variable**<br />- Introduced variable has the expected signature and initializer expression<br />- "Introduce for All" correctly finds dupes | | | N/A |
| | **Inline Temporary Variable**<br />- Inlined values are appropriately expanded/reduced | | | N/A |
| | **Organize Usings**<br />- Honors "Place 'System' namespace first" option | | | N/A |
| | **Convert `Get*` Methods to Properties**<br />*Add Description* | | | N/A |
| | :mag: **Encapsulate Field**<br />- Select a field and convert it to a property backed by the field<br />- Try selecting multiple fields at once | | | N/A |
| | **Modifier Ordering** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Convert `ReferenceEquals` to `is null`** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Add Missing Modifiers** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Convert Lambda to Local Function** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Move Declaration Near Reference** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Introduce Pattern Matching** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Simplify Inferred Tuple Names** [Visual Studio 2017 version 15.5] | _Requires C# 7.1 or greater_ | | N/A |
| | **Convert keyword and symbol references to doc comment tags** [Visual Studio 2017 version 15.5] | | | N/A |
| **Fixes** | **Add Using**<br />- Triggers on appropriate constructs<br />- Including NuGet references<br />- Including Referenced Assemblies<br />- Includes spelling fixes | | | |
| | **Generate Local**<br />- Select an expression and introduce a local variable to represent it<br />- This should start an Inline Rename session | | | N/A |
| | **Generate Field**<br />- Select an expression and introduce a field to represent it<br />- This should start an Inline Rename session | | | N/A |
| | **Generate Method/Constructor**<br />- Call a nonexistent method or constructor to generate it from its usage<br />- Generated method has the expected signature and accessibility<br />- Add parameter to existing constructor from callsite [Visual Studio 2017 version 15.3] | | | N/A |
| | **Generate Constructor from members**<br />- Select fields/properties to generate a constructor accepting corresponding arguments<br />- Generated constructor has the expected signature and accessibility | | | N/A |
| | **Implement Interface**<br />- Only missing methods added<br />- All added methods have the expected signature and accessibility | | | N/A |
| | **Implement IDisposable**<br />- Implement IDisposable and you should see a large block of code properly implementing that particular interface | | | N/A |
| | **Implement Abstract Class**<br />- Inherit from an abstract class, and you should be able to auto-generate all of the missing members | | | N/A |
| | **Remove Unused Variables** [Visual Studio 2017 version 15.3]| | | N/A |
| | **Remove Unused Usings** | | | |
| | **Sort Usings** | | | N/A |
| | **Convert Get Methods to Properties**<br />- Name a method `GetStuff` and convert it to a property called `Stuff` | | | N/A |
| | **Make Method Async/Sync**<br />- Add an `await` to a synchronous method, you should be offered to add the async keyword<br />- Remove all `await` keywords from an async method, you should be offered to remove the async keyword | | | N/A |
| | **Use Object Initializer Over Property Assignment**<br />- Create a new instance of a type and then assign each of its properties on subsequent lines<br />- You should be offered to convert that to an object initializer | | | N/A |
| | **Insert Digit Separators** [Visual Studio 2017 version 15.3] | | | N/A |
| **Code Gen** | :mag: **Snippets**<br />- Tab completion, presence in completion list<br />- Insertion via Snippet Picker UI (Ctrl + K, Ctrl + X) or (Ctrl + K, Ctrl + S)<br />- (VB) Snippet Picker UI via `?<Tab>`<br />- (VB) Special snippet completion list (`p?<esc><tab>`) | | | N/A |
| | **Event Hookup on Tab** (*C# only*)<br />- Type "+=" after an event name and QuickInfo shows<br />- Invoking should pick good name & launch Inline Rename | | N/A | N/A |
| | **End Construct Generation** (*VB only*)<br />- Type `Sub Test()` and hit enter, the `End Sub` should be generated automatically | N/A | | N/A |
| | **Automatic End Construct Update** (*VB only*)<br />- Type `Sub Test()` and `End Sub`, changing `Sub` to `Function` in either one should update the other | N/A | | N/A |
| | **Spell checking**<br />- Type a name that's close to a variable name but off by a character or two<br />- Lightbulb should have option to fix up the spelling<br />- Includes type names that will require a using | | | N/A |
| | **Move type to file**<br />- Lightbulb to move type to another file when the type name doesn't match the filename<br />- Option to change the file name if the type doesn't match the file name | | | N/A |
| | **Convert between properties and Get methods** <br />- Offers to change a method named `GetStuff` to a property named `Stuff` | | | N/A |
| | **Convert auto property to full property** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Add missing cases**<br />Use a `switch` on a strict subset of an Enum's members<br />- It should offer to generate the rest of the cases | | | N/A |
| | **Add null checks for parameters** [Visual Studio 2017 version 15.3] | | | N/A |
| | **Change base for numeric literals** [Visual Studio 2017 version 15.3] | | | N/A |
| | **Convert if to switch** [Visual Studio 2017 version 15.3] | | | N/A |
| | **Resolve git merge conflicts** [Visual Studio 2017 version 15.3] | | | N/A |
| | **Add argument name** [Visual Studio 2017 version 15.3 | | | N/A |
| | **Fade and remove unreachable code** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Add missing file banner** [Visual Studio 2017 version 15.5] | | | N/A |
| | **Deconstruct tuple declaration** [Visual Studio 2017 version 15.4] | | | N/A |
### IDE Features
| Category | Feature/Description | C# Signoff/Notes | VB Signoff/Notes | F# Signoff/Notes |
| --- | --- | --- | --- | --- |
| **General** | **Signature Help**<br />- Overloads shown with appropriate, colorized signature | | | |
| | **Quick Info**<br />- Hover on identifiers<br />- On completion list items | | | |
| | :mag: **Outlining**<br />- Make sure outlining is enabled under options<br />- Define a method and expect to see a collapsible region around the method definition<br />- Make sure collapse and expand work | | | |
| | **Brace Matching** (*C# only*)<br />- Highlights matching brace token, if caret is on an open or close brace.<br />- Hovering on a close brace shows the code around the open brace | | N/A | N/A |
| | **Highlight References**<br />- Ensure "Highlight references to symbol under cursor" is enabled in options<br />- If caret is on an identifier, all references to that identifier in the active document should be highlighted<br />- We also show related keywords, so placing the caret on a return should show the other returns, if should show elses, try shows catches and finallys, etc.<br />- Should be able to navigate between highlighted references with Ctrl+Shift+Up/Down | | | |
| | :mag: **Peek**<br />Press Alt + F12 after placing the cursor on a predefined Type or predefined member and expect to see to a temporary window showing the appropriate definition | | | |
| | :mag: **Navigation Bars**<br />- Open some existing source files, make sure you can navigate around the file choosing classes or methods.<br />- Switch between project contexts<br />- In VB, the NavBar can do code generation for events and for New/Finalize methods | | | |
| | **Metadata As Source**<br />- Press F12 on a predefined type and expect the cursor to move the predefined type definition inside a Metadata-As-Source Generated document.<br />- Expect to see the xml doc comments collapsed above the method. | | | N/A |
| | **Navigate to Decompiled Source** [Visual Studio 2017 version 15.6 Preview 2]<br />- Set the option at `Tools -> Options -> Text Editor -> C# -> Advanced -> Enable navigation to decompiled sources (experimental)` <br />- F12 on a type defined in metadata<br />- You should see decompiled method bodies, not just declarations | | | N/A |
| | :mag: **Navigate To**<br />- Place caret on a user defined Type reference and press "ctrl + ,"<br />- This should list the User Defined Type in the drop down on the Upper Right corner of the editor and selecting this item will move the cursor to the User Reference Definition<br />- Filters per kind of symbol [Visual Studio 2017]<br />- Results should be sorted as follows: [Visual Studio 2017 version 15.6 Preview 4]<br /><details><summary>Expand for details</summary>TODO</details> | | | |
| | **Go to Next/Previous Method**<br />- `Edit.NextMethod` and `Edit.PreviousMethod` should work<br />- You may need to set up keyboard bindings for these commands under `Tools > Options > Environment > Keyboard` | | | N/A |
| | **Solution Explorer Pivots**<br />- Define a Type and some members in a sample Document.<br />- Expand the Document listed in the Solution Explorer window and expect to see the Type and Members defined<br />- Right-click types and try Base Types / Derived Types / Is Used By / Implements<br /> - Right-click methods and try Calls / Is Called By / Is Used By / Implements | | | N/A |
| | **Call Hierarchy**<br />- Place the caret over a method, right click & select View Hierarchy<br />- This should open the "Call Hierarchy window" listing the methods that call the original method and also the callsites within each calling method. | | | N/A |
| | :mag: **Code Lens**<br />- Make sure Code Lens is enabled from the options. Look for an adornment on top of each method declaration with lists the number of references for that method, last time someone modified the method, who modified the method and other information | | | N/A |
| | **Project System**<br />- Open/close a project<br />- Add/remove references<br />- Unload/reload projects<br />- Source Control integration (adding references checks out projects, etc.) | | | |
| | **Debugger IntelliSense**<br />- Hit a breakpoint (or step) and verify that there's IntelliSense in the Immediate Window (C#, VB)<br />- Type an expression, and hit enter. Verify it's evaluated. Type another expression. IntelliSense should still work.<br />- (VB) there should be IntelliSense if you type "?" followed by an expression (eg, the text of the line in the window is "?foo")<br />- Hit a breakpoint (or step) and verify that there's IntelliSense in the Watch Window<br />- Hit a breakpoint (or step) and verify that there's IntelliSense in the Quick Watch Window<br /> - Verify intellisense in the Conditional Breakpoint view<br />- Verify each of the above scenarios after hitting f5 and hitting another breakpoint, and after stepping | | | |
| | **Breakpoint Spans**<br />- The span highlighted when a breakpoint is set should be logical | | | |
| | **Code Model / Class Designer**<br />- Right click a file in Solution Explorer & choose View Class Diagram.<br />- This shows the "Class Details" window where you can add/remove members, change their type/accessibility/name, parameter info, etc. | | | N/A |
| | **Object Browser / Class View**<br />- Open object browser and classview and verify that project contents are represented live.<br />- Should be able to invoke find all references, navigate to the definition, and do searches. | | | N/A |
| | **Lightbulb**<br />- Should work with `Ctrl+.` and the right-click menu<br />- Should include a diff view<br />- Should include options to fix all in Document/Project/Solution, and to Preview Changes<br />Varying icons for lightbulb items [Visual Studio 2017 version 15.4] | | | |
| | **Line Separators**<br />- Turn the option on under `Tools > Options`<br />- Ensure there's a line between methods. | | | N/A |
| | **Indent Guides**<br />- Vertical dotted lines appear between braces for declaration-level things<br />- Hovering on the line shows context | | | |
| **Code Style** | **Naming Rules** | | | N/A |
| | **Use this./me.** | | | N/A |
| | **Use predefined type** | | | N/A |
| | **Prefer object/collection initializer** | | | N/A |
| | **Prefer explicit tuple name** | | | N/A |
| | **Prefer coalesce expression over null check** | | | N/A |
| | **Prefer null propagation over null check** | | | N/A |
| | **var preferences** (*C# only*) | | N/A | N/A |
| | **Prefer braces** (*C# only*) | | N/A | N/A |
| | **Prefer pattern matching over is/as checks** (*C# only*) | | N/A | N/A |
| | **Use expression body** (*C# only*) | | N/A | N/A |
| | **Prefer inlined variable declaration** (*C# only*) | | N/A | N/A |
| | **Prefer throw expression** (*C# only*) | | N/A | N/A |
| | **Prefer conditional delegate call** (*C# only*) | | N/A | N/A |
### Project System & External Integration
(Any changes to the runtime will require much more testing in this category)
*All feature descriptions and testing suggestions are merely examples. Each language feature should be carefully considered independently against each IDE feature to find interesting intersections*
| Category | Integration | Signoff/Notes |
| --- | --- | --- |
| **Projection Buffers** | **Razor** (web)<br />- Verify expression and block contexts<br />- Test on projection boundaries<br /> - Emphasis on rename and formatting | |
| | **Venus**<br />- Verify expression and block contexts<br />- Test on projection boundaries<br /> - Emphasis on rename and formatting | |
| **Designers** | **WPF**<br />- Event generation from designer to code<br />- Designer consumption of new types of members<br />- Cross language features (Go to definition, find references, rename) | |
| | **WinForms**<br />- Create a project, add some controls to the form<br />- Verify that simple changes to InitializeComponent round-trip to the designer.<br />- Verify that double clicking a control generates or navigates to an event handler for its default event | |
| **Project System Interactions** | **Linked Files (all flavors)**<br />- Regular linked files<br />- Shared Projects<br />- Multitargeted .NET Core Apps | |
## Interaction with other new language features in the IDE
Verify IDE handling of the new language feature in conjunction with other new/unreleased language features
| Feature | C# Signoff/Notes | VB Signoff/Notes | F# Signoff/Notes |
| --- | --- | --- | --- |
| **\<New Language Feature 1\>** | | | |
| **\<New Language Feature 2\>** | | | |
## <a name="featuresuggestions">New Feature Suggestions</a>
What refactorings, fixes, code transformations, or other in-editor experiences would enhance this language feature?
| Feature Name | Description |
| --- | --- |
| ? | ? |
| ? | ? |
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/Rule Set Format.md | Introduction
============
This document, in conjunction with the [Rule Set Schema](..//..//src//Compilers//Core//Portable//RuleSet//RuleSetSchema.xsd), describes the structure of .ruleset files used by the C# and Visual Basic compilers to turn diagnostic analyzers on and off and to control their severity.
This document only discusses the required and common parts of .ruleset files; for a full set, please see the schema file.
Sample
=====
The following demonstrates a small but complete example of a .ruleset file.
``` XML
<RuleSet Name="Project WizBang Rules"
ToolsVersion="12.0">
<Include Path="..\OtherRules.ruleset"
Action="Default" />
<Rules AnalyzerId="System.Runtime.Analyzers"
RuleNamespace="System.Runtime.Analyzers">
<Rule Id="CA1027" Action="Warning" />
<Rule Id="CA1309" Action="Error" />
<Rule Id="CA2217" Action="Warning" />
</Rules>
<Rules AnalyzerId="System.Runtime.InteropServices.Analyzers"
RuleNamespace="System.Runtime.InteropService.Analyzers">
<Rule Id="CA1401" Action="None" />
<Rule Id="CA2101" Action="Error" />
</Rules>
</RuleSet>
```
Passing Rule Sets to the Compiler
=================================
Command Line
------------
Rule set files can be passed to csc.exe and vbc.exe using the `/ruleset` switch, which takes an absolute or relative file path. For example:
```
vbc.exe /ruleset:ProjectRules.ruleset ...
vbc.exe /ruleset:..\..\..\SolutionRules.ruleset ...
vbc.exe /ruleset:D:\WizbangCorp\Development\CompanyRules.ruleset ...
```
MSBuild Projects
----------------
Within MSBuild project files the rule set can be specified via the `CodeAnalysisRuleSet` property. For example:
``` XML
<PropertyGroup>
<CodeAnalysisRuleSet>ProjectRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
```
Note that because the rule set is specified via a *property* rather than an *item*, IDEs like Visual Studio will not show the rule set as a file in your project by default. For this reason it is common to explicitly include the file as an item as well:
``` XML
<ItemGroup>
<None Include="ProjectRules.ruleset" />
</ItemGroup>
```
Elements
========
`RuleSet`
---------
The `RuleSet` is the root element of the file.
Attributes:
* Name (**required**): A short, descriptive name for the file.
* Description (**optional**): A longer description of the purpose of the rule set file.
* ToolsVersion (**required**): This attribute is required for backwards compatibility with other tools that use .ruleset files. In practice it is the version of Visual Studio that produced this .ruleset file. When in doubt, simply use "12.0".
Children: `Include`, `Rules`
`Include`
---------
Pulls in the settings from the specified rule set file. Settings in the current file override settings in the included file.
Parent: `RuleSet`
Attributes:
* Path (**required**): An absolute or relative path to another .ruleset file.
* Action (**required**): Specifies the effective action of the included rules. Must be one of the following values:
* Default - The rules use the actions specified in the included file.
* Error - The included rules are treated as though their action values were all "Error".
* Warning - The included rules are treated as though their actions values were all "Warning".
* Info - The included rules are treated as though their actions values were all "Info".
* Hidden - The included rules are treated as though their actions values were all "Hidden".
* None - The included rules are treated as though their actions values were all "None".
Children: None.
`Rules`
-------
Hold settings for rules from a single diagnostic analyzer.
Parent: `RuleSet`
Attributes:
* AnalyzerId (**required**): The name of the analyzer. In practice this is the simple name of the assembly containing the diagnostics.
* RuleNamespace (**required**): This attribute is required for backwards compatibility with other tools that use .ruleset files. In practice it is generally the same as the AnalyzerId.
Children: `Rule`
`Rule`
------
Specifies what action to take for a given diagnostic rule.
Parent: `Rules`
Attributes:
* Id (**required**): The ID of the diagnostic rule.
* Action (**required**): One of the following values:
* Error - Instances of this diagnostic are treated as compiler errors.
* Warning - Instances of this diagnostic are treated as compiler warnings.
* Info - Instances of this diagnostic are treated as compiler messages.
* Hidden - Instances of this diagnostic are hidden from the user.
* None - Turns off the diagnostic rule.
Children: None.
Notes:
Within a `Rules` element, a `Rule` with a given `Id` may only appear once. The C# and Visual Basic compilers impose a further constraint: if multiple `Rules` elements contain a `Rule` with the same `Id` they must all specify the same `Action` value.
The difference between the Hidden and None actions is subtle but important. When a diagnostic rule is set to Hidden instances of that rule are still created, but aren't displayed to the user by default. However, the host process can access these diagnostics and take some host-specific action. For example, Visual Studio uses a combination of Hidden diagnostics and a custom editor extension to "grey out" dead or unnecessary code in the editor. A diagnostic rule set to None, however, is effectively turned off. Instances of this diagnostic may not be produced at all; even if they are suppressed rather than being made available to the host.
| Introduction
============
This document, in conjunction with the [Rule Set Schema](..//..//src//Compilers//Core//Portable//RuleSet//RuleSetSchema.xsd), describes the structure of .ruleset files used by the C# and Visual Basic compilers to turn diagnostic analyzers on and off and to control their severity.
This document only discusses the required and common parts of .ruleset files; for a full set, please see the schema file.
Sample
=====
The following demonstrates a small but complete example of a .ruleset file.
``` XML
<RuleSet Name="Project WizBang Rules"
ToolsVersion="12.0">
<Include Path="..\OtherRules.ruleset"
Action="Default" />
<Rules AnalyzerId="System.Runtime.Analyzers"
RuleNamespace="System.Runtime.Analyzers">
<Rule Id="CA1027" Action="Warning" />
<Rule Id="CA1309" Action="Error" />
<Rule Id="CA2217" Action="Warning" />
</Rules>
<Rules AnalyzerId="System.Runtime.InteropServices.Analyzers"
RuleNamespace="System.Runtime.InteropService.Analyzers">
<Rule Id="CA1401" Action="None" />
<Rule Id="CA2101" Action="Error" />
</Rules>
</RuleSet>
```
Passing Rule Sets to the Compiler
=================================
Command Line
------------
Rule set files can be passed to csc.exe and vbc.exe using the `/ruleset` switch, which takes an absolute or relative file path. For example:
```
vbc.exe /ruleset:ProjectRules.ruleset ...
vbc.exe /ruleset:..\..\..\SolutionRules.ruleset ...
vbc.exe /ruleset:D:\WizbangCorp\Development\CompanyRules.ruleset ...
```
MSBuild Projects
----------------
Within MSBuild project files the rule set can be specified via the `CodeAnalysisRuleSet` property. For example:
``` XML
<PropertyGroup>
<CodeAnalysisRuleSet>ProjectRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
```
Note that because the rule set is specified via a *property* rather than an *item*, IDEs like Visual Studio will not show the rule set as a file in your project by default. For this reason it is common to explicitly include the file as an item as well:
``` XML
<ItemGroup>
<None Include="ProjectRules.ruleset" />
</ItemGroup>
```
Elements
========
`RuleSet`
---------
The `RuleSet` is the root element of the file.
Attributes:
* Name (**required**): A short, descriptive name for the file.
* Description (**optional**): A longer description of the purpose of the rule set file.
* ToolsVersion (**required**): This attribute is required for backwards compatibility with other tools that use .ruleset files. In practice it is the version of Visual Studio that produced this .ruleset file. When in doubt, simply use "12.0".
Children: `Include`, `Rules`
`Include`
---------
Pulls in the settings from the specified rule set file. Settings in the current file override settings in the included file.
Parent: `RuleSet`
Attributes:
* Path (**required**): An absolute or relative path to another .ruleset file.
* Action (**required**): Specifies the effective action of the included rules. Must be one of the following values:
* Default - The rules use the actions specified in the included file.
* Error - The included rules are treated as though their action values were all "Error".
* Warning - The included rules are treated as though their actions values were all "Warning".
* Info - The included rules are treated as though their actions values were all "Info".
* Hidden - The included rules are treated as though their actions values were all "Hidden".
* None - The included rules are treated as though their actions values were all "None".
Children: None.
`Rules`
-------
Hold settings for rules from a single diagnostic analyzer.
Parent: `RuleSet`
Attributes:
* AnalyzerId (**required**): The name of the analyzer. In practice this is the simple name of the assembly containing the diagnostics.
* RuleNamespace (**required**): This attribute is required for backwards compatibility with other tools that use .ruleset files. In practice it is generally the same as the AnalyzerId.
Children: `Rule`
`Rule`
------
Specifies what action to take for a given diagnostic rule.
Parent: `Rules`
Attributes:
* Id (**required**): The ID of the diagnostic rule.
* Action (**required**): One of the following values:
* Error - Instances of this diagnostic are treated as compiler errors.
* Warning - Instances of this diagnostic are treated as compiler warnings.
* Info - Instances of this diagnostic are treated as compiler messages.
* Hidden - Instances of this diagnostic are hidden from the user.
* None - Turns off the diagnostic rule.
Children: None.
Notes:
Within a `Rules` element, a `Rule` with a given `Id` may only appear once. The C# and Visual Basic compilers impose a further constraint: if multiple `Rules` elements contain a `Rule` with the same `Id` they must all specify the same `Action` value.
The difference between the Hidden and None actions is subtle but important. When a diagnostic rule is set to Hidden instances of that rule are still created, but aren't displayed to the user by default. However, the host process can access these diagnostics and take some host-specific action. For example, Visual Studio uses a combination of Hidden diagnostics and a custom editor extension to "grey out" dead or unnecessary code in the editor. A diagnostic rule set to None, however, is effectively turned off. Instances of this diagnostic may not be produced at all; even if they are suppressed rather than being made available to the host.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/skiplocalsinit.md |
# Feature design for SkipLocalsInit
The feature is to add a new well-known attribute to the compiler, System.Runtime.CompilerServices.SkipLocalsInit that causes method bodies nested "inside" the scope of the attribute to elide the ".locals init" CIL directive that causes the CLR to zero-init local variables and space reserved using the "localloc" instruction. "Nested inside the scope of the attribute" is a concept defined as follows:
1. When the attribute is applied to a module, all emitted methods inside that module, including generated methods, will skip local initialization.
2. When the attribute is applied to a type (including interfaces), all methods transitively inside that type, including generated methods, will skip local initialization. This includes nested types.
3. When the attribute is applied to a method, the method and all methods generated by the compiler which contain user-influenced code inside that method (e.g., local functions, lambdas, async methods) will skip local initialization.
For the above, generated methods will skip local initialization only if they have user code inside them, or a significant number of
compiler-generated locals. For example, the MoveNext method of an async method will skip local initialization, but the constructor of
a display class probably will not, as the display class constructor likely has no locals anyway.
Some notable decisions:
1. Although SkipLocalsInit does not require unsafe code blocks, it does require the `unsafe` flag to be passed to the compiler. This
is to signal that in some cases code could view unassigned memory, including `stackalloc`.
2. Due to the compiler not controlling localsinit for other modules when emitting to a netmodule, SkipLocalsInit is not respected on
the assembly level, even if the AttributeUsage of the SkipLocalsInitAttribute is specified that it is allowed.
3. The `Inherited` property of the SkipLocalsInitAttribute is not respected. SkipLocalsInit does not propagate through inheritance.
|
# Feature design for SkipLocalsInit
The feature is to add a new well-known attribute to the compiler, System.Runtime.CompilerServices.SkipLocalsInit that causes method bodies nested "inside" the scope of the attribute to elide the ".locals init" CIL directive that causes the CLR to zero-init local variables and space reserved using the "localloc" instruction. "Nested inside the scope of the attribute" is a concept defined as follows:
1. When the attribute is applied to a module, all emitted methods inside that module, including generated methods, will skip local initialization.
2. When the attribute is applied to a type (including interfaces), all methods transitively inside that type, including generated methods, will skip local initialization. This includes nested types.
3. When the attribute is applied to a method, the method and all methods generated by the compiler which contain user-influenced code inside that method (e.g., local functions, lambdas, async methods) will skip local initialization.
For the above, generated methods will skip local initialization only if they have user code inside them, or a significant number of
compiler-generated locals. For example, the MoveNext method of an async method will skip local initialization, but the constructor of
a display class probably will not, as the display class constructor likely has no locals anyway.
Some notable decisions:
1. Although SkipLocalsInit does not require unsafe code blocks, it does require the `unsafe` flag to be passed to the compiler. This
is to signal that in some cases code could view unassigned memory, including `stackalloc`.
2. Due to the compiler not controlling localsinit for other modules when emitting to a netmodule, SkipLocalsInit is not respected on
the assembly level, even if the AttributeUsage of the SkipLocalsInitAttribute is specified that it is allowed.
3. The `Inherited` property of the SkipLocalsInitAttribute is not respected. SkipLocalsInit does not propagate through inheritance.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/CSharp/Compiler Breaking Changes - VS2019.md | **This document lists known breaking changes in Roslyn 3.0 (Visual Studio 2019) from Roslyn 2.\* (Visual Studio 2017)**
*Breaks are formatted with a monotonically increasing numbered list to allow them to referenced via shorthand (i.e., "known break #1").
Each entry should include a short description of the break, followed by either a link to the issue describing the full details of the break or the full details of the break inline.*
1. https://github.com/dotnet/roslyn/issues/27800 C# will now preserve left-to-right evaluation for compound assignment addition/subtraction expressions where the left-hand side is dynamic. In this example code:
``` C#
class DynamicTest
{
public int Property { get; set; }
static dynamic GetDynamic() => return new DynamicTest();
static int GetInt() => 1;
public static void Main() => GetDynamic().Property += GetInt();
}
```
Previous versions of Roslyn would have evaluated this as:
1. GetInt()
2. GetDynamic()
3. get_Property
4. set_Property
We now evaluate it as:
1. GetDynamic()
2. get_Property
3. GetInt()
4. set_Property
2. Previously, we allowed adding a module with `Microsoft.CodeAnalysis.EmbeddedAttribute` or `System.Runtime.CompilerServices.NonNullTypesAttribute` types declared in it.
In Visual Studio 2019, this produces a collision error with the injected declarations of those types.
3. Previously, you could refer to a `System.Runtime.CompilerServices.NonNullTypesAttribute` type declared in a referenced assembly.
In Visual Studio 2019, the type from assembly is ignored in favor of the injected declaration of that type.
4. https://github.com/dotnet/roslyn/issues/29656 Previously, ref-returning async local functions would compile, by ignoring the `ref` modifier of the return type.
In Visual Studio 2019, this now produces an error, just like ref-returning async methods do.
5. https://github.com/dotnet/roslyn/issues/27748 C# will now produce a warning for an expression of the form `e is _`. The *is_type_expression* can be used with a type named `_`. However, in C# 8 we are introducing a discard pattern written `_` (which cannot be used as the *pattern* of an *is_pattern_expression*). To reduce confusion, there is a new warning when you write `e is _`:
``` none
(11,31): warning CS8413: The name '_' refers to the type 'Program1._', not the discard pattern. Use '@_' for the type, or 'var _' to discard.
bool M1(object o) => o is _;
```
6. C# 8 produces a warning when a `switch` statement uses a constant named `_` as a case label.
``` none
(1,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.
switch(e) { case _: break; }
```
7. In C# 8.0, the parentheses of a switch statement are optional when the expression being switched on is a tuple expression, because the tuple expression has its own parentheses:
``` c#
switch (a, b)
```
Due to this the `OpenParenToken` and `CloseParenToken` fields of a `SwitchStatementSyntax` node may now sometimes be empty.
8. In an *is-pattern-expression*, a warning is now issued when a constant expression does not match the provided pattern because of its value. Such code was previously accepted but gave no warning. For example:
``` c#
if (3 is 4) // warning: the given expression never matches the provided pattern.
```
We also issue a warning when a constant expression *always* matches a constant pattern in an *is-pattern-expression*. For example
``` c#
if (3 is 3) // warning: the given expression always matches the provided constant.
```
Other cases of the pattern always matching (e.g. `e is var t`) do not trigger a warning, even when they are known by the compiler to produce an invariant result.
9. https://github.com/dotnet/roslyn/issues/26098 In C# 8, we give a warning when an is-type expression is always `false` because the input type is an open class type and the type it is tested against is a value type:
``` c#
class C<T> { }
void M<T>(C<T> x)
{
if (x is int) { } // warning: the given expression is never of the provided ('int') type.
}
```
previously, we gave the warning only in the reverse case
``` c#
void M<T>(int x)
{
if (x is C<T>) { } // warning: the given expression is never of the provided ('C<T>') type.
}
```
10. Previously, reference assemblies were emitted including embedded resources. In Visual Studio 2019, embedded resources are no longer emitted into ref assemblies.
See https://github.com/dotnet/roslyn/issues/31197
11. Ref structs now support disposal via pattern. A ref struct enumerator with an accessible `void Dispose()` instance method will now have it invoked at the end of enumeration, regardless of whether the struct type implements IDisposable:
``` c#
public class C
{
public ref struct RefEnumerator
{
public int Current => 0;
public bool MoveNext() => false;
public void Dispose() => Console.WriteLine("Called in C# 8.0 only");
}
public RefEnumerator GetEnumerator() => new RefEnumerator();
public static void Main()
{
foreach(var x in new C())
{
}
// RefEnumerator.Dispose() will be called here in C# 8.0
}
}
```
12. https://github.com/dotnet/roslyn/issues/32732 Switch statements that handle both a `true` case and a `false` case are now considered to handle all of the possible input values.
| **This document lists known breaking changes in Roslyn 3.0 (Visual Studio 2019) from Roslyn 2.\* (Visual Studio 2017)**
*Breaks are formatted with a monotonically increasing numbered list to allow them to referenced via shorthand (i.e., "known break #1").
Each entry should include a short description of the break, followed by either a link to the issue describing the full details of the break or the full details of the break inline.*
1. https://github.com/dotnet/roslyn/issues/27800 C# will now preserve left-to-right evaluation for compound assignment addition/subtraction expressions where the left-hand side is dynamic. In this example code:
``` C#
class DynamicTest
{
public int Property { get; set; }
static dynamic GetDynamic() => return new DynamicTest();
static int GetInt() => 1;
public static void Main() => GetDynamic().Property += GetInt();
}
```
Previous versions of Roslyn would have evaluated this as:
1. GetInt()
2. GetDynamic()
3. get_Property
4. set_Property
We now evaluate it as:
1. GetDynamic()
2. get_Property
3. GetInt()
4. set_Property
2. Previously, we allowed adding a module with `Microsoft.CodeAnalysis.EmbeddedAttribute` or `System.Runtime.CompilerServices.NonNullTypesAttribute` types declared in it.
In Visual Studio 2019, this produces a collision error with the injected declarations of those types.
3. Previously, you could refer to a `System.Runtime.CompilerServices.NonNullTypesAttribute` type declared in a referenced assembly.
In Visual Studio 2019, the type from assembly is ignored in favor of the injected declaration of that type.
4. https://github.com/dotnet/roslyn/issues/29656 Previously, ref-returning async local functions would compile, by ignoring the `ref` modifier of the return type.
In Visual Studio 2019, this now produces an error, just like ref-returning async methods do.
5. https://github.com/dotnet/roslyn/issues/27748 C# will now produce a warning for an expression of the form `e is _`. The *is_type_expression* can be used with a type named `_`. However, in C# 8 we are introducing a discard pattern written `_` (which cannot be used as the *pattern* of an *is_pattern_expression*). To reduce confusion, there is a new warning when you write `e is _`:
``` none
(11,31): warning CS8413: The name '_' refers to the type 'Program1._', not the discard pattern. Use '@_' for the type, or 'var _' to discard.
bool M1(object o) => o is _;
```
6. C# 8 produces a warning when a `switch` statement uses a constant named `_` as a case label.
``` none
(1,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.
switch(e) { case _: break; }
```
7. In C# 8.0, the parentheses of a switch statement are optional when the expression being switched on is a tuple expression, because the tuple expression has its own parentheses:
``` c#
switch (a, b)
```
Due to this the `OpenParenToken` and `CloseParenToken` fields of a `SwitchStatementSyntax` node may now sometimes be empty.
8. In an *is-pattern-expression*, a warning is now issued when a constant expression does not match the provided pattern because of its value. Such code was previously accepted but gave no warning. For example:
``` c#
if (3 is 4) // warning: the given expression never matches the provided pattern.
```
We also issue a warning when a constant expression *always* matches a constant pattern in an *is-pattern-expression*. For example
``` c#
if (3 is 3) // warning: the given expression always matches the provided constant.
```
Other cases of the pattern always matching (e.g. `e is var t`) do not trigger a warning, even when they are known by the compiler to produce an invariant result.
9. https://github.com/dotnet/roslyn/issues/26098 In C# 8, we give a warning when an is-type expression is always `false` because the input type is an open class type and the type it is tested against is a value type:
``` c#
class C<T> { }
void M<T>(C<T> x)
{
if (x is int) { } // warning: the given expression is never of the provided ('int') type.
}
```
previously, we gave the warning only in the reverse case
``` c#
void M<T>(int x)
{
if (x is C<T>) { } // warning: the given expression is never of the provided ('C<T>') type.
}
```
10. Previously, reference assemblies were emitted including embedded resources. In Visual Studio 2019, embedded resources are no longer emitted into ref assemblies.
See https://github.com/dotnet/roslyn/issues/31197
11. Ref structs now support disposal via pattern. A ref struct enumerator with an accessible `void Dispose()` instance method will now have it invoked at the end of enumeration, regardless of whether the struct type implements IDisposable:
``` c#
public class C
{
public ref struct RefEnumerator
{
public int Current => 0;
public bool MoveNext() => false;
public void Dispose() => Console.WriteLine("Called in C# 8.0 only");
}
public RefEnumerator GetEnumerator() => new RefEnumerator();
public static void Main()
{
foreach(var x in new C())
{
}
// RefEnumerator.Dispose() will be called here in C# 8.0
}
}
```
12. https://github.com/dotnet/roslyn/issues/32732 Switch statements that handle both a `true` case and a `false` case are now considered to handle all of the possible input values.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/Core/MSBuildTask/README.md | # Microsoft.Build.Tasks.CodeAnalysis
This MSBuild tasks contains the core tasks and targets for compiling C# and VB projects.
## Debugging
Debugging this code requires a bit of setup because it's not an independent component. It relies on having other parts of the toolset deployed in the same directory. Additionally the project being debugged needs to be modified to ensure this DLL is built instead of the one that ships along side MSBuild.
Set the startup project to Toolset. This project properly deploys all of the necessary components and hence provides a simple F5 experience.
Next modify the Debug settings for Toolset. The startup program needs to be MSBuild.exe. Set the "start external program" field to the full path of MSBuild:
> C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe
Any version 14.0 or high is fine. Pass the path of the target project as the command line arguments.
The target project itself needs to be modified so that it will load the freshly built binaries. Otherwise it will load the binaries deployed with MSBuild. Open up the project file and add the following lines **before** the first `<Import>` declaration in the file:
``` xml
<UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Csc"
AssemblyFile="E:\dd\roslyn\Binaries\Debug\Exes\Toolset\Microsoft.Build.Tasks.CodeAnalysis.dll" />
<UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Vbc"
AssemblyFile="E:\dd\roslyn\Binaries\Debug\Exes\Toolset\Microsoft.Build.Tasks.CodeAnalysis.dll" />
```
Replace `e:\dd\roslyn` with the path to your Roslyn enlistment.
Once that is all done you should be able to F5 the Toolset project and debug the MSBuild task directly.
| # Microsoft.Build.Tasks.CodeAnalysis
This MSBuild tasks contains the core tasks and targets for compiling C# and VB projects.
## Debugging
Debugging this code requires a bit of setup because it's not an independent component. It relies on having other parts of the toolset deployed in the same directory. Additionally the project being debugged needs to be modified to ensure this DLL is built instead of the one that ships along side MSBuild.
Set the startup project to Toolset. This project properly deploys all of the necessary components and hence provides a simple F5 experience.
Next modify the Debug settings for Toolset. The startup program needs to be MSBuild.exe. Set the "start external program" field to the full path of MSBuild:
> C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe
Any version 14.0 or high is fine. Pass the path of the target project as the command line arguments.
The target project itself needs to be modified so that it will load the freshly built binaries. Otherwise it will load the binaries deployed with MSBuild. Open up the project file and add the following lines **before** the first `<Import>` declaration in the file:
``` xml
<UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Csc"
AssemblyFile="E:\dd\roslyn\Binaries\Debug\Exes\Toolset\Microsoft.Build.Tasks.CodeAnalysis.dll" />
<UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.Vbc"
AssemblyFile="E:\dd\roslyn\Binaries\Debug\Exes\Toolset\Microsoft.Build.Tasks.CodeAnalysis.dll" />
```
Replace `e:\dd\roslyn` with the path to your Roslyn enlistment.
Once that is all done you should be able to F5 the Toolset project and debug the MSBuild task directly.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/API Notes/9-30-19.md | ## API Review Notes for September 30th, 2019
### Changes reviewed
Starting commit: `12b125030c34e340086b7fa192fb9426aaddf054`
Ending Commit: `38c90f8401f9e3ee5fb7c82aac36f6b85fdda979`
### Notes
For the AnalyzerConfig removals, we've said that we're fine with this change because the API was just published, and wasn't intended to be.
We don't want to maintain the API shape in the future, and we're willing to accept the risk of breaks in order to remove it now, before many people can take a hard dependency on the API surface.
ErrorLogPath removed from CommandLineArguments, moved to ErrorLogOptions.Path
- We should maintain this API.
- Just forward to the old implementation.
- @333fred will send a PR.
TextDocument
- Should we not remove the constructor? This is a binary breaking change
- This empty constructor cannot be used.
- We'll keep the change.
Workspace
- CanApplyParseOptionChange going from virtual protected to virtual public is a source and binary breaking change
- We should look at having a new non-virtual public method on Workspace and forward to this API.
- @jasonmalinowski will look at this fix.
SyntaxFactory.AnonymousMethodExpression
- Added overload with multiple parameters.
- Part of https://github.com/dotnet/roslyn/pull/37674, which brings the API in line with MethodBodySyntax.
This change is fine.
Formatter.OrganizeUsings
- Should make cancellationtoken optional?
- Need to followup with framework on what the current guidelines are
- Make this default for now
- @jasonmalinowski to follow up.
| ## API Review Notes for September 30th, 2019
### Changes reviewed
Starting commit: `12b125030c34e340086b7fa192fb9426aaddf054`
Ending Commit: `38c90f8401f9e3ee5fb7c82aac36f6b85fdda979`
### Notes
For the AnalyzerConfig removals, we've said that we're fine with this change because the API was just published, and wasn't intended to be.
We don't want to maintain the API shape in the future, and we're willing to accept the risk of breaks in order to remove it now, before many people can take a hard dependency on the API surface.
ErrorLogPath removed from CommandLineArguments, moved to ErrorLogOptions.Path
- We should maintain this API.
- Just forward to the old implementation.
- @333fred will send a PR.
TextDocument
- Should we not remove the constructor? This is a binary breaking change
- This empty constructor cannot be used.
- We'll keep the change.
Workspace
- CanApplyParseOptionChange going from virtual protected to virtual public is a source and binary breaking change
- We should look at having a new non-virtual public method on Workspace and forward to this API.
- @jasonmalinowski will look at this fix.
SyntaxFactory.AnonymousMethodExpression
- Added overload with multiple parameters.
- Part of https://github.com/dotnet/roslyn/pull/37674, which brings the API in line with MethodBodySyntax.
This change is fine.
Formatter.OrganizeUsings
- Should make cancellationtoken optional?
- Need to followup with framework on what the current guidelines are
- Make this default for now
- @jasonmalinowski to follow up.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./CONTRIBUTING.md | # Contributing to Roslyn
Guidelines for contributing to the Roslyn repo.
## Submitting Pull Requests
- **DO** ensure submissions pass all Azure DevOps legs and are merge conflict free.
- **DO** follow the [.editorconfig](http://editorconfig.org/) settings for each directory.
- **DO** submit language feature requests as issues in the [C# language](https://github.com/dotnet/csharplang#discussion) / [VB language](https://github.com/dotnet/vblang) repos. Once a feature is championed and validated by LDM, a developer will be assigned to help begin a prototype on this repo inside a feature branch.
- **DO NOT** submit language features as PRs to this repo first, or they will likely be declined.
- **DO** submit issues for other features. This facilitates discussion of a feature separately from its implementation, and increases the acceptance rates for pull requests.
- **DO NOT** submit large code formatting changes without discussing with the team first.
When you are ready to proceed with making a change, get set up to build (either on [Windows](https://github.com/dotnet/roslyn/blob/main/docs/contributing/Building%2C%20Debugging%2C%20and%20Testing%20on%20Windows.md) or on [Unix](https://github.com/dotnet/roslyn/blob/main/docs/contributing/Building%2C%20Debugging%2C%20and%20Testing%20on%20Unix.md)) the code and familiarize yourself with our developer workflow.
These two blogs posts on contributing code to open source projects are good too: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza and [Don’t “Push” Your Pull Requests](https://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik.
## Creating Issues
- **DO** use a descriptive title that identifies the issue to be addressed or the requested feature. For example, when describing an issue where the compiler is not behaving as expected, write your bug title in terms of what the compiler should do rather than what it is doing – “C# compiler should report CS1234 when Xyz is used in Abcd.”
- **DO** specify a detailed description of the issue or requested feature.
- **DO** provide the following for bug reports
- Describe the expected behavior and the actual behavior. If it is not self-evident such as in the case of a crash, provide an explanation for why the expected behavior is expected.
- Provide example code that reproduces the issue.
- Specify any relevant exception messages and stack traces.
- **DO** subscribe to notifications for the created issue in case there are any follow up questions.
## Coding Style
The Roslyn project is a member of the [.NET Foundation](https://github.com/orgs/dotnet) and follows the same [developer guide](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/coding-style.md). The repo also includes [.editorconfig](http://editorconfig.org) files to help enforce this convention. Contributors should ensure they follow these guidelines when making submissions.
### CSharp
- **DO** use the coding style outlined in the [.NET Runtime Coding Guidelines](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/coding-style.md)
- **DO** use plain code to validate parameters at public boundaries. Do not use Contracts or magic helpers.
```csharp
if (argument == null)
{
throw new ArgumentNullException(nameof(argument));
}
```
- **DO** use `Debug.Assert()` for checks not needed in release builds. Always include a “message” string in your assert to identify failure conditions. Add assertions to document assumptions on non-local program state or parameter values, e.g. “At this point in parsing the scanner should have been advanced to a ‘.’ token by the caller”.
- **DO** avoid allocations in compiler hot paths:
- Avoid LINQ.
- Avoid using `foreach` over collections that do not have a `struct` enumerator.
- Consider using an object pool. There are many usages of object pools in the compiler to see an example.
### Visual Basic Conventions
- **DO** apply the spirit of C# guidelines to Visual Basic when there are natural analogs.
- **DO** place all field declarations at the beginning of a type definition
### Tips 'n' Tricks
Our team finds using [this enhanced source view](http://sourceroslyn.io/) of Roslyn helpful when developing.
| # Contributing to Roslyn
Guidelines for contributing to the Roslyn repo.
## Submitting Pull Requests
- **DO** ensure submissions pass all Azure DevOps legs and are merge conflict free.
- **DO** follow the [.editorconfig](http://editorconfig.org/) settings for each directory.
- **DO** submit language feature requests as issues in the [C# language](https://github.com/dotnet/csharplang#discussion) / [VB language](https://github.com/dotnet/vblang) repos. Once a feature is championed and validated by LDM, a developer will be assigned to help begin a prototype on this repo inside a feature branch.
- **DO NOT** submit language features as PRs to this repo first, or they will likely be declined.
- **DO** submit issues for other features. This facilitates discussion of a feature separately from its implementation, and increases the acceptance rates for pull requests.
- **DO NOT** submit large code formatting changes without discussing with the team first.
When you are ready to proceed with making a change, get set up to build (either on [Windows](https://github.com/dotnet/roslyn/blob/main/docs/contributing/Building%2C%20Debugging%2C%20and%20Testing%20on%20Windows.md) or on [Unix](https://github.com/dotnet/roslyn/blob/main/docs/contributing/Building%2C%20Debugging%2C%20and%20Testing%20on%20Unix.md)) the code and familiarize yourself with our developer workflow.
These two blogs posts on contributing code to open source projects are good too: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza and [Don’t “Push” Your Pull Requests](https://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik.
## Creating Issues
- **DO** use a descriptive title that identifies the issue to be addressed or the requested feature. For example, when describing an issue where the compiler is not behaving as expected, write your bug title in terms of what the compiler should do rather than what it is doing – “C# compiler should report CS1234 when Xyz is used in Abcd.”
- **DO** specify a detailed description of the issue or requested feature.
- **DO** provide the following for bug reports
- Describe the expected behavior and the actual behavior. If it is not self-evident such as in the case of a crash, provide an explanation for why the expected behavior is expected.
- Provide example code that reproduces the issue.
- Specify any relevant exception messages and stack traces.
- **DO** subscribe to notifications for the created issue in case there are any follow up questions.
## Coding Style
The Roslyn project is a member of the [.NET Foundation](https://github.com/orgs/dotnet) and follows the same [developer guide](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/coding-style.md). The repo also includes [.editorconfig](http://editorconfig.org) files to help enforce this convention. Contributors should ensure they follow these guidelines when making submissions.
### CSharp
- **DO** use the coding style outlined in the [.NET Runtime Coding Guidelines](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/coding-style.md)
- **DO** use plain code to validate parameters at public boundaries. Do not use Contracts or magic helpers.
```csharp
if (argument == null)
{
throw new ArgumentNullException(nameof(argument));
}
```
- **DO** use `Debug.Assert()` for checks not needed in release builds. Always include a “message” string in your assert to identify failure conditions. Add assertions to document assumptions on non-local program state or parameter values, e.g. “At this point in parsing the scanner should have been advanced to a ‘.’ token by the caller”.
- **DO** avoid allocations in compiler hot paths:
- Avoid LINQ.
- Avoid using `foreach` over collections that do not have a `struct` enumerator.
- Consider using an object pool. There are many usages of object pools in the compiler to see an example.
### Visual Basic Conventions
- **DO** apply the spirit of C# guidelines to Visual Basic when there are natural analogs.
- **DO** place all field declarations at the beginning of a type definition
### Tips 'n' Tricks
Our team finds using [this enhanced source view](http://sourceroslyn.io/) of Roslyn helpful when developing.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/ExpressionVariables.md | Expression Variables
=========================
The *expression variables* feature extends the features introduced in C# 7 to permit expressions
containing expression variables (out variable declarations and declaration patterns) in field
initializers, property initializers, ctor-initializers, and query clauses.
See https://github.com/dotnet/csharplang/issues/32 and
https://github.com/dotnet/csharplang/blob/main/proposals/csharp-7.3/expression-variables-in-initializers.md
for more information.
Current state of the feature:
[X] Permit in field initializers
[X] Permit in property initializers
[ ] Permit in ctor-initializers
[X] Permit in query clauses
| Expression Variables
=========================
The *expression variables* feature extends the features introduced in C# 7 to permit expressions
containing expression variables (out variable declarations and declaration patterns) in field
initializers, property initializers, ctor-initializers, and query clauses.
See https://github.com/dotnet/csharplang/issues/32 and
https://github.com/dotnet/csharplang/blob/main/proposals/csharp-7.3/expression-variables-in-initializers.md
for more information.
Current state of the feature:
[X] Permit in field initializers
[X] Permit in property initializers
[ ] Permit in ctor-initializers
[X] Permit in query clauses
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/ide/api-designs/Workspace and Source Generated Documents.md | # Source Generator / Workspace API Proposal
In Visual Studio 16.8, we shipped only limited source generator support in the Workspace APIs; any caller requesting a Compilation would get a Compilation that contained the correct generated SyntaxTrees, but there was no way to know where the trees came from, nor interact with the generated documents in any other way. This proposal describes how we are going to shore these APIs up.
## SourceGeneratedDocument Type
A new type will be introduced, `SourceGeneratedDocument`, that inherits from `Document`. `GetSyntaxTreeAsync`, `GetSyntaxRootAsync`, and `GetTextAsync` (and the corresponding synchronous and Try methods) will return the generated text or trees. The trees will be the same instances as would be found in the `Compilation.SyntaxTrees`.
The `Id` of the `Document` will be generated dynamically by the workspace. As much as possible, the Id will be persistent between snapshots as much as is practical. When a generator produces a document, it provides a "hint name" which is intended to be used for the IDE to allow for 'permanence' between runs. `DocumentId`s are defined by a GUID in the implementation, so to ensure the DocumentId can be stable, we will generate the GUID as a hash of the hint name, the generator name, and any other pertinent information. Although the implementation may do extra caching behind the scenes where it won't have to recompute hashes in this way, this will ensure the `DocumentId` stays stable even if the caches fail to avoid any surprises.
`SourceGeneratedDocument` will have some additional members:
1. `HintName`: the exact hint name that was provided by the generator.
1. `SourceGenerator`: the ISourceGenerator instance that produced this document.
For now, any _mutation_ of a SourceGeneratedDocument will not be supported. Calls to the following members will throw `NotSupportedException`:
1. `WithText`
2. `WithSyntaxRoot`
3. `WithName`
4. `WithFolders`
5. `WithFilePath`
Down the road, I hope that we might offer an extension point for a source generator to participate in WithText and WithSyntaxRoot. In many cases the generated source may contain expressions that are verbatim C# (think a .cshtml file having a C# section), and so we could have WithText or WithSyntaxRoot apply the resulting edit back to the document that the verbatim C# came from. The design of this is out of scope here.
## APIs on `Project`
### Existing API: `Documents`
Note the Documents collection will _not_ change, and will only include regular documents. It cannot include source generated documents because since it is a property access, there is no opportunity to make this async, nor have any way to express cancellation. Since a generator could produce any number of documents, there's simply no way to make this answer quickly without fundamentally taking a different approach to the API.
### New API: `ImmutableArray<SourceGeneratedDocument> GetSourceGeneratedDocumentsAsync(CancelationToken)`
This will run generators if they have not already ran, and then return a `SourceGeneratedDocument` for each generated document.
The implementation of this will run `GetCompilationAsync` if the documents have not been generated; if the Compilation had already been generated, we would have cached the generated document information and so this would be cheap. We will hold onto the list of documents strongly (the tree will be a recoverable tree), so even if the `Compilation` is GC'ed we won't have to recompute this part a second time.
### New API: `SourceGeneratedDocument? GetSourceGeneratedDocumentAsync(DocumentId, CancellationToken)`
Fetches a single document by ID; equivalent to calling the API and filtering down to the right document.
### Existing API: `GetDocument(SyntaxTree)`
No changes, it will potentially return a `SourceGeneratedDocument` now. Callers _may_ have to check whether it's a generated document before they try to offer a fix or refactoring on the document.
This API is the hardest API to figure out what to do in this entire spec. If it doesn't return generated documents, many features would break, since it's very common to assume that if a syntax tree exists in a `Compilation`, that there must be a `Document` that matches it. However, some features might _not_ want to see a generated document returned here because then they're going to try to modify that, and that won't make sense either. An audit of the code fixes in Roslyn discovered that for many of the places that would need an update to _ignore_ a generated document would also need an update to deal with the null reference that would come back from `GetDocument`.
The other odd thing here is whether this function needs to be asynchronous or not. The current belief is no, because the only way you can have gotten a SyntaxTree to pass to it from the same `Solution` is either from:
1. The `Compilation` or a symbol that came from it, which means generators have ran.
2. You inspected some `SourceGeneratedDocument` and got it's tree, which means that generator has already ran.
The only surprise you might run into is taking a `SyntaxTree` from an earlier `Solution`, passing it to a newer `Solution`, and getting a document that no longer exists because in the later `Solution` is no longer generating this document. However, passing a `SyntaxTree` between snapshots like that is questionable in the first place. Any code that is working with multiple snapshots and knew that a Document between the snapshots had the same tree could have done something like this, but that code is potentially broken _anyways_ with source generators since now one tree can change due to another tree changing.
## APIs on `Workspace`
### Existing APIs: `OpenDocument(DocumentId)`/`CloseDocument(DocumentId)`
This API today is used by any feature that wants to tell the host to open a file. This will accept the DocumentId of a generated document and work properly.
### Existing APIs: `IsDocumentOpen(DocumentId)` / `GetOpenDocumentIds(...)`
These will behave no differently than before.
### Existing APIs: `OnDocumentOpened`/`OnDocumentClosed`
These APIs today associate a Workspace and a SourceTextContainer. Besides allowing APIs like `GetOpenDocumentInCurrentContextWithChanges` to work, this also ensures that a change to the text buffer updates the Workspace automatically. For generated documents, it will wire up the first part (assocating the container) but will not update the Workspace contents when the buffer changes. This is because the updates flow in the _other_ direction, and for now that updating is being managed by a Visual Studio-layer component. Further refactoring may move the core updating into the Workspace layer directly, but not for now.
## APIs for Fetching Documents
### Existing API: `GetOpenDocumentInCurrentContextWithChanges(ITextSnapshot)`
Because we want source generated documents to have the same IDE affordances as any other open file, this API will still work but return a `SourceGeneratedDocument` in that case. Some special handling is required though due to asynchrony. If a user has a generated document open, we may have an async process running in the background that may be trying to refresh this open generated document. The call to `GetOpenDocumentInCurrentContextWithChanges` however will "freeze" the generated document to match the `ITextSnapshot`, so any calls to `GetSourceGeneratedDocumentsAsync()` will return that exact same text, even if that content is out of sync with what would be generated given that project state.
This does mean that in this case, the contents of this document won't match if you compared the document to Workspace.CurrentSolution, got the generated document by ID, and then asked for it's text. This however is OK: that can _always_ be the case for any caller to `GetOpenDocumentInCurrentContextWithChanges` since it always forks to match the `ITextSnapshot`. We're just making the window where this can happen to be bigger than usual. | # Source Generator / Workspace API Proposal
In Visual Studio 16.8, we shipped only limited source generator support in the Workspace APIs; any caller requesting a Compilation would get a Compilation that contained the correct generated SyntaxTrees, but there was no way to know where the trees came from, nor interact with the generated documents in any other way. This proposal describes how we are going to shore these APIs up.
## SourceGeneratedDocument Type
A new type will be introduced, `SourceGeneratedDocument`, that inherits from `Document`. `GetSyntaxTreeAsync`, `GetSyntaxRootAsync`, and `GetTextAsync` (and the corresponding synchronous and Try methods) will return the generated text or trees. The trees will be the same instances as would be found in the `Compilation.SyntaxTrees`.
The `Id` of the `Document` will be generated dynamically by the workspace. As much as possible, the Id will be persistent between snapshots as much as is practical. When a generator produces a document, it provides a "hint name" which is intended to be used for the IDE to allow for 'permanence' between runs. `DocumentId`s are defined by a GUID in the implementation, so to ensure the DocumentId can be stable, we will generate the GUID as a hash of the hint name, the generator name, and any other pertinent information. Although the implementation may do extra caching behind the scenes where it won't have to recompute hashes in this way, this will ensure the `DocumentId` stays stable even if the caches fail to avoid any surprises.
`SourceGeneratedDocument` will have some additional members:
1. `HintName`: the exact hint name that was provided by the generator.
1. `SourceGenerator`: the ISourceGenerator instance that produced this document.
For now, any _mutation_ of a SourceGeneratedDocument will not be supported. Calls to the following members will throw `NotSupportedException`:
1. `WithText`
2. `WithSyntaxRoot`
3. `WithName`
4. `WithFolders`
5. `WithFilePath`
Down the road, I hope that we might offer an extension point for a source generator to participate in WithText and WithSyntaxRoot. In many cases the generated source may contain expressions that are verbatim C# (think a .cshtml file having a C# section), and so we could have WithText or WithSyntaxRoot apply the resulting edit back to the document that the verbatim C# came from. The design of this is out of scope here.
## APIs on `Project`
### Existing API: `Documents`
Note the Documents collection will _not_ change, and will only include regular documents. It cannot include source generated documents because since it is a property access, there is no opportunity to make this async, nor have any way to express cancellation. Since a generator could produce any number of documents, there's simply no way to make this answer quickly without fundamentally taking a different approach to the API.
### New API: `ImmutableArray<SourceGeneratedDocument> GetSourceGeneratedDocumentsAsync(CancelationToken)`
This will run generators if they have not already ran, and then return a `SourceGeneratedDocument` for each generated document.
The implementation of this will run `GetCompilationAsync` if the documents have not been generated; if the Compilation had already been generated, we would have cached the generated document information and so this would be cheap. We will hold onto the list of documents strongly (the tree will be a recoverable tree), so even if the `Compilation` is GC'ed we won't have to recompute this part a second time.
### New API: `SourceGeneratedDocument? GetSourceGeneratedDocumentAsync(DocumentId, CancellationToken)`
Fetches a single document by ID; equivalent to calling the API and filtering down to the right document.
### Existing API: `GetDocument(SyntaxTree)`
No changes, it will potentially return a `SourceGeneratedDocument` now. Callers _may_ have to check whether it's a generated document before they try to offer a fix or refactoring on the document.
This API is the hardest API to figure out what to do in this entire spec. If it doesn't return generated documents, many features would break, since it's very common to assume that if a syntax tree exists in a `Compilation`, that there must be a `Document` that matches it. However, some features might _not_ want to see a generated document returned here because then they're going to try to modify that, and that won't make sense either. An audit of the code fixes in Roslyn discovered that for many of the places that would need an update to _ignore_ a generated document would also need an update to deal with the null reference that would come back from `GetDocument`.
The other odd thing here is whether this function needs to be asynchronous or not. The current belief is no, because the only way you can have gotten a SyntaxTree to pass to it from the same `Solution` is either from:
1. The `Compilation` or a symbol that came from it, which means generators have ran.
2. You inspected some `SourceGeneratedDocument` and got it's tree, which means that generator has already ran.
The only surprise you might run into is taking a `SyntaxTree` from an earlier `Solution`, passing it to a newer `Solution`, and getting a document that no longer exists because in the later `Solution` is no longer generating this document. However, passing a `SyntaxTree` between snapshots like that is questionable in the first place. Any code that is working with multiple snapshots and knew that a Document between the snapshots had the same tree could have done something like this, but that code is potentially broken _anyways_ with source generators since now one tree can change due to another tree changing.
## APIs on `Workspace`
### Existing APIs: `OpenDocument(DocumentId)`/`CloseDocument(DocumentId)`
This API today is used by any feature that wants to tell the host to open a file. This will accept the DocumentId of a generated document and work properly.
### Existing APIs: `IsDocumentOpen(DocumentId)` / `GetOpenDocumentIds(...)`
These will behave no differently than before.
### Existing APIs: `OnDocumentOpened`/`OnDocumentClosed`
These APIs today associate a Workspace and a SourceTextContainer. Besides allowing APIs like `GetOpenDocumentInCurrentContextWithChanges` to work, this also ensures that a change to the text buffer updates the Workspace automatically. For generated documents, it will wire up the first part (assocating the container) but will not update the Workspace contents when the buffer changes. This is because the updates flow in the _other_ direction, and for now that updating is being managed by a Visual Studio-layer component. Further refactoring may move the core updating into the Workspace layer directly, but not for now.
## APIs for Fetching Documents
### Existing API: `GetOpenDocumentInCurrentContextWithChanges(ITextSnapshot)`
Because we want source generated documents to have the same IDE affordances as any other open file, this API will still work but return a `SourceGeneratedDocument` in that case. Some special handling is required though due to asynchrony. If a user has a generated document open, we may have an async process running in the background that may be trying to refresh this open generated document. The call to `GetOpenDocumentInCurrentContextWithChanges` however will "freeze" the generated document to match the `ITextSnapshot`, so any calls to `GetSourceGeneratedDocumentsAsync()` will return that exact same text, even if that content is out of sync with what would be generated given that project state.
This does mean that in this case, the contents of this document won't match if you compared the document to Workspace.CurrentSolution, got the generated document by ID, and then asked for it's text. This however is OK: that can _always_ be the case for any caller to `GetOpenDocumentInCurrentContextWithChanges` since it always forks to match the `ITextSnapshot`. We're just making the window where this can happen to be bigger than usual. | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/infrastructure/feature branches azure.md | # Creating Feature Branches
This document describes the process for setting up CI on a feature branch of roslyn.
## Push the branch
The first step is to create the branch seeded with the initial change on roslyn. This branch should have the name `features/<feature name>`. For example: `features/mono` for working on mono work.
Assuming the branch should start with the contents of `main` the branch can be created by doing the following:
Note: these steps assume the remote `origin` points to the official [roslyn repository](https://github.com/dotnet/roslyn).
``` cmd
> git fetch origin
> git checkout -B init origin/main
> git push origin init:features/mono
```
## Adding branch to Azure Pipelines
The following files need to be edited in order for GitHub to trigger Azure Pipelines Test runs on PRs:
- [azure-pipelines.yml](https://github.com/dotnet/roslyn/blob/main/azure-pipelines.yml)
- [azure-pipelines-integration.yml](https://github.com/dotnet/roslyn/blob/main/azure-pipelines-integration.yml)
Under the `pr` section in the file add your branch name.
``` yaml
pr:
- main
- main-vs-deps
- ...
- features/mono
```
| # Creating Feature Branches
This document describes the process for setting up CI on a feature branch of roslyn.
## Push the branch
The first step is to create the branch seeded with the initial change on roslyn. This branch should have the name `features/<feature name>`. For example: `features/mono` for working on mono work.
Assuming the branch should start with the contents of `main` the branch can be created by doing the following:
Note: these steps assume the remote `origin` points to the official [roslyn repository](https://github.com/dotnet/roslyn).
``` cmd
> git fetch origin
> git checkout -B init origin/main
> git push origin init:features/mono
```
## Adding branch to Azure Pipelines
The following files need to be edited in order for GitHub to trigger Azure Pipelines Test runs on PRs:
- [azure-pipelines.yml](https://github.com/dotnet/roslyn/blob/main/azure-pipelines.yml)
- [azure-pipelines-integration.yml](https://github.com/dotnet/roslyn/blob/main/azure-pipelines-integration.yml)
Under the `pr` section in the file add your branch name.
``` yaml
pr:
- main
- main-vs-deps
- ...
- features/mono
```
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/outvar.md | Out Variable Declarations
=========================
The *out variable declaration* feature enables a variable to be declared at the location that it is being passed as an `out` argument.
```antlr
argument_value
: 'out' type identifier
| ...
;
```
A variable declared this way is called an *out variable*.
You may use the contextual keyword `var` for the variable's type.
The scope will be the same as for a *pattern-variable* introduced via pattern-matching.
According to Language Specification (section 7.6.7 Element access)
the argument-list of an element-access (indexing expression)
does not contain ref or out arguments.
However, they are permitted by the compiler for various scenarios, for example indexers
declared in metadata that accept `out`.
Within the scope of a local variable introduced by a local-variable-declaration,
it is a compile-time error to refer to that local variable in a textual position
that precedes its declaration.
It is also an error to reference implicitly-typed (§8.5.1) out variable in the same argument list that immediately
contains its declaration.
Overload resolution is modified as follows:
We add a new conversion:
> There is a *conversion from expression* from an implicitly-typed out variable declaration to every type.
Also
> The type of an explicitly-typed out variable argument is the declared type.
and
> An implicitly-typed out variable argument has no type.
Neither conversion from expression is better when the argument is an implicitly-typed out variable declaration. (this needs to be woven into the form of the specification)
The type of an implicitly-typed out variable is the type of the corresponding parameter in the signature of the method.
The new syntax node `DeclarationExpressionSyntax` is added to represent the declaration in an out var argument.
#### Discussion
There is a discussion thread for this feature at https://github.com/dotnet/roslyn/issues/6183.
#### Open issues and TODOs:
Tracked at https://github.com/dotnet/roslyn/issues/11566.
| Out Variable Declarations
=========================
The *out variable declaration* feature enables a variable to be declared at the location that it is being passed as an `out` argument.
```antlr
argument_value
: 'out' type identifier
| ...
;
```
A variable declared this way is called an *out variable*.
You may use the contextual keyword `var` for the variable's type.
The scope will be the same as for a *pattern-variable* introduced via pattern-matching.
According to Language Specification (section 7.6.7 Element access)
the argument-list of an element-access (indexing expression)
does not contain ref or out arguments.
However, they are permitted by the compiler for various scenarios, for example indexers
declared in metadata that accept `out`.
Within the scope of a local variable introduced by a local-variable-declaration,
it is a compile-time error to refer to that local variable in a textual position
that precedes its declaration.
It is also an error to reference implicitly-typed (§8.5.1) out variable in the same argument list that immediately
contains its declaration.
Overload resolution is modified as follows:
We add a new conversion:
> There is a *conversion from expression* from an implicitly-typed out variable declaration to every type.
Also
> The type of an explicitly-typed out variable argument is the declared type.
and
> An implicitly-typed out variable argument has no type.
Neither conversion from expression is better when the argument is an implicitly-typed out variable declaration. (this needs to be woven into the form of the specification)
The type of an implicitly-typed out variable is the type of the corresponding parameter in the signature of the method.
The new syntax node `DeclarationExpressionSyntax` is added to represent the declaration in an out var argument.
#### Discussion
There is a discussion thread for this feature at https://github.com/dotnet/roslyn/issues/6183.
#### Open issues and TODOs:
Tracked at https://github.com/dotnet/roslyn/issues/11566.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/wiki/Getting-Started-C#-Syntax-Transformation.md | ## Prerequisites
* [Visual Studio 2015](https://www.visualstudio.com/downloads)
* [.NET Compiler Platform SDK](https://aka.ms/roslynsdktemplates)
* [Getting Started C# Syntax Analysis](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Getting-Started-C%23-Syntax-Analysis.md)
* [Getting Started C# Semantic Analysis](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Getting-Started-C%23-Semantic-Analysis.md)
## Introduction
This walkthrough builds on concepts and techniques explored in the **Getting Started: Syntax Analysis** and **Getting Started: Semantic Analysis** walkthroughs. If you haven't already, it's strongly advised that you complete those walkthroughs before beginning this one.
In this walkthrough, you'll explore techniques for creating and transforming syntax trees. In combination with the techniques you learned in previous Getting Started walkthroughs, you will create your first command-line refactoring!
## Immutability and the .NET Compiler Platform
A fundamental tenet of the .NET Compiler Platform is immutability. Because immutable data structures cannot be changed after they are created, they can be safely shared and analyzed by multiple consumers simultaneously without the dangers of one tool affecting another in unpredictable ways. No locks or other concurrency measures needed. This applies to syntax trees, compilations, symbols, semantic models, and every other data structure you'll encounter. Instead of modification, new objects are created based on specified differences to the old ones. You'll apply this concept to syntax trees to create tree transformations!
## Creating and "Modifying" Trees
### Creating Nodes with Factory Methods
To create **SyntaxNodes** you must use the **SyntaxFactory** class factory methods. For each kind of node, token, or trivia there is a factory method which can be used to create an instance of that type. By composing nodes hierarchically in a bottom-up fashion you can create syntax trees.
#### Example - Creating a SyntaxNode using Factory Methods
This example uses the **SyntaxFactory** class methods to construct a **NameSyntax** representing the **System.Collections.Generic** namespace.
**NameSyntax** is the base class for four types of names that appear in C#:
* **IdentifierNameSyntax** which represents simple single identifier names like **System** and **Microsoft**
* **GenericNameSyntax** which represents a generic type or method name such as **List<int>**
* **QualifiedNameSyntax** which represents a qualified name of the form ```<left-name>.<right-identifier-or-generic-name>``` such as **System.IO**
* **AliasQualifiedNameSyntax** which represents a name using an assembly extern alias such a **LibraryV2::Foo**
By composing these names together you can create any name which can appear in the C# language.
1) Create a new C# **Stand-Alone Code Analysis Tool** project.
* In Visual Studio, choose **File -> New -> Project...** to display the New Project dialog.
* Under **Visual C# -> Extensibility**, choose **Stand-Alone Code Analysis Tool**.
* Name your project "**ConstructionCS**" and click OK.
2) Add the following using directive to the top of the file to import the factory methods of the **SyntaxFactory** class so that we can use them later without qualifying them:
```C#
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
```
3) Move your cursor to the line containing the **closing brace** of your **Main** method and set a breakpoint there.
* In Visual Studio, choose **Debug -> Toggle Breakpoint**.
4) Run the program.
* In Visual Studio, choose **Debug -> Start Debugging**.
5) First create a simple **IdentifierNameSyntax** representing the name of the **System** namespace and assign it to a variable. As you build up a **QualifiedNameSyntax** from this node you will reuse this variable so declare this variable to be of type **NameSyntax** to allow it to store both types of **SyntaxNode** - **DO NOT** use type inference:
```C#
NameSyntax name = IdentifierName("System");
```
6) Set this statement as the next statement to be executed and execute it.
* Right-click this line and choose **Set Next Statement**.
* In Visual Studio, choose **Debug -> Step Over**, to execute this statement and initialize the new variable.
* You will need to repeat this process for each of the following steps as we introduce new variables and inspect them with the debugger.
7) Open the **Immediate Window**.
* In Visual Studio, choose **Debug -> Windows -> Immediate**.
8) Using the Immediate Window, type the expression **name.ToString()** and press Enter to evaluate it. You should see the string "**System**" as the result.
9) Next, construct a **QualifiedNameSyntax** using this **name** node as the **left** of the name and a new **IdentifierNameSyntax** for the **Collections** namespace as the **right** side of the **QualifiedNameSyntax**:
```C#
name = QualifiedName(name, IdentifierName("Collections"));
```
10) Execute this statement to set the **name** variable to the new **QualifiedNameSyntax** node.
11) Using the Immediate Window, evaluate the expression **name.ToString()**. It should evaluate to "**System.Collections**".
12) Continue this pattern by building another **QualifiedNameSyntax** node for the **Generic** namespace:
```C#
name = QualifiedName(name, IdentifierName("Generic"));
```
13) Execute this statement and again use the Immediate Window to observe that **name.ToString()** now evaluates to the fully qualified name "**System.Collections.Generic**".
### Modifying Nodes with With* and ReplaceNode Methods
Because the syntax trees are immutable, the **Syntax API** provides no direct mechanism for modifying an existing syntax tree after construction. However, the **Syntax API** does provide methods for producing new trees based on specified changes to existing ones. Each concrete class that derives from **SyntaxNode** defines **With*** methods which you can use to specify changes to its child properties. Additionally, the **ReplaceNode** extension method can be used to replace a descendent node in a subtree. Without this method updating a node would also require manually updating its parent to point to the newly created child and repeating this process up the entire tree - a process known as _re-spining_ the tree.
#### Example - Transformations using the With* and ReplaceNode methods.
This example uses the **WithName** method to replace the name in a **UsingDirectiveSyntax** node with the one constructed above.
1) Continuing from the previous example above, add this code to parse a sample code file:
```C#
SyntaxTree tree = CSharpSyntaxTree.ParseText(
@"using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}
}");
var root = (CompilationUnitSyntax)tree.GetRoot();
```
* Note that the file uses the **System.Collections** namespace and not the **System.Collections.Generic** namespace.
2) Execute these statements.
3) Create a new **UsingDirectiveSyntax** node using the **UsingDirectiveSyntax.WithName** method to update the "**System.Collections**" name with the name we created above:
```C#
var oldUsing = root.Usings[1];
var newUsing = oldUsing.WithName(name);
```
4) Using the Immediate Window, evaluate the expression **root.ToString()** and observe that the original tree has not been changed to contain this new updated node.
5) Add the following line using the **ReplaceNode** extension method to create a new tree, replacing the existing import with the updated **newUsing** node, and store the new tree in the existing **root** variable:
```C#
root = root.ReplaceNode(oldUsing, newUsing);
```
6) Execute this statement.
7) Using the Immediate Window evaluate the expression **root.ToString()** this time observing that the tree now correctly imports the **System.Collections.Generic** namespace.
8) Stop the program.
* In Visual Studio, choose **Debug -> Stop debugging**.
9) Your **Program.cs** file should now look like this:
```C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ConstructionCS
{
class Program
{
static void Main(string[] args)
{
NameSyntax name = IdentifierName("System");
name = QualifiedName(name, IdentifierName("Collections"));
name = QualifiedName(name, IdentifierName("Generic"));
SyntaxTree tree = CSharpSyntaxTree.ParseText(
@"using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}
}");
var root = (CompilationUnitSyntax)tree.GetRoot();
var oldUsing = root.Usings[1];
var newUsing = oldUsing.WithName(name);
root = root.ReplaceNode(oldUsing, newUsing);
}
}
}
```
### Transforming Trees using SyntaxRewriters
The **With*** and **ReplaceNode** methods provide convenient means to transform individual branches of a syntax tree. However, often it may be necessary to perform multiple transformations on a syntax tree in concert. The **SyntaxRewriter** class is a subclass of **SyntaxVisitor** which can be used to apply a transformation to a specific type of **SyntaxNode**. It is also possible to apply a set of transformations to multiple types of **SyntaxNode** wherever they appear in a syntax tree. The following example demonstrates this in a naive implementation of a command-line refactoring which removes explicit types in local variable declarations anywhere where type inference could be used. This example makes use of techniques discussed in this walkthrough as well as the **Getting Started: Syntactic Analysis** and **Getting Started: Semantic Analysis** walkthroughs.
#### Example - Creating a SyntaxRewriter to transform syntax trees.
1) Create a new C# **Stand-Alone Code Analysis Tool** project.
* In Visual Studio, choose **File -> New -> Project...** to display the New Project dialog.
* Under **Visual C# -> Extensibility**, choose **Stand-Alone Code Analysis Tool**.
* Name your project "**TransformationCS**" and click OK.
2) Insert the following **using** directive at the top of your **Program.cs** file:
```C#
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
```
3) Add a new class file to the project.
* In Visual Studio, choose **Project -> Add Class...**
* In the "Add New Item" dialog type **TypeInferenceRewriter.cs** as the filename.
4) Add the following using directives.
```C#
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
```
5) Make the **TypeInferenceRewriter** class extend the **CSharpSyntaxRewriter** class:
```C#
public class TypeInferenceRewriter : CSharpSyntaxRewriter
{
```
6) Add the following code to declare a private read-only field to hold a **SemanticModel** and initialize it from the constructor. You will need this field later on to determine where type inference can be used:
```C#
private readonly SemanticModel SemanticModel;
public TypeInferenceRewriter(SemanticModel semanticModel)
{
this.SemanticModel = semanticModel;
}
```
7) Override the **VisitLocalDeclarationStatement** method:
```C#
public override SyntaxNode VisitLocalDeclarationStatement(
LocalDeclarationStatementSyntax node)
{
}
```
* Note that the **VisitLocalDeclarationStatement** method returns a **SyntaxNode**, not **LocalDeclarationStatementSyntax**. In this example you'll return another **LocalDeclarationStatementSyntax** node based on the existing one. In other scenarios one kind of node may be replaced by another kind of node entirely - or even removed.
8) For the purpose of this example you'll only handle local variable declarations, though type inference may be used in **foreach** loops, **for** loops, LINQ expressions, and lambda expressions. Furthermore this rewriter will only transform declarations of the simplest form:
```C#
Type variable = expression;
```
The following forms of variable declarations in C# are either incompatible with type inference or left as an exercise to the reader.
```C#
// Multiple variables in a single declaration.
Type variable1 = expression1,
variable2 = expression2;
// No initializer.
Type variable;
```
9) Add the following code to the body of the **VisitLocalDeclarationStatement** method to skip rewriting these forms of declarations:
```C#
if (node.Declaration.Variables.Count > 1)
{
return node;
}
if (node.Declaration.Variables[0].Initializer == null)
{
return node;
}
```
* Note that returning the **node** parameter unmodified results in no rewriting taking place for that node.
10) Add these statements to extract the type name specified in the declaration and bind it using the **SemanticModel** field to obtain a type symbol.
```C#
VariableDeclaratorSyntax declarator = node.Declaration.Variables.First();
TypeSyntax variableTypeName = node.Declaration.Type;
ITypeSymbol variableType =
(ITypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName)
.Symbol;
```
11) Now, add this statement to bind the initializer expression:
```C#
TypeInfo initializerInfo =
SemanticModel.GetTypeInfo(declarator
.Initializer
.Value);
```
12) Finally, add the following **if** statement to replace the existing type name with the **var** keyword if the type of the initializer expression matches the type specified:
```C#
if (variableType == initializerInfo.Type)
{
TypeSyntax varTypeName =
IdentifierName("var")
.WithLeadingTrivia(
variableTypeName.GetLeadingTrivia())
.WithTrailingTrivia(
variableTypeName.GetTrailingTrivia());
return node.ReplaceNode(variableTypeName, varTypeName);
}
else
{
return node;
}
```
* Note that this conditional is required because if the types don't match the declaration may be casting the initializer expression to a base class or interface. Removing the explicit type in these cases would change the semantics of a program.
* Note also that **var** is specified as an identifier rather than a keyword because **var** is a contextual keyword.
* Note that the leading and trailing trivia (whitespace) is transferred from the old type name to the **var** keyword to maintain vertical whitespace and indentation.
* Note also that it's simpler to use **ReplaceNode** rather than **With*** to transform the **LocalDeclarationStatementSyntax** because the type name is actually the grandchild of the declaration statement.
13) Your **TypeInferenceRewriter.cs** file should now look like this:
```C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace TransformationCS
{
public class TypeInferenceRewriter : CSharpSyntaxRewriter
{
private readonly SemanticModel SemanticModel;
public TypeInferenceRewriter(SemanticModel semanticModel)
{
this.SemanticModel = semanticModel;
}
public override SyntaxNode VisitLocalDeclarationStatement(
LocalDeclarationStatementSyntax node)
{
if (node.Declaration.Variables.Count > 1)
{
return node;
}
if (node.Declaration.Variables[0].Initializer == null)
{
return node;
}
VariableDeclaratorSyntax declarator = node.Declaration.Variables.First();
TypeSyntax variableTypeName = node.Declaration.Type;
ITypeSymbol variableType =
(ITypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName)
.Symbol;
TypeInfo initializerInfo =
SemanticModel.GetTypeInfo(declarator
.Initializer
.Value);
if (variableType == initializerInfo.Type)
{
TypeSyntax varTypeName =
IdentifierName("var")
.WithLeadingTrivia(
variableTypeName.GetLeadingTrivia())
.WithTrailingTrivia(
variableTypeName.GetTrailingTrivia());
return node.ReplaceNode(variableTypeName, varTypeName);
}
else
{
return node;
}
}
}
}
```
14) Return to your **Program.cs** file.
15) To test your **TypeInferenceRewriter** you'll need to create a test **Compilation** to obtain the **SemanticModels** required for the type inference analysis. You'll do this step last. In the meantime declare a placeholder variable representing your test Compilation:
```C#
Compilation test = CreateTestCompilation();
```
16) After pausing a moment you should see an error squiggle appear reporting that no **CreateTestCompilation** method exists. Press **Ctrl+Period** to open the light-bulb and then press Enter to invoke the **Generate Method Stub** command. This will generate a method stub for the **CreateTestCompilation** method in **Program**. You'll come back to fill this in later:

17) Next, write the following code to iterate over each **SyntaxTree** in the test **Compilation.** For each one initialize a new **TypeInferenceRewriter** with the **SemanticModel** for that tree:
```C#
foreach (SyntaxTree sourceTree in test.SyntaxTrees)
{
SemanticModel model = test.GetSemanticModel(sourceTree);
TypeInferenceRewriter rewriter = new TypeInferenceRewriter(model);
}
```
18) Lastly, inside the **foreach** statement you just created, add the following code to perform the transformation on each source tree and conditionally write out the new transformed tree if any edits were made. Remember, your rewriter should only modify a tree if it encountered one or more local variable declarations that could be simplified using type inference:
```C#
SyntaxNode newSource = rewriter.Visit(sourceTree.GetRoot());
if (newSource != sourceTree.GetRoot())
{
File.WriteAllText(sourceTree.FilePath, newSource.ToFullString());
}
```
19) You're almost done! There's just once step left. Creating a test **Compilation**. Since you haven't been using type inference at all during this walkthrough it would have made a perfect test case. Unfortunately, creating a Compilation from a C# project file is beyond the scope of this walkthrough. But fortunately, if you've been following instructions very carefully there's hope. Replace the contents of the **CreateTestCompilation** method with the following code. It creates a test compilation that coincidentally matches the project described in this walkthrough:
```C#
String programPath = @"..\..\Program.cs";
String programText = File.ReadAllText(programPath);
SyntaxTree programTree =
CSharpSyntaxTree.ParseText(programText)
.WithFilePath(programPath);
String rewriterPath = @"..\..\TypeInferenceRewriter.cs";
String rewriterText = File.ReadAllText(rewriterPath);
SyntaxTree rewriterTree =
CSharpSyntaxTree.ParseText(rewriterText)
.WithFilePath(rewriterPath);
SyntaxTree[] sourceTrees = { programTree, rewriterTree };
MetadataReference mscorlib =
MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
MetadataReference codeAnalysis =
MetadataReference.CreateFromFile(typeof(SyntaxTree).Assembly.Location);
MetadataReference csharpCodeAnalysis =
MetadataReference.CreateFromFile(typeof(CSharpSyntaxTree).Assembly.Location);
MetadataReference[] references = { mscorlib, codeAnalysis, csharpCodeAnalysis };
return CSharpCompilation.Create("TransformationCS",
sourceTrees,
references,
new CSharpCompilationOptions(
OutputKind.ConsoleApplication));
```
20) Your **Program.cs** file should look like this now:
```C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace TransformationCS
{
internal class Program
{
private static void Main()
{
Compilation test = CreateTestCompilation();
foreach (SyntaxTree sourceTree in test.SyntaxTrees)
{
SemanticModel model = test.GetSemanticModel(sourceTree);
TypeInferenceRewriter rewriter = new TypeInferenceRewriter(model);
SyntaxNode newSource = rewriter.Visit(sourceTree.GetRoot());
if (newSource != sourceTree.GetRoot())
{
File.WriteAllText(sourceTree.FilePath, newSource.ToFullString());
}
}
}
private static Compilation CreateTestCompilation()
{
String programPath = @"..\..\Program.cs";
String programText = File.ReadAllText(programPath);
SyntaxTree programTree =
CSharpSyntaxTree.ParseText(programText)
.WithFilePath(programPath);
String rewriterPath = @"..\..\TypeInferenceRewriter.cs";
String rewriterText = File.ReadAllText(rewriterPath);
SyntaxTree rewriterTree =
CSharpSyntaxTree.ParseText(rewriterText)
.WithFilePath(rewriterPath);
SyntaxTree[] sourceTrees = { programTree, rewriterTree };
MetadataReference mscorlib =
MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
MetadataReference codeAnalysis =
MetadataReference.CreateFromFile(typeof(SyntaxTree).Assembly.Location);
MetadataReference csharpCodeAnalysis =
MetadataReference.CreateFromFile(typeof(CSharpSyntaxTree).Assembly.Location);
MetadataReference[] references = { mscorlib, codeAnalysis, csharpCodeAnalysis };
return CSharpCompilation.Create("TransformationCS",
sourceTrees,
references,
new CSharpCompilationOptions(
OutputKind.ConsoleApplication));
}
}
}
```
21) Cross your fingers and run the project.
* In Visual Studio, choose **Debug -> Start Debugging**.
22) You should be prompted by Visual Studio that the files in your project have changed. Click "**Yes to All**" to reload the modified files. Examine them to observe your awesomeness :)
* Note how much cleaner the code looks without all those explicit and redundant type specifiers.
23) Congratulations! You've just used the **Compiler APIs** to write your own refactoring that searches all files in a C# project for certain syntactic patterns, analyzes the semantics of source code that matches those patterns, and transforms it. You're now officially a Refactoring guru! | ## Prerequisites
* [Visual Studio 2015](https://www.visualstudio.com/downloads)
* [.NET Compiler Platform SDK](https://aka.ms/roslynsdktemplates)
* [Getting Started C# Syntax Analysis](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Getting-Started-C%23-Syntax-Analysis.md)
* [Getting Started C# Semantic Analysis](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Getting-Started-C%23-Semantic-Analysis.md)
## Introduction
This walkthrough builds on concepts and techniques explored in the **Getting Started: Syntax Analysis** and **Getting Started: Semantic Analysis** walkthroughs. If you haven't already, it's strongly advised that you complete those walkthroughs before beginning this one.
In this walkthrough, you'll explore techniques for creating and transforming syntax trees. In combination with the techniques you learned in previous Getting Started walkthroughs, you will create your first command-line refactoring!
## Immutability and the .NET Compiler Platform
A fundamental tenet of the .NET Compiler Platform is immutability. Because immutable data structures cannot be changed after they are created, they can be safely shared and analyzed by multiple consumers simultaneously without the dangers of one tool affecting another in unpredictable ways. No locks or other concurrency measures needed. This applies to syntax trees, compilations, symbols, semantic models, and every other data structure you'll encounter. Instead of modification, new objects are created based on specified differences to the old ones. You'll apply this concept to syntax trees to create tree transformations!
## Creating and "Modifying" Trees
### Creating Nodes with Factory Methods
To create **SyntaxNodes** you must use the **SyntaxFactory** class factory methods. For each kind of node, token, or trivia there is a factory method which can be used to create an instance of that type. By composing nodes hierarchically in a bottom-up fashion you can create syntax trees.
#### Example - Creating a SyntaxNode using Factory Methods
This example uses the **SyntaxFactory** class methods to construct a **NameSyntax** representing the **System.Collections.Generic** namespace.
**NameSyntax** is the base class for four types of names that appear in C#:
* **IdentifierNameSyntax** which represents simple single identifier names like **System** and **Microsoft**
* **GenericNameSyntax** which represents a generic type or method name such as **List<int>**
* **QualifiedNameSyntax** which represents a qualified name of the form ```<left-name>.<right-identifier-or-generic-name>``` such as **System.IO**
* **AliasQualifiedNameSyntax** which represents a name using an assembly extern alias such a **LibraryV2::Foo**
By composing these names together you can create any name which can appear in the C# language.
1) Create a new C# **Stand-Alone Code Analysis Tool** project.
* In Visual Studio, choose **File -> New -> Project...** to display the New Project dialog.
* Under **Visual C# -> Extensibility**, choose **Stand-Alone Code Analysis Tool**.
* Name your project "**ConstructionCS**" and click OK.
2) Add the following using directive to the top of the file to import the factory methods of the **SyntaxFactory** class so that we can use them later without qualifying them:
```C#
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
```
3) Move your cursor to the line containing the **closing brace** of your **Main** method and set a breakpoint there.
* In Visual Studio, choose **Debug -> Toggle Breakpoint**.
4) Run the program.
* In Visual Studio, choose **Debug -> Start Debugging**.
5) First create a simple **IdentifierNameSyntax** representing the name of the **System** namespace and assign it to a variable. As you build up a **QualifiedNameSyntax** from this node you will reuse this variable so declare this variable to be of type **NameSyntax** to allow it to store both types of **SyntaxNode** - **DO NOT** use type inference:
```C#
NameSyntax name = IdentifierName("System");
```
6) Set this statement as the next statement to be executed and execute it.
* Right-click this line and choose **Set Next Statement**.
* In Visual Studio, choose **Debug -> Step Over**, to execute this statement and initialize the new variable.
* You will need to repeat this process for each of the following steps as we introduce new variables and inspect them with the debugger.
7) Open the **Immediate Window**.
* In Visual Studio, choose **Debug -> Windows -> Immediate**.
8) Using the Immediate Window, type the expression **name.ToString()** and press Enter to evaluate it. You should see the string "**System**" as the result.
9) Next, construct a **QualifiedNameSyntax** using this **name** node as the **left** of the name and a new **IdentifierNameSyntax** for the **Collections** namespace as the **right** side of the **QualifiedNameSyntax**:
```C#
name = QualifiedName(name, IdentifierName("Collections"));
```
10) Execute this statement to set the **name** variable to the new **QualifiedNameSyntax** node.
11) Using the Immediate Window, evaluate the expression **name.ToString()**. It should evaluate to "**System.Collections**".
12) Continue this pattern by building another **QualifiedNameSyntax** node for the **Generic** namespace:
```C#
name = QualifiedName(name, IdentifierName("Generic"));
```
13) Execute this statement and again use the Immediate Window to observe that **name.ToString()** now evaluates to the fully qualified name "**System.Collections.Generic**".
### Modifying Nodes with With* and ReplaceNode Methods
Because the syntax trees are immutable, the **Syntax API** provides no direct mechanism for modifying an existing syntax tree after construction. However, the **Syntax API** does provide methods for producing new trees based on specified changes to existing ones. Each concrete class that derives from **SyntaxNode** defines **With*** methods which you can use to specify changes to its child properties. Additionally, the **ReplaceNode** extension method can be used to replace a descendent node in a subtree. Without this method updating a node would also require manually updating its parent to point to the newly created child and repeating this process up the entire tree - a process known as _re-spining_ the tree.
#### Example - Transformations using the With* and ReplaceNode methods.
This example uses the **WithName** method to replace the name in a **UsingDirectiveSyntax** node with the one constructed above.
1) Continuing from the previous example above, add this code to parse a sample code file:
```C#
SyntaxTree tree = CSharpSyntaxTree.ParseText(
@"using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}
}");
var root = (CompilationUnitSyntax)tree.GetRoot();
```
* Note that the file uses the **System.Collections** namespace and not the **System.Collections.Generic** namespace.
2) Execute these statements.
3) Create a new **UsingDirectiveSyntax** node using the **UsingDirectiveSyntax.WithName** method to update the "**System.Collections**" name with the name we created above:
```C#
var oldUsing = root.Usings[1];
var newUsing = oldUsing.WithName(name);
```
4) Using the Immediate Window, evaluate the expression **root.ToString()** and observe that the original tree has not been changed to contain this new updated node.
5) Add the following line using the **ReplaceNode** extension method to create a new tree, replacing the existing import with the updated **newUsing** node, and store the new tree in the existing **root** variable:
```C#
root = root.ReplaceNode(oldUsing, newUsing);
```
6) Execute this statement.
7) Using the Immediate Window evaluate the expression **root.ToString()** this time observing that the tree now correctly imports the **System.Collections.Generic** namespace.
8) Stop the program.
* In Visual Studio, choose **Debug -> Stop debugging**.
9) Your **Program.cs** file should now look like this:
```C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ConstructionCS
{
class Program
{
static void Main(string[] args)
{
NameSyntax name = IdentifierName("System");
name = QualifiedName(name, IdentifierName("Collections"));
name = QualifiedName(name, IdentifierName("Generic"));
SyntaxTree tree = CSharpSyntaxTree.ParseText(
@"using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}
}");
var root = (CompilationUnitSyntax)tree.GetRoot();
var oldUsing = root.Usings[1];
var newUsing = oldUsing.WithName(name);
root = root.ReplaceNode(oldUsing, newUsing);
}
}
}
```
### Transforming Trees using SyntaxRewriters
The **With*** and **ReplaceNode** methods provide convenient means to transform individual branches of a syntax tree. However, often it may be necessary to perform multiple transformations on a syntax tree in concert. The **SyntaxRewriter** class is a subclass of **SyntaxVisitor** which can be used to apply a transformation to a specific type of **SyntaxNode**. It is also possible to apply a set of transformations to multiple types of **SyntaxNode** wherever they appear in a syntax tree. The following example demonstrates this in a naive implementation of a command-line refactoring which removes explicit types in local variable declarations anywhere where type inference could be used. This example makes use of techniques discussed in this walkthrough as well as the **Getting Started: Syntactic Analysis** and **Getting Started: Semantic Analysis** walkthroughs.
#### Example - Creating a SyntaxRewriter to transform syntax trees.
1) Create a new C# **Stand-Alone Code Analysis Tool** project.
* In Visual Studio, choose **File -> New -> Project...** to display the New Project dialog.
* Under **Visual C# -> Extensibility**, choose **Stand-Alone Code Analysis Tool**.
* Name your project "**TransformationCS**" and click OK.
2) Insert the following **using** directive at the top of your **Program.cs** file:
```C#
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
```
3) Add a new class file to the project.
* In Visual Studio, choose **Project -> Add Class...**
* In the "Add New Item" dialog type **TypeInferenceRewriter.cs** as the filename.
4) Add the following using directives.
```C#
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
```
5) Make the **TypeInferenceRewriter** class extend the **CSharpSyntaxRewriter** class:
```C#
public class TypeInferenceRewriter : CSharpSyntaxRewriter
{
```
6) Add the following code to declare a private read-only field to hold a **SemanticModel** and initialize it from the constructor. You will need this field later on to determine where type inference can be used:
```C#
private readonly SemanticModel SemanticModel;
public TypeInferenceRewriter(SemanticModel semanticModel)
{
this.SemanticModel = semanticModel;
}
```
7) Override the **VisitLocalDeclarationStatement** method:
```C#
public override SyntaxNode VisitLocalDeclarationStatement(
LocalDeclarationStatementSyntax node)
{
}
```
* Note that the **VisitLocalDeclarationStatement** method returns a **SyntaxNode**, not **LocalDeclarationStatementSyntax**. In this example you'll return another **LocalDeclarationStatementSyntax** node based on the existing one. In other scenarios one kind of node may be replaced by another kind of node entirely - or even removed.
8) For the purpose of this example you'll only handle local variable declarations, though type inference may be used in **foreach** loops, **for** loops, LINQ expressions, and lambda expressions. Furthermore this rewriter will only transform declarations of the simplest form:
```C#
Type variable = expression;
```
The following forms of variable declarations in C# are either incompatible with type inference or left as an exercise to the reader.
```C#
// Multiple variables in a single declaration.
Type variable1 = expression1,
variable2 = expression2;
// No initializer.
Type variable;
```
9) Add the following code to the body of the **VisitLocalDeclarationStatement** method to skip rewriting these forms of declarations:
```C#
if (node.Declaration.Variables.Count > 1)
{
return node;
}
if (node.Declaration.Variables[0].Initializer == null)
{
return node;
}
```
* Note that returning the **node** parameter unmodified results in no rewriting taking place for that node.
10) Add these statements to extract the type name specified in the declaration and bind it using the **SemanticModel** field to obtain a type symbol.
```C#
VariableDeclaratorSyntax declarator = node.Declaration.Variables.First();
TypeSyntax variableTypeName = node.Declaration.Type;
ITypeSymbol variableType =
(ITypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName)
.Symbol;
```
11) Now, add this statement to bind the initializer expression:
```C#
TypeInfo initializerInfo =
SemanticModel.GetTypeInfo(declarator
.Initializer
.Value);
```
12) Finally, add the following **if** statement to replace the existing type name with the **var** keyword if the type of the initializer expression matches the type specified:
```C#
if (variableType == initializerInfo.Type)
{
TypeSyntax varTypeName =
IdentifierName("var")
.WithLeadingTrivia(
variableTypeName.GetLeadingTrivia())
.WithTrailingTrivia(
variableTypeName.GetTrailingTrivia());
return node.ReplaceNode(variableTypeName, varTypeName);
}
else
{
return node;
}
```
* Note that this conditional is required because if the types don't match the declaration may be casting the initializer expression to a base class or interface. Removing the explicit type in these cases would change the semantics of a program.
* Note also that **var** is specified as an identifier rather than a keyword because **var** is a contextual keyword.
* Note that the leading and trailing trivia (whitespace) is transferred from the old type name to the **var** keyword to maintain vertical whitespace and indentation.
* Note also that it's simpler to use **ReplaceNode** rather than **With*** to transform the **LocalDeclarationStatementSyntax** because the type name is actually the grandchild of the declaration statement.
13) Your **TypeInferenceRewriter.cs** file should now look like this:
```C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace TransformationCS
{
public class TypeInferenceRewriter : CSharpSyntaxRewriter
{
private readonly SemanticModel SemanticModel;
public TypeInferenceRewriter(SemanticModel semanticModel)
{
this.SemanticModel = semanticModel;
}
public override SyntaxNode VisitLocalDeclarationStatement(
LocalDeclarationStatementSyntax node)
{
if (node.Declaration.Variables.Count > 1)
{
return node;
}
if (node.Declaration.Variables[0].Initializer == null)
{
return node;
}
VariableDeclaratorSyntax declarator = node.Declaration.Variables.First();
TypeSyntax variableTypeName = node.Declaration.Type;
ITypeSymbol variableType =
(ITypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName)
.Symbol;
TypeInfo initializerInfo =
SemanticModel.GetTypeInfo(declarator
.Initializer
.Value);
if (variableType == initializerInfo.Type)
{
TypeSyntax varTypeName =
IdentifierName("var")
.WithLeadingTrivia(
variableTypeName.GetLeadingTrivia())
.WithTrailingTrivia(
variableTypeName.GetTrailingTrivia());
return node.ReplaceNode(variableTypeName, varTypeName);
}
else
{
return node;
}
}
}
}
```
14) Return to your **Program.cs** file.
15) To test your **TypeInferenceRewriter** you'll need to create a test **Compilation** to obtain the **SemanticModels** required for the type inference analysis. You'll do this step last. In the meantime declare a placeholder variable representing your test Compilation:
```C#
Compilation test = CreateTestCompilation();
```
16) After pausing a moment you should see an error squiggle appear reporting that no **CreateTestCompilation** method exists. Press **Ctrl+Period** to open the light-bulb and then press Enter to invoke the **Generate Method Stub** command. This will generate a method stub for the **CreateTestCompilation** method in **Program**. You'll come back to fill this in later:

17) Next, write the following code to iterate over each **SyntaxTree** in the test **Compilation.** For each one initialize a new **TypeInferenceRewriter** with the **SemanticModel** for that tree:
```C#
foreach (SyntaxTree sourceTree in test.SyntaxTrees)
{
SemanticModel model = test.GetSemanticModel(sourceTree);
TypeInferenceRewriter rewriter = new TypeInferenceRewriter(model);
}
```
18) Lastly, inside the **foreach** statement you just created, add the following code to perform the transformation on each source tree and conditionally write out the new transformed tree if any edits were made. Remember, your rewriter should only modify a tree if it encountered one or more local variable declarations that could be simplified using type inference:
```C#
SyntaxNode newSource = rewriter.Visit(sourceTree.GetRoot());
if (newSource != sourceTree.GetRoot())
{
File.WriteAllText(sourceTree.FilePath, newSource.ToFullString());
}
```
19) You're almost done! There's just once step left. Creating a test **Compilation**. Since you haven't been using type inference at all during this walkthrough it would have made a perfect test case. Unfortunately, creating a Compilation from a C# project file is beyond the scope of this walkthrough. But fortunately, if you've been following instructions very carefully there's hope. Replace the contents of the **CreateTestCompilation** method with the following code. It creates a test compilation that coincidentally matches the project described in this walkthrough:
```C#
String programPath = @"..\..\Program.cs";
String programText = File.ReadAllText(programPath);
SyntaxTree programTree =
CSharpSyntaxTree.ParseText(programText)
.WithFilePath(programPath);
String rewriterPath = @"..\..\TypeInferenceRewriter.cs";
String rewriterText = File.ReadAllText(rewriterPath);
SyntaxTree rewriterTree =
CSharpSyntaxTree.ParseText(rewriterText)
.WithFilePath(rewriterPath);
SyntaxTree[] sourceTrees = { programTree, rewriterTree };
MetadataReference mscorlib =
MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
MetadataReference codeAnalysis =
MetadataReference.CreateFromFile(typeof(SyntaxTree).Assembly.Location);
MetadataReference csharpCodeAnalysis =
MetadataReference.CreateFromFile(typeof(CSharpSyntaxTree).Assembly.Location);
MetadataReference[] references = { mscorlib, codeAnalysis, csharpCodeAnalysis };
return CSharpCompilation.Create("TransformationCS",
sourceTrees,
references,
new CSharpCompilationOptions(
OutputKind.ConsoleApplication));
```
20) Your **Program.cs** file should look like this now:
```C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace TransformationCS
{
internal class Program
{
private static void Main()
{
Compilation test = CreateTestCompilation();
foreach (SyntaxTree sourceTree in test.SyntaxTrees)
{
SemanticModel model = test.GetSemanticModel(sourceTree);
TypeInferenceRewriter rewriter = new TypeInferenceRewriter(model);
SyntaxNode newSource = rewriter.Visit(sourceTree.GetRoot());
if (newSource != sourceTree.GetRoot())
{
File.WriteAllText(sourceTree.FilePath, newSource.ToFullString());
}
}
}
private static Compilation CreateTestCompilation()
{
String programPath = @"..\..\Program.cs";
String programText = File.ReadAllText(programPath);
SyntaxTree programTree =
CSharpSyntaxTree.ParseText(programText)
.WithFilePath(programPath);
String rewriterPath = @"..\..\TypeInferenceRewriter.cs";
String rewriterText = File.ReadAllText(rewriterPath);
SyntaxTree rewriterTree =
CSharpSyntaxTree.ParseText(rewriterText)
.WithFilePath(rewriterPath);
SyntaxTree[] sourceTrees = { programTree, rewriterTree };
MetadataReference mscorlib =
MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
MetadataReference codeAnalysis =
MetadataReference.CreateFromFile(typeof(SyntaxTree).Assembly.Location);
MetadataReference csharpCodeAnalysis =
MetadataReference.CreateFromFile(typeof(CSharpSyntaxTree).Assembly.Location);
MetadataReference[] references = { mscorlib, codeAnalysis, csharpCodeAnalysis };
return CSharpCompilation.Create("TransformationCS",
sourceTrees,
references,
new CSharpCompilationOptions(
OutputKind.ConsoleApplication));
}
}
}
```
21) Cross your fingers and run the project.
* In Visual Studio, choose **Debug -> Start Debugging**.
22) You should be prompted by Visual Studio that the files in your project have changed. Click "**Yes to All**" to reload the modified files. Examine them to observe your awesomeness :)
* Note how much cleaner the code looks without all those explicit and redundant type specifiers.
23) Congratulations! You've just used the **Compiler APIs** to write your own refactoring that searches all files in a C# project for certain syntactic patterns, analyzes the semantics of source code that matches those patterns, and transforms it. You're now officially a Refactoring guru! | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/Visual Basic/Compiler Breaking Changes - post VS2019.md | ## This document lists known breaking changes in Roslyn in *Visual Studio 2019 Update 1* and beyond compared to *Visual Studio 2019*.
*Breaks are formatted with a monotonically increasing numbered list to allow them to referenced via shorthand (i.e., "known break #1").
Each entry should include a short description of the break, followed by either a link to the issue describing the full details of the break or the full details of the break inline.*
1. https://github.com/dotnet/roslyn/issues/38305
Compiler used to generate incorrect code when a built-in comparison operator producing Boolean? was used
as an operand of a logical short-circuiting operator used as a Boolean expression.
For example, for an expression
```
GetBool3() = True AndAlso GetBool2()
```
and functions
```
Function GetBool2() As Boolean
System.Console.WriteLine("GetBool2")
Return True
End Function
Shared Function GetBool3() As Boolean?
Return Nothing
End Function
```
it is expected that GetBool2 function going to be called. This is also the expected behavior outside of
a Boolean expression, but in context of a Boolean expression the GetBool2 function was not called.
Compiler now generates code that follows language semantics and calls GetBool2 function for the expression above. | ## This document lists known breaking changes in Roslyn in *Visual Studio 2019 Update 1* and beyond compared to *Visual Studio 2019*.
*Breaks are formatted with a monotonically increasing numbered list to allow them to referenced via shorthand (i.e., "known break #1").
Each entry should include a short description of the break, followed by either a link to the issue describing the full details of the break or the full details of the break inline.*
1. https://github.com/dotnet/roslyn/issues/38305
Compiler used to generate incorrect code when a built-in comparison operator producing Boolean? was used
as an operand of a logical short-circuiting operator used as a Boolean expression.
For example, for an expression
```
GetBool3() = True AndAlso GetBool2()
```
and functions
```
Function GetBool2() As Boolean
System.Console.WriteLine("GetBool2")
Return True
End Function
Shared Function GetBool3() As Boolean?
Return Nothing
End Function
```
it is expected that GetBool2 function going to be called. This is also the expected behavior outside of
a Boolean expression, but in context of a Boolean expression the GetBool2 function was not called.
Compiler now generates code that follows language semantics and calls GetBool2 function for the expression above. | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./CODE-OF-CONDUCT.md | # Code of Conduct
This project has adopted the code of conduct defined by the Contributor Covenant
to clarify expected behavior in our community.
For more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).
| # Code of Conduct
This project has adopted the code of conduct defined by the Contributor Covenant
to clarify expected behavior in our community.
For more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/Visual Basic/Overflow In Embedded Runtime.md | ### VB Embedded Runtime inherits overflow checking from the compilation
See https://github.com/dotnet/roslyn/issues/6941. Some VB runtime methods are specified to throw an `OverflowException` when a converted value overflows the target type. When compiling a VB project with the runtime embedded (`/vbruntime*`), the compiler includes the necessary VB runtime helpers into the assembly that is produced. These runtime helpers inherit the overflow checking behavior of the VB.NET project that they are embedded into. As a result, if you both embed the runtime and have overflow checking disabled (`/removeintchecks+`), you will not get the specified exceptions from the runtime helpers. Although technically it is a bug, it has long been the behavior of VB.NET and we have found that customers would be broken by having it fixed, so we do not expect to change this behavior.
``` vb
Sub Main()
Dim s As SByte = -128
Dim o As Object = s
Dim b = CByte(o) ' Should throw OverflowException but does not if you compile with /vbruntime* /removeintchecks+
Console.WriteLine(b)
End Sub
```
| ### VB Embedded Runtime inherits overflow checking from the compilation
See https://github.com/dotnet/roslyn/issues/6941. Some VB runtime methods are specified to throw an `OverflowException` when a converted value overflows the target type. When compiling a VB project with the runtime embedded (`/vbruntime*`), the compiler includes the necessary VB runtime helpers into the assembly that is produced. These runtime helpers inherit the overflow checking behavior of the VB.NET project that they are embedded into. As a result, if you both embed the runtime and have overflow checking disabled (`/removeintchecks+`), you will not get the specified exceptions from the runtime helpers. Although technically it is a bug, it has long been the behavior of VB.NET and we have found that customers would be broken by having it fixed, so we do not expect to change this behavior.
``` vb
Sub Main()
Dim s As SByte = -128
Dim o As Object = s
Dim b = CByte(o) ' Should throw OverflowException but does not if you compile with /vbruntime* /removeintchecks+
Console.WriteLine(b)
End Sub
```
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Tools/dotnet-format/README.md | dotnet-format
=============
Has a new home at [dotnet/format](https://github.com/dotnet/format/) | dotnet-format
=============
Has a new home at [dotnet/format](https://github.com/dotnet/format/) | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Tools/PrepareTests/README.md | # Prepare Tests
## Usage
This tool is meant to prepare our unit tests for efficient upload and download
in our CI pipeline. Our build and test legs run on different machines and hence
they must go through a single upload cycle and many download cycles (per test
scenario).
The output of our build is ~11GB and that does not really lend itself to being
uploaded and downloaded as often as is needed in our tests. Some amount of
curation is needed to make that a practical experience. Even if it's as simple
as deleting all of the non-unit test directories from our `bin` folder and
using the results as the payload.
Our eventual goal though is to be running on Helix and that environment is
optimized for a specific payload structure. Helix consists of Jobs which have
a collection of associated Work Items attached to it. Helix will fan out
Work Items to a series of machines but it will attempt to schedule many
Work Items for the same Job in sequence on the same machine.
To support that scheduling Helix wants the payloads structured in the following
manner:
1. Correlated payload: there is one per job and that is on disk for every
Work Item in the Job. Given that the schedule attempts to re-use the same machine
for Work Items in a Job this means the correlated payload is only downloaded
based on the number of machines used, not the number of Work Items scheduled.
1. Work Item payload: this is downloaded whenever a work item is executed. There
is no re-use here hence this should be as small as possible.
In Roslyn terms the Job is effectively a single unit test DLL and the Work Items
are the partitions that RunTests creates over them. Although in Helix there will
be a lot more partitions.
This tool effectively optimizes our payload for the Helix case. All of the
duplicate files in our build are structured into a single payload. That will
eventually become our correlation payload. What is left in the unit test
directory is unique to that test and hence is about as minimum as it can get.
Given that the end goal is Helix, and we need some sort of test data
manipulation now, I thought it best to just insert that tool here rather than
having an intermediate step.
## Implementation
This tool recognizes that a large number of the artifacts in our output
directory are duplicates. For example consider how many times
Microsoft.CodeAnalysis.dll gets copied around during our build (quite a bit).
The tool uses that information to the following effect:
1. Create a payload directory, `testPayload`, that the tool will populate
1. Crack every DLL in the `bin` directory, read it's MVID, and keep a list
of all file paths which are this MVID
1. Create a directory, `.duplicates`, in `testPayload`
1. For each MVID that has multiple copies create a hard link in `.duplicates`
where the name is the MVID.
1. For every other file in `bin` which is not a duplicate create a hard link
in `.duplicates` with the same relative path.
1. Create a file, `rehydrate.cmd`, that will restore all the duplicate files
by creating a hard link into `.duplicates`. This file will be run on the test
machine.
This reduces our test payload size to ~1.5GB.
*Note*: yes in many ways this is similar to hard linking during build. The
difference being that this is much more effective because build hard linking
isn't perfect and also it creates a handy correlation payload for us. | # Prepare Tests
## Usage
This tool is meant to prepare our unit tests for efficient upload and download
in our CI pipeline. Our build and test legs run on different machines and hence
they must go through a single upload cycle and many download cycles (per test
scenario).
The output of our build is ~11GB and that does not really lend itself to being
uploaded and downloaded as often as is needed in our tests. Some amount of
curation is needed to make that a practical experience. Even if it's as simple
as deleting all of the non-unit test directories from our `bin` folder and
using the results as the payload.
Our eventual goal though is to be running on Helix and that environment is
optimized for a specific payload structure. Helix consists of Jobs which have
a collection of associated Work Items attached to it. Helix will fan out
Work Items to a series of machines but it will attempt to schedule many
Work Items for the same Job in sequence on the same machine.
To support that scheduling Helix wants the payloads structured in the following
manner:
1. Correlated payload: there is one per job and that is on disk for every
Work Item in the Job. Given that the schedule attempts to re-use the same machine
for Work Items in a Job this means the correlated payload is only downloaded
based on the number of machines used, not the number of Work Items scheduled.
1. Work Item payload: this is downloaded whenever a work item is executed. There
is no re-use here hence this should be as small as possible.
In Roslyn terms the Job is effectively a single unit test DLL and the Work Items
are the partitions that RunTests creates over them. Although in Helix there will
be a lot more partitions.
This tool effectively optimizes our payload for the Helix case. All of the
duplicate files in our build are structured into a single payload. That will
eventually become our correlation payload. What is left in the unit test
directory is unique to that test and hence is about as minimum as it can get.
Given that the end goal is Helix, and we need some sort of test data
manipulation now, I thought it best to just insert that tool here rather than
having an intermediate step.
## Implementation
This tool recognizes that a large number of the artifacts in our output
directory are duplicates. For example consider how many times
Microsoft.CodeAnalysis.dll gets copied around during our build (quite a bit).
The tool uses that information to the following effect:
1. Create a payload directory, `testPayload`, that the tool will populate
1. Crack every DLL in the `bin` directory, read it's MVID, and keep a list
of all file paths which are this MVID
1. Create a directory, `.duplicates`, in `testPayload`
1. For each MVID that has multiple copies create a hard link in `.duplicates`
where the name is the MVID.
1. For every other file in `bin` which is not a duplicate create a hard link
in `.duplicates` with the same relative path.
1. Create a file, `rehydrate.cmd`, that will restore all the duplicate files
by creating a hard link into `.duplicates`. This file will be run on the test
machine.
This reduces our test payload size to ~1.5GB.
*Note*: yes in many ways this is similar to hard linking during build. The
difference being that this is much more effective because build hard linking
isn't perfect and also it creates a handy correlation payload for us. | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/infrastructure/msbuild.md | # MSBuild usage
## Supporting different MSBuilds
This repo must support the ability to build with a number of different MSBuild configurations:
- MSBuild via Visual Studio: this happens when developers open Roslyn.sln in Visual Studio and execute the build action. This uses desktop MSBuild to drive the solution.
- MSBuild via CLI: the cross platform portions of the repo are built via the CLI. This is a subset of the code contained in Roslyn.sln.
- MSBuild xcopy: an xcopyable version of MSBuild that is used to run many of our Jenkins legs. It allows Roslyn to build and run tests on a completely fresh Windows image (no pre-reqs). The [xcopy-msbuild](https://github.com/jaredpar/xcopy-msbuild) project is responsible for building this image.
- BuildTools: this is a collection of tools produced by [dotnet/buildtools](https://github.com/dotnet/buildtools) which build a number of dotnet repos.
This places a small burden on our repo to keep our build props / targets files simple to avoid any odd conflicts. This is rarely an issue at this point.
## Picking MSBuild
Given our repo supports multiple MSBuild versions, it must pick one to use when building, restoring, etc ... The preference list is as follows:
1. Developer command prompt: when invoked from inside a developer command prompt the associated MSBuild will be used.
1. Machine MSBuild: when invoked on a machine with MSBuild 15.0 installed, the first mentioned instance will be used.
1. XCopy MSBuild: fallback when no other option is available
| # MSBuild usage
## Supporting different MSBuilds
This repo must support the ability to build with a number of different MSBuild configurations:
- MSBuild via Visual Studio: this happens when developers open Roslyn.sln in Visual Studio and execute the build action. This uses desktop MSBuild to drive the solution.
- MSBuild via CLI: the cross platform portions of the repo are built via the CLI. This is a subset of the code contained in Roslyn.sln.
- MSBuild xcopy: an xcopyable version of MSBuild that is used to run many of our Jenkins legs. It allows Roslyn to build and run tests on a completely fresh Windows image (no pre-reqs). The [xcopy-msbuild](https://github.com/jaredpar/xcopy-msbuild) project is responsible for building this image.
- BuildTools: this is a collection of tools produced by [dotnet/buildtools](https://github.com/dotnet/buildtools) which build a number of dotnet repos.
This places a small burden on our repo to keep our build props / targets files simple to avoid any odd conflicts. This is rarely an issue at this point.
## Picking MSBuild
Given our repo supports multiple MSBuild versions, it must pick one to use when building, restoring, etc ... The preference list is as follows:
1. Developer command prompt: when invoked from inside a developer command prompt the associated MSBuild will be used.
1. Machine MSBuild: when invoked on a machine with MSBuild 15.0 installed, the first mentioned instance will be used.
1. XCopy MSBuild: fallback when no other option is available
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/Design/README.md | Design Docs
===========
This directory is a place for design documents for the Roslyn compilers.
| Design Docs
===========
This directory is a place for design documents for the Roslyn compilers.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/wildcards.work.md | work items remaining for wildcards
==================================
### Specs
- [ ] Gather together a specification document
- [ ] Language behavior (e.g. [this](https://github.com/dotnet/roslyn/issues/14862) and [this](https://github.com/dotnet/roslyn/issues/14794) and [this](https://github.com/dotnet/roslyn/issues/14832))
- [ ] [SemanticModel behavior](https://gist.github.com/gafter/ab10e413efe3a066209cbf14cb874988) (see also [here](https://gist.github.com/gafter/37305d619bd04511f4f66b86f6f2d3a5))
- [ ] Warnings (for expression variables declared but not used)
- [x] Debugging (value discarded is not visible in debugger)
### Compiler
- [x] Syntax model changes
- [x] Symbol changes
- [x] Parsing for the short-form wildcard pattern `_`
- [x] Implement binding of wildcards
- [x] In a pattern
- [x] In a deconstruction declaration
- [x] In a deconstruction assignment expression
- [ ] In an out argument (in every argument context)
- [x] Both the long form `var _` and the short form `_`
- [x] Type inference for wildcards in each context
- [ ] Implement semantic model changes
- [ ] `GetTypeInfo` of a wildcard expression `_` should be the type of the discarded value
- [ ] `GetSymbolInfo` of a wildcard expression `_` should be an `IDiscardedSymbol`
- [x] Implement lowering of wildcards
- [x] In a pattern
- [x] In a deconstruction declaration
- [x] In a deconstruction assignment expression
- [ ] In an out argument (in each argument context)
### Testing
- [ ] Symbol tests
- [ ] Syntax tests
- [ ] SemanticModel tests
- [ ] Language static semantic tests
- [ ] Runtime behavioral tests
- [ ] PDB tests
- [ ] Scripting tests
- [ ] EE tests
- [ ] In a pattern context
- [ ] In a deconstruction declaration context
- [ ] In a deconstruction assignment expression context
- [ ] In an out argument (in every argument context)
- [ ] Both the long form `var _` and the short form `_`, where permitted
- [ ] In the long/short form when there is/not a conflicting name in scope
| work items remaining for wildcards
==================================
### Specs
- [ ] Gather together a specification document
- [ ] Language behavior (e.g. [this](https://github.com/dotnet/roslyn/issues/14862) and [this](https://github.com/dotnet/roslyn/issues/14794) and [this](https://github.com/dotnet/roslyn/issues/14832))
- [ ] [SemanticModel behavior](https://gist.github.com/gafter/ab10e413efe3a066209cbf14cb874988) (see also [here](https://gist.github.com/gafter/37305d619bd04511f4f66b86f6f2d3a5))
- [ ] Warnings (for expression variables declared but not used)
- [x] Debugging (value discarded is not visible in debugger)
### Compiler
- [x] Syntax model changes
- [x] Symbol changes
- [x] Parsing for the short-form wildcard pattern `_`
- [x] Implement binding of wildcards
- [x] In a pattern
- [x] In a deconstruction declaration
- [x] In a deconstruction assignment expression
- [ ] In an out argument (in every argument context)
- [x] Both the long form `var _` and the short form `_`
- [x] Type inference for wildcards in each context
- [ ] Implement semantic model changes
- [ ] `GetTypeInfo` of a wildcard expression `_` should be the type of the discarded value
- [ ] `GetSymbolInfo` of a wildcard expression `_` should be an `IDiscardedSymbol`
- [x] Implement lowering of wildcards
- [x] In a pattern
- [x] In a deconstruction declaration
- [x] In a deconstruction assignment expression
- [ ] In an out argument (in each argument context)
### Testing
- [ ] Symbol tests
- [ ] Syntax tests
- [ ] SemanticModel tests
- [ ] Language static semantic tests
- [ ] Runtime behavioral tests
- [ ] PDB tests
- [ ] Scripting tests
- [ ] EE tests
- [ ] In a pattern context
- [ ] In a deconstruction declaration context
- [ ] In a deconstruction assignment expression context
- [ ] In an out argument (in every argument context)
- [ ] Both the long form `var _` and the short form `_`, where permitted
- [ ] In the long/short form when there is/not a conflicting name in scope
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/contributing/Building, Debugging, and Testing on Unix.md | # Building, Debugging and Testing on Unix
This guide is meant to help developers setup an environment for debugging / contributing to Roslyn from Linux.
Particularly for developers who aren't experienced with .NET Core development on Linux.
## Working with the code
1. Ensure the commands `git` and `curl` are available
1. Clone [email protected]:dotnet/roslyn.git
1. Run `./build.sh --restore`
1. Run `./build.sh --build`
## Working in Visual Studio Code
1. Install [VS Code](https://code.visualstudio.com/Download)
- After you install VS Code, install the [C# extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp)
- Important tip: You can look up editor commands by name by hitting *Ctrl+Shift+P*, or by hitting *Ctrl+P* and typing a `>` character. This will help you get familiar with editor commands mentioned below. On a Mac, use *⌘* instead of *Ctrl*.
2. Install a recent preview [.NET Core SDK](https://dotnet.microsoft.com/download/dotnet-core). At time of writing, Roslyn uses .NET 5 preview 8. The exact version in use is recorded in our [global.json](https://github.com/dotnet/roslyn/blob/main/global.json) file.
3. You can build from VS Code by running the *Run Build Task* command, then selecting an appropriate task such as *build* or *build current project* (the latter builds the containing project for the current file you're viewing in the editor).
4. You can run tests from VS Code by opening a test class in the editor, then using the *Run Tests in Context* and *Debug Tests in Context* editor commands. You may want to bind these commands to keyboard shortcuts that match their Visual Studio equivalents (**Ctrl+R, T** for *Run Tests in Context* and **Ctrl+R, Ctrl+T** for *Debug Tests in Context*).
## Running Tests
The unit tests can be executed by running `./build.sh --test`.
To run all tests in a single project, it's recommended to use the `dotnet test path/to/project` command.
## GitHub
The best way to clone and push is to use SSH. On Windows you typically use HTTPS and this is not directly compatible
with two factor authentication (requires a PAT). The SSH setup is much simpler and GitHub has a great HOWTO for
getting this setup.
https://help.github.com/articles/connecting-to-github-with-ssh/
## Debugging test failures
The best way to debug is using lldb with the SOS plugin. This is the same SOS as used in WinDbg and if you're familiar
with it then lldb debugging will be pretty straight forward.
The [dotnet/diagnostics](https://github.com/dotnet/diagnostics) repo has more information:
- [Getting LLDB](https://github.com/dotnet/diagnostics/blob/main/documentation/lldb/linux-instructions.md)
- [Installing SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/installing-sos-instructions.md)
- [Using SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/sos-debugging-extension.md)
CoreCLR also has some guidelines for specific Linux debugging scenarios:
- https://github.com/dotnet/coreclr/blob/main/Documentation/botr/xplat-minidump-generation.md
- https://github.com/dotnet/coreclr/blob/main/Documentation/building/debugging-instructions.md#debugging-core-dumps-with-lldb.
Corrections:
- LLDB and createdump must be run as root
- `dotnet tool install -g dotnet-symbol` must be run from `$HOME`
### Core Dumps
The CoreClr does not used the standard core dumping mechanisms on Linux. Instead you must specify via
environment variables that you want a core dump to be produced. The simplest setup is to do the following:
```
> export COMPlus_DbgEnableMiniDump=1
> export COMPlus_DbgMiniDumpType=4
```
This will cause full memory dumps to be produced which can then be loaded into LLDB.
A preview of [dotnet-dump](https://github.com/dotnet/diagnostics/blob/main/documentation/dotnet-dump-instructions.md) is also available for interactively creating and analyzing dumps.
### GC stress failures
When you suspect there is a GC failure related to your test then you can use the following environment variables
to help track it down.
```
> export COMPlus_HeapVerify=1
> export COMPlus_gcConcurrent=1
```
The `COMPlus_HeapVerify` variable causes GC to run a verification routine on every entry and exit. Will crash with
a more actionable trace for the GC team.
The `COMPlus_gcConcurrent` variable removes concurrency in the GC. This helps isolate whether this is a GC failure
or memory corruption outside the GC. This should be set after you use `COMPLUS_HeapVerify` to determine it is
indeed crashing in the GC.
Note: this variables can also be used on Windows as well.
## Ubuntu 18.04
The recommended OS for developing Roslyn is Ubuntu 18.04. This guide was written using Ubuntu 18.04 but should be
applicable to most Linux environments. Ubuntu 18.04 was chosen here due to it's support for enhanced VMs in Hyper-V.
This makes it easier to use from a Windows machine: full screen, copy / paste, etc ...
### Hyper-V
Hyper-V has a builtin Ubuntu 18.04 image which supports enhanced mode. Here is a tutorial for creating
such an image:
https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/quick-create-virtual-machine
When following this make sure to:
1. Click Installation Source and uncheck "Windows Secure Boot"
1. Complete the Ubuntu installation wizard. Full screen mode won't be available until this is done.
Overall this takes about 5-10 minutes to complete.
### Source Link
Many of the repositories that need to be built use source link and it crashes on Ubuntu 18.04 due to dependency changes.
To disable source link add the following to the `Directory.Build.props` file in the root of the repository.
``` xml
<EnableSourceControlManagerQueries>false</EnableSourceControlManagerQueries>
<EnableSourceLink>false</EnableSourceLink>
<DeterministicSourcePaths>false</DeterministicSourcePaths>
```
### Prerequisites
Make sure to install the following via `apt install`
- clang
- lldb
- cmake
- xrdp
| # Building, Debugging and Testing on Unix
This guide is meant to help developers setup an environment for debugging / contributing to Roslyn from Linux.
Particularly for developers who aren't experienced with .NET Core development on Linux.
## Working with the code
1. Ensure the commands `git` and `curl` are available
1. Clone [email protected]:dotnet/roslyn.git
1. Run `./build.sh --restore`
1. Run `./build.sh --build`
## Working in Visual Studio Code
1. Install [VS Code](https://code.visualstudio.com/Download)
- After you install VS Code, install the [C# extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp)
- Important tip: You can look up editor commands by name by hitting *Ctrl+Shift+P*, or by hitting *Ctrl+P* and typing a `>` character. This will help you get familiar with editor commands mentioned below. On a Mac, use *⌘* instead of *Ctrl*.
2. Install a recent preview [.NET Core SDK](https://dotnet.microsoft.com/download/dotnet-core). At time of writing, Roslyn uses .NET 5 preview 8. The exact version in use is recorded in our [global.json](https://github.com/dotnet/roslyn/blob/main/global.json) file.
3. You can build from VS Code by running the *Run Build Task* command, then selecting an appropriate task such as *build* or *build current project* (the latter builds the containing project for the current file you're viewing in the editor).
4. You can run tests from VS Code by opening a test class in the editor, then using the *Run Tests in Context* and *Debug Tests in Context* editor commands. You may want to bind these commands to keyboard shortcuts that match their Visual Studio equivalents (**Ctrl+R, T** for *Run Tests in Context* and **Ctrl+R, Ctrl+T** for *Debug Tests in Context*).
## Running Tests
The unit tests can be executed by running `./build.sh --test`.
To run all tests in a single project, it's recommended to use the `dotnet test path/to/project` command.
## GitHub
The best way to clone and push is to use SSH. On Windows you typically use HTTPS and this is not directly compatible
with two factor authentication (requires a PAT). The SSH setup is much simpler and GitHub has a great HOWTO for
getting this setup.
https://help.github.com/articles/connecting-to-github-with-ssh/
## Debugging test failures
The best way to debug is using lldb with the SOS plugin. This is the same SOS as used in WinDbg and if you're familiar
with it then lldb debugging will be pretty straight forward.
The [dotnet/diagnostics](https://github.com/dotnet/diagnostics) repo has more information:
- [Getting LLDB](https://github.com/dotnet/diagnostics/blob/main/documentation/lldb/linux-instructions.md)
- [Installing SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/installing-sos-instructions.md)
- [Using SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/sos-debugging-extension.md)
CoreCLR also has some guidelines for specific Linux debugging scenarios:
- https://github.com/dotnet/coreclr/blob/main/Documentation/botr/xplat-minidump-generation.md
- https://github.com/dotnet/coreclr/blob/main/Documentation/building/debugging-instructions.md#debugging-core-dumps-with-lldb.
Corrections:
- LLDB and createdump must be run as root
- `dotnet tool install -g dotnet-symbol` must be run from `$HOME`
### Core Dumps
The CoreClr does not used the standard core dumping mechanisms on Linux. Instead you must specify via
environment variables that you want a core dump to be produced. The simplest setup is to do the following:
```
> export COMPlus_DbgEnableMiniDump=1
> export COMPlus_DbgMiniDumpType=4
```
This will cause full memory dumps to be produced which can then be loaded into LLDB.
A preview of [dotnet-dump](https://github.com/dotnet/diagnostics/blob/main/documentation/dotnet-dump-instructions.md) is also available for interactively creating and analyzing dumps.
### GC stress failures
When you suspect there is a GC failure related to your test then you can use the following environment variables
to help track it down.
```
> export COMPlus_HeapVerify=1
> export COMPlus_gcConcurrent=1
```
The `COMPlus_HeapVerify` variable causes GC to run a verification routine on every entry and exit. Will crash with
a more actionable trace for the GC team.
The `COMPlus_gcConcurrent` variable removes concurrency in the GC. This helps isolate whether this is a GC failure
or memory corruption outside the GC. This should be set after you use `COMPLUS_HeapVerify` to determine it is
indeed crashing in the GC.
Note: this variables can also be used on Windows as well.
## Ubuntu 18.04
The recommended OS for developing Roslyn is Ubuntu 18.04. This guide was written using Ubuntu 18.04 but should be
applicable to most Linux environments. Ubuntu 18.04 was chosen here due to it's support for enhanced VMs in Hyper-V.
This makes it easier to use from a Windows machine: full screen, copy / paste, etc ...
### Hyper-V
Hyper-V has a builtin Ubuntu 18.04 image which supports enhanced mode. Here is a tutorial for creating
such an image:
https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/quick-create-virtual-machine
When following this make sure to:
1. Click Installation Source and uncheck "Windows Secure Boot"
1. Complete the Ubuntu installation wizard. Full screen mode won't be available until this is done.
Overall this takes about 5-10 minutes to complete.
### Source Link
Many of the repositories that need to be built use source link and it crashes on Ubuntu 18.04 due to dependency changes.
To disable source link add the following to the `Directory.Build.props` file in the root of the repository.
``` xml
<EnableSourceControlManagerQueries>false</EnableSourceControlManagerQueries>
<EnableSourceLink>false</EnableSourceLink>
<DeterministicSourcePaths>false</DeterministicSourcePaths>
```
### Prerequisites
Make sure to install the following via `apt install`
- clang
- lldb
- cmake
- xrdp
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/Core/Portable/DiaSymReader/Readme.md | The content of this directory is a copy of a subset of https://github.com/dotnet/symreader/tree/main/src/Microsoft.DiaSymReader.
The only difference is in top-level class visibility (public in DiaSymReader, internal here). | The content of this directory is a copy of a subset of https://github.com/dotnet/symreader/tree/main/src/Microsoft.DiaSymReader.
The only difference is in top-level class visibility (public in DiaSymReader, internal here). | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/UsedAssemblyReferences.md | Used Assembly References
=========================
The *Used Assembly References* feature provides a ```GetUsedAssemblyReferences``` API on a ```Compilation``` to obtain a set
of metadata assembly references that are considered to be used by the compilation. For example, if a type declared in a
referenced assembly is referenced in source code within the compilation, the reference is considered to be used. Etc.
See https://github.com/dotnet/roslyn/issues/37768 for more information. | Used Assembly References
=========================
The *Used Assembly References* feature provides a ```GetUsedAssemblyReferences``` API on a ```Compilation``` to obtain a set
of metadata assembly references that are considered to be used by the compilation. For example, if a type declared in a
referenced assembly is referenced in source code within the compilation, the reference is considered to be used. Etc.
See https://github.com/dotnet/roslyn/issues/37768 for more information. | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/specs/CSharp 6/Better Betterness.md | # Better Betterness
"Better Betterness" is a language change to C# 6, present in the Roslyn C# compiler that shipped as part of Visual Studio 2015 and later. This change is applied in the compiler no matter what language version is specified on the command-line. Consequently we apply these new rules even when you are using the compiler as a C# 5 compiler using `/langver:5`.
Here are relevant sections of the modified language spec:
### 7.5.3.3 Better conversion from expression
Given an implicit conversion C<sub>1</sub> that converts from an expression E to a type T<sub>1</sub>, and an implicit conversion C<sub>2</sub> that converts from an expression E to a type T<sub>2</sub>, C<sub>1</sub> is a ***better conversion*** than C<sub>2</sub> if E does not exactly match T<sub>2</sub> and one of the following holds:
- E exactly matches T<sub>1</sub> (§7.5.3.4)
- T<sub>1</sub> is a better conversion target than T<sub>2</sub> (§7.5.3.5)
### 7.5.3.4 Exactly matching Expression
Given an expression E and a type T, E ***exactly matches*** T is one of the following holds:
- E has a type S, and an identity conversion exists from S to T
- E is an anonymous function, T is either a delegate type D or an expression tree type Expression<D> and one of the following holds:
- An inferred return type X exists for E in the context of the parameter list of D (§7.5.2.12), and an identity conversion exists from X to the return type of D
- Either E is non-async and D has a return type Y or E is async and D has a return type Task<Y>, and one of the following holds:
- The body of E is an expression that exactly matches Y
- The body of E is a statement block where every return statement returns an expression that exactly matches Y
### 7.5.3.5 Better conversion target
Given two different types T<sub>1</sub> and T<sub>2</sub>, T<sub>1</sub> is a ***better conversion target*** than T<sub>2</sub> if
- An implicit conversion from T<sub>1</sub> to T<sub>2</sub> exists
- T<sub>1</sub> is either a delegate type D<sub>1</sub> or an expression tree type Expression<D<sub>1</sub>>, T<sub>2</sub> is either a delegate type D<sub>2</sub> or an expression tree type Expression<D<sub>2</sub>>, D<sub>1</sub> has a return type S<sub>1</sub> and one of the following holds:
- D<sub>2</sub> is void returning
- D<sub>2</sub> has a return type S<sub>2</sub>, and S<sub>1</sub> is a better conversion target than S<sub>2</sub>
- T<sub>1</sub> is Task<S<sub>1</sub>>, T<sub>2</sub> is Task<S<sub>2</sub>>, and S<sub>1</sub> is a better conversion target than S<sub>2</sub>
- T<sub>1</sub> is S<sub>1</sub> or S<sub>1</sub>? where S<sub>1</sub> is a signed integral type, and T<sub>2</sub> is S<sub>2</sub> or S<sub>2</sub>? where S<sub>2</sub> is an unsigned integral type. Specifically:
- S<sub>1</sub> is `sbyte` and S<sub>2</sub> is `byte`, `ushort`, `uint`, or `ulong`
- S<sub>1</sub> is `short` and S<sub>2</sub> is `ushort`, `uint`, or `ulong`
- S<sub>1</sub> is `int` and S<sub>2</sub> is `uint`, or `ulong`
- S<sub>1</sub> is `long` and S<sub>2</sub> is `ulong`
##### Explanation
There no longer is a concept of “better conversion from type”.
Note that the new rules remove quite a bit of special casing that was based on the shape of the expression. With these new rules the expression matters only insofar as it is a “perfect match” for the type – which always takes priority. (This maintains the property that you can always choose a specific overload by casting the arguments to the precise types expected in that overload).
“Exactly matches” is primarily complicated by logic to “see through” lambdas and match the return type. The old rules would allow you to see through exactly 1 layer of lambdas (which seems completely arbitrary), whereas they are now generalized to any number:
- `7` exactly matches `int`
- `() => 7` exactly matches `Func<int>`
- `() => () => 7` exactly matches `Func<Func<int>>` but didn’t in earlier releases!!!
The rules that “see through” delegates and tasks now work regardless of the shape of the argument expression, where they used to require things being lambdas and async. So they are now factored into “Better conversion target” which ignores the expression. The rules for nullable were always lacking, and we’ve completed those – some of this was already “accidentally” implemented in the old compiler, most is new behavior.
##### Compatibility fix
In VS2015 Update 2 (Roslyn release 1.2), we detected and fixed a subtle incompatibility in the changed overload resolution rules. See https://github.com/dotnet/roslyn/issues/6560 for an example of affected code. To fix this, the second bullet of §7.5.3.5, above, is modified as follows:
> In case of a method group conversion (§6.6) for the corresponding argument, if a better conversion target (§7.5.3.5 Better conversion target), is a delegate type that is not compatible (§15.2 Delegate compatibility) with the single best method from the method group (§6.6 Method group conversions), then neither delegate type is better.
This explanation is necessarily a bit informal (e.g. there is no "corresponding argument" in §7.5.3.5); factoring it into the specification will require reorganizing the spec.
For reference:
### 15.2 Delegate compatibility
A method or delegate M is compatible with a delegate type D if all of the following are true:
- D and M have the same number of parameters, and each parameter in D has the same ref or out modifiers as the corresponding parameter in M.
- For each value parameter (a parameter with no ref or out modifier), an identity conversion (§6.1.1) or implicit reference conversion (§6.1.6) exists from the parameter type in D to the corresponding parameter type in M.
- For each ref or out parameter, the parameter type in D is the same as the parameter type in M.
- An identity or implicit reference conversion exists from the return type of M to the return type of D.
### 6.6 Method group conversions
...
- A conversion is considered to exist if the algorithm of §7.6.5.1 produces a single best method M having the same number of parameters as D.
...
| # Better Betterness
"Better Betterness" is a language change to C# 6, present in the Roslyn C# compiler that shipped as part of Visual Studio 2015 and later. This change is applied in the compiler no matter what language version is specified on the command-line. Consequently we apply these new rules even when you are using the compiler as a C# 5 compiler using `/langver:5`.
Here are relevant sections of the modified language spec:
### 7.5.3.3 Better conversion from expression
Given an implicit conversion C<sub>1</sub> that converts from an expression E to a type T<sub>1</sub>, and an implicit conversion C<sub>2</sub> that converts from an expression E to a type T<sub>2</sub>, C<sub>1</sub> is a ***better conversion*** than C<sub>2</sub> if E does not exactly match T<sub>2</sub> and one of the following holds:
- E exactly matches T<sub>1</sub> (§7.5.3.4)
- T<sub>1</sub> is a better conversion target than T<sub>2</sub> (§7.5.3.5)
### 7.5.3.4 Exactly matching Expression
Given an expression E and a type T, E ***exactly matches*** T is one of the following holds:
- E has a type S, and an identity conversion exists from S to T
- E is an anonymous function, T is either a delegate type D or an expression tree type Expression<D> and one of the following holds:
- An inferred return type X exists for E in the context of the parameter list of D (§7.5.2.12), and an identity conversion exists from X to the return type of D
- Either E is non-async and D has a return type Y or E is async and D has a return type Task<Y>, and one of the following holds:
- The body of E is an expression that exactly matches Y
- The body of E is a statement block where every return statement returns an expression that exactly matches Y
### 7.5.3.5 Better conversion target
Given two different types T<sub>1</sub> and T<sub>2</sub>, T<sub>1</sub> is a ***better conversion target*** than T<sub>2</sub> if
- An implicit conversion from T<sub>1</sub> to T<sub>2</sub> exists
- T<sub>1</sub> is either a delegate type D<sub>1</sub> or an expression tree type Expression<D<sub>1</sub>>, T<sub>2</sub> is either a delegate type D<sub>2</sub> or an expression tree type Expression<D<sub>2</sub>>, D<sub>1</sub> has a return type S<sub>1</sub> and one of the following holds:
- D<sub>2</sub> is void returning
- D<sub>2</sub> has a return type S<sub>2</sub>, and S<sub>1</sub> is a better conversion target than S<sub>2</sub>
- T<sub>1</sub> is Task<S<sub>1</sub>>, T<sub>2</sub> is Task<S<sub>2</sub>>, and S<sub>1</sub> is a better conversion target than S<sub>2</sub>
- T<sub>1</sub> is S<sub>1</sub> or S<sub>1</sub>? where S<sub>1</sub> is a signed integral type, and T<sub>2</sub> is S<sub>2</sub> or S<sub>2</sub>? where S<sub>2</sub> is an unsigned integral type. Specifically:
- S<sub>1</sub> is `sbyte` and S<sub>2</sub> is `byte`, `ushort`, `uint`, or `ulong`
- S<sub>1</sub> is `short` and S<sub>2</sub> is `ushort`, `uint`, or `ulong`
- S<sub>1</sub> is `int` and S<sub>2</sub> is `uint`, or `ulong`
- S<sub>1</sub> is `long` and S<sub>2</sub> is `ulong`
##### Explanation
There no longer is a concept of “better conversion from type”.
Note that the new rules remove quite a bit of special casing that was based on the shape of the expression. With these new rules the expression matters only insofar as it is a “perfect match” for the type – which always takes priority. (This maintains the property that you can always choose a specific overload by casting the arguments to the precise types expected in that overload).
“Exactly matches” is primarily complicated by logic to “see through” lambdas and match the return type. The old rules would allow you to see through exactly 1 layer of lambdas (which seems completely arbitrary), whereas they are now generalized to any number:
- `7` exactly matches `int`
- `() => 7` exactly matches `Func<int>`
- `() => () => 7` exactly matches `Func<Func<int>>` but didn’t in earlier releases!!!
The rules that “see through” delegates and tasks now work regardless of the shape of the argument expression, where they used to require things being lambdas and async. So they are now factored into “Better conversion target” which ignores the expression. The rules for nullable were always lacking, and we’ve completed those – some of this was already “accidentally” implemented in the old compiler, most is new behavior.
##### Compatibility fix
In VS2015 Update 2 (Roslyn release 1.2), we detected and fixed a subtle incompatibility in the changed overload resolution rules. See https://github.com/dotnet/roslyn/issues/6560 for an example of affected code. To fix this, the second bullet of §7.5.3.5, above, is modified as follows:
> In case of a method group conversion (§6.6) for the corresponding argument, if a better conversion target (§7.5.3.5 Better conversion target), is a delegate type that is not compatible (§15.2 Delegate compatibility) with the single best method from the method group (§6.6 Method group conversions), then neither delegate type is better.
This explanation is necessarily a bit informal (e.g. there is no "corresponding argument" in §7.5.3.5); factoring it into the specification will require reorganizing the spec.
For reference:
### 15.2 Delegate compatibility
A method or delegate M is compatible with a delegate type D if all of the following are true:
- D and M have the same number of parameters, and each parameter in D has the same ref or out modifiers as the corresponding parameter in M.
- For each value parameter (a parameter with no ref or out modifier), an identity conversion (§6.1.1) or implicit reference conversion (§6.1.6) exists from the parameter type in D to the corresponding parameter type in M.
- For each ref or out parameter, the parameter type in D is the same as the parameter type in M.
- An identity or implicit reference conversion exists from the return type of M to the return type of D.
### 6.6 Method group conversions
...
- A conversion is considered to exist if the algorithm of §7.6.5.1 produces a single best method M having the same number of parameters as D.
...
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/ide/test-plans/source-generators.md | ## Features Opening New Windows
1. Locate a use of a generated symbol in the project, and invoke Go to Definition.
- [ ] It works.
2. Locate a use of a generated symbol in the project, and invoke Go to Implementation.
- [ ] It works.
3. Locate a use of a generated symbol in the project, and invoke Find References.
- [ ] References to the generated symbol in regular code are located.
- [ ] References to the generated symbol in generated code are located.
## Features That Are Blocked
1. Locate a use of a generated method in a project, and invoke Rename with Ctrl+R Ctrl+R.
- [ ] It should be blocked.
2. Locate a use of a generated method in a project, change the name at the use site.
- [ ] **[NOT WORKING YET]** Rename tracking should not trigger.
## Navigating within a Generated Document
1. Invoke Go to Definition on a generated symbol to open a source generated file.
- [ ] **[NOT WORKING YET]** The navigation bar on the top of the file shows the project that contains the generated source
2. Invoke Find References on the symbol we navigated to.
- [ ] **[NOT WORKING YET]** The original reference should appear in find references.
3. Click on some symbol used more than once in a generated file.
- [ ] Highlight references should highlight all uses in the file.
## Window > New Window Support
1. Invoke Go to Definition to open a source-generated file. Then do Window > New Window to ensure that the new window is set up correctly.
- [ ] It's read only.
- [ ] The title and caption are correct.
2. Remove the source generator from the project.
- [ ] Confirm the first window correctly gets an info bar showing the file is no longer valid.
- [ ] Confirm the second window correctly gets an info bar showing the file is no longer valid.
| ## Features Opening New Windows
1. Locate a use of a generated symbol in the project, and invoke Go to Definition.
- [ ] It works.
2. Locate a use of a generated symbol in the project, and invoke Go to Implementation.
- [ ] It works.
3. Locate a use of a generated symbol in the project, and invoke Find References.
- [ ] References to the generated symbol in regular code are located.
- [ ] References to the generated symbol in generated code are located.
## Features That Are Blocked
1. Locate a use of a generated method in a project, and invoke Rename with Ctrl+R Ctrl+R.
- [ ] It should be blocked.
2. Locate a use of a generated method in a project, change the name at the use site.
- [ ] **[NOT WORKING YET]** Rename tracking should not trigger.
## Navigating within a Generated Document
1. Invoke Go to Definition on a generated symbol to open a source generated file.
- [ ] **[NOT WORKING YET]** The navigation bar on the top of the file shows the project that contains the generated source
2. Invoke Find References on the symbol we navigated to.
- [ ] **[NOT WORKING YET]** The original reference should appear in find references.
3. Click on some symbol used more than once in a generated file.
- [ ] Highlight references should highlight all uses in the file.
## Window > New Window Support
1. Invoke Go to Definition to open a source-generated file. Then do Window > New Window to ensure that the new window is set up correctly.
- [ ] It's read only.
- [ ] The title and caption are correct.
2. Remove the source generator from the project.
- [ ] Confirm the first window correctly gets an info bar showing the file is no longer valid.
- [ ] Confirm the second window correctly gets an info bar showing the file is no longer valid.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/Design/Parser.md | Parser Design Guidelines
========================
This document describes design guidelines for the Roslyn parsers. These are not hard rules that cannot be violated. Use good judgment. It is acceptable to vary from the guidelines when there are reasons that outweigh their benefits.

The parsers do not currently comply with these guidelines, even in places where there is no good reason not to. The guidelines were written after the parsers. We expect to refactor the parsers opportunistically to comply with these guidelines, particularly when there are concrete benefit from doing so.
Designing the syntax model (data model for the syntax tree) for new features is currently outside the scope of these guidelines.
#### **DO** have the parser accept input text that complies with the syntax model
The syntax model defines the contract between syntax and semantic analysis. If the parser can build a meaningful syntax tree for a sequence of input tokens, then it should be left to semantic analysis to report when that tree is not semantically valid.
The most important diagnostics to report from the parser are "missing token" and "unexpected token".
There may be reasons to violate this rule. For example, the syntax model does not have a concept of precedence, but the parser uses precedence to decide how to assemble the tree. Precedence errors are therefore reported in the parser.
#### **DO NOT** use ambient context to direct the behavior of the parser
The parser should, as much as possible, be context-free. Use context where needed only to resolve language ambiguities. For example, in contexts where both a type and an expression are permitted, but a type is preferred, (such as the right-hand-side of `is`) we parse `X.Y` as a type. But in contexts where both are permitted, but it is to be treated as a type only if followed by an identifier (such as following `case`), we use look-ahead to decide which kind of tree to build. Try to minimize the amount of context used to make parsing decisions, as that will improve the quality of incremental parsing.
There may be reasons to violate this rule, for example where the language is specified to be sensitive to context. For example, `await` is treated as a keyword if the enclosing method has the `async` modifier.
#### Examples
Here are some examples of places where we might change the parser toward satisfying these guidelines, and the problems that may solve:
1. 100l : warning: use `L` for long literals
It may seem a small thing to produce this warning in the parser, but it interferes with incremental parsing. The incremental parser will not reuse a node that has diagnostics. As a consequence, even the presence of this helpful warning in code can reduce the performance of the parser as the user types in that source. That reduced performance may mean that the editor will not appear as responsive.
By moving this warning out of the parser and into semantic analysis, the IDE can be more responsive during typing.
1. Member parsing
The syntax model represents constructors and methods using separate nodes. When a declaration of the form `public M() {}` is seen, the parser checks the name of the function against the name of the enclosing type to decide whether it should represent it as a constructor, or as a method with a missing type. In this case the name of the enclosing type is a form of *ambient context* that affects the behavior of the compiler.
By treating such as declaration as a constructor in the syntax model, and checking the name in semantic analysis, it becomes possible to expose a context-free public API for parsing a member declaration. See https://github.com/dotnet/roslyn/issues/367 for a feature request that we have been unable to do because of this problem. | Parser Design Guidelines
========================
This document describes design guidelines for the Roslyn parsers. These are not hard rules that cannot be violated. Use good judgment. It is acceptable to vary from the guidelines when there are reasons that outweigh their benefits.

The parsers do not currently comply with these guidelines, even in places where there is no good reason not to. The guidelines were written after the parsers. We expect to refactor the parsers opportunistically to comply with these guidelines, particularly when there are concrete benefit from doing so.
Designing the syntax model (data model for the syntax tree) for new features is currently outside the scope of these guidelines.
#### **DO** have the parser accept input text that complies with the syntax model
The syntax model defines the contract between syntax and semantic analysis. If the parser can build a meaningful syntax tree for a sequence of input tokens, then it should be left to semantic analysis to report when that tree is not semantically valid.
The most important diagnostics to report from the parser are "missing token" and "unexpected token".
There may be reasons to violate this rule. For example, the syntax model does not have a concept of precedence, but the parser uses precedence to decide how to assemble the tree. Precedence errors are therefore reported in the parser.
#### **DO NOT** use ambient context to direct the behavior of the parser
The parser should, as much as possible, be context-free. Use context where needed only to resolve language ambiguities. For example, in contexts where both a type and an expression are permitted, but a type is preferred, (such as the right-hand-side of `is`) we parse `X.Y` as a type. But in contexts where both are permitted, but it is to be treated as a type only if followed by an identifier (such as following `case`), we use look-ahead to decide which kind of tree to build. Try to minimize the amount of context used to make parsing decisions, as that will improve the quality of incremental parsing.
There may be reasons to violate this rule, for example where the language is specified to be sensitive to context. For example, `await` is treated as a keyword if the enclosing method has the `async` modifier.
#### Examples
Here are some examples of places where we might change the parser toward satisfying these guidelines, and the problems that may solve:
1. 100l : warning: use `L` for long literals
It may seem a small thing to produce this warning in the parser, but it interferes with incremental parsing. The incremental parser will not reuse a node that has diagnostics. As a consequence, even the presence of this helpful warning in code can reduce the performance of the parser as the user types in that source. That reduced performance may mean that the editor will not appear as responsive.
By moving this warning out of the parser and into semantic analysis, the IDE can be more responsive during typing.
1. Member parsing
The syntax model represents constructors and methods using separate nodes. When a declaration of the form `public M() {}` is seen, the parser checks the name of the function against the name of the enclosing type to decide whether it should represent it as a constructor, or as a method with a missing type. In this case the name of the enclosing type is a form of *ambient context* that affects the behavior of the compiler.
By treating such as declaration as a constructor in the syntax model, and checking the name in semantic analysis, it becomes possible to expose a context-free public API for parsing a member declaration. See https://github.com/dotnet/roslyn/issues/367 for a feature request that we have been unable to do because of this problem. | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/CSharp/Static Type Constraints.md | Static Type Constraints
=======================
The Roslyn C# compiler does not implement all of the required constraints around static types as required by the C# language specification.
The native compiler gave an error when a type argument was inferred to be a static type, for example in a call like
```cs
M(default(StaticType))
```
Now this was only possible because the native compiler does not enforce the restriction that you can’t use a static type in a default expression. That is the first bug (#344) and won’t be fixed in Roslyn due to compatibility.
Now that the inferred type argument is a static type, the native compiler gave an error for that. While the language spec says that it is illegal to use a static type as a generic type argument, it isn’t clear if that was intended to apply to inferred type arguments. In any case, the native compiler would give an error in the above call due to the (inferred) type parameter being a static type.
Roslyn only implemented the constraint when binding explicit type arguments, so Roslyn didn’t diagnose this. This was bug the second bug (#345). I “fixed” that in Roslyn by moving the check from the place where we bind the type argument to the place where we check type arguments against the type parameter constraints.
Now as a separate matter the native compiler did not give an error when a static type was used as a type argument in a dynamic call, while Roslyn would give an error:
```cs
((dynamic)3).M<StaticType>()
```
This is the third bug (#511), and while Roslyn relies on the spec for its behavior, it is a breaking change from the native compiler. But as it turns out, this compat issue is fixed by the fix described above, because the type argument in a dynamic call is not checked against any type parameter constraints. So Roslyn now fails to diagnose this situation (i.e. doesn’t implement the required language rules) but at least it is compatible with the native compiler here.
I’m on a horse.
| Static Type Constraints
=======================
The Roslyn C# compiler does not implement all of the required constraints around static types as required by the C# language specification.
The native compiler gave an error when a type argument was inferred to be a static type, for example in a call like
```cs
M(default(StaticType))
```
Now this was only possible because the native compiler does not enforce the restriction that you can’t use a static type in a default expression. That is the first bug (#344) and won’t be fixed in Roslyn due to compatibility.
Now that the inferred type argument is a static type, the native compiler gave an error for that. While the language spec says that it is illegal to use a static type as a generic type argument, it isn’t clear if that was intended to apply to inferred type arguments. In any case, the native compiler would give an error in the above call due to the (inferred) type parameter being a static type.
Roslyn only implemented the constraint when binding explicit type arguments, so Roslyn didn’t diagnose this. This was bug the second bug (#345). I “fixed” that in Roslyn by moving the check from the place where we bind the type argument to the place where we check type arguments against the type parameter constraints.
Now as a separate matter the native compiler did not give an error when a static type was used as a type argument in a dynamic call, while Roslyn would give an error:
```cs
((dynamic)3).M<StaticType>()
```
This is the third bug (#511), and while Roslyn relies on the spec for its behavior, it is a breaking change from the native compiler. But as it turns out, this compat issue is fixed by the fix described above, because the type argument in a dynamic call is not checked against any type parameter constraints. So Roslyn now fails to diagnose this situation (i.e. doesn’t implement the required language rules) but at least it is compatible with the native compiler here.
I’m on a horse.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/Visual Basic/CommandLine.md | # Visual Basic Compiler Options
| FLAG | DESCRIPTION |
| ---- | ---- |
| **OUTPUT FILE**
| `/out:`*file* | Specifies the output file name.
| `/refout:`*file* | Specify the reference assembly's output file name
| `/target:exe` | Create a console application (default). (Short form: `/t`)
| `/target:winexe` | Create a Windows application.
| `/target:library` | Create a library assembly.
| `/target:module` | Create a module that can be added to an assembly.
| `/target:appcontainerexe` | Create a Windows application that runs in AppContainer.
| `/target:winmdobj` | Create a Windows Metadata intermediate file
| `/doc`{`+`|`-`} | Generates XML documentation file.
| `/doc:`*file* | Generates XML documentation file to *file*.
| **INPUT FILES**
| `/addmodule:`*file_list* | Reference metadata from the specified modules
| `/link:`*file_list* | Embed metadata from the specified interop assembly. (Short form: `/l`)
| `/recurse:`*wildcard* | Include all files in the current directory and subdirectories according to the wildcard specifications.
| `/reference:`*file_list* | Reference metadata from the specified assembly. (Short form: `/r`)
| `/analyzer:`*file_list* | Run the analyzers from this assembly (Short form: `/a`)
| `/additionalfile:`*file list* | Additional files that don't directly affect code generation but may be used by analyzers for producing errors or warnings.
| **RESOURCES**
| `/linkresource`:*resinfo* | Link the specified resource to this assembly (Short form: `/linkres`) Where the *resinfo* format is *file*{`,`*string name*{`,``public``|``private`}}
| `/resource`:*resinfo* | Embed the specified resource (Short form: `/res`)
| `/nowin32manifest` | The default manifest should not be embedded in the manifest section of the output PE.
| `/win32icon:`*file* | Specifies a Win32 icon file (.ico) for the default Win32 resources.
| `/win32manifest:`*file* | The provided file is embedded in the manifest section of the output PE.
| `/win32resource:`*file* | Specifies a Win32 resource file (.res).
| **CODE GENERATION**
| `/debug`{`+`|`-`} | Emit debugging information.
| `/debug`:`full` | Emit debugging information to .pdb file using default format for the current platform: _Windows PDB_ on Windows, _Portable PDB_ on other systems
| `/debug`:`pdbonly` | Same as `/debug:full`. For backward compatibility.
| `/debug`:`portable` | Emit debugging information to to .pdb file using cross-platform [Portable PDB format](https://github.com/dotnet/core/blob/main/Documentation/diagnostics/portable_pdb.md)
| `/debug`:`embedded` | Emit debugging information into the .dll/.exe itself (.pdb file is not produced) using [Portable PDB format](https://github.com/dotnet/core/blob/main/Documentation/diagnostics/portable_pdb.md).
| `/sourcelink`:*file* | [Source link](https://github.com/dotnet/core/blob/main/Documentation/diagnostics/source_link.md) info to embed into PDB.
| `/optimize`{`+`|`-`} | Enable optimizations.
| `/removeintchecks`{`+`|`-`} | Remove integer checks. Default off.
| `/debug:full` | Emit full debugging information (default).
| `/debug:portable` | Emit debugging information in the portable format.
| `/debug:pdbonly` | Emit PDB file only.
| `/deterministic` | Produce a deterministic assembly (including module version GUID and timestamp)
| `/refonly | Produce a reference assembly, instead of a full assembly, as the primary output
| **ERRORS AND WARNINGS**
| `/nowarn` | Disable all warnings.
| `/nowarn:`*number_list* | Disable a list of individual warnings.
| `/warnaserror`{`+`|`-`} | Treat all warnings as errors.
| `/warnaserror`{`+`|`-`}:*number_list* | Treat a list of warnings as errors.
| `/ruleset:`*file* | Specify a ruleset file that disables specific diagnostics.
| `/errorlog:`*file* | Specify a file to log all compiler and analyzer diagnostics.
| `/reportanalyzer` | Report additional analyzer information, such as execution time.
| **LANGUAGE**
| `/define:`*symbol_list* | Declare global conditional compilation symbol(s). *symbol_list* is *name*`=`*value*`,`... (Short form: `/d`)
| `/imports:`*import_list* | Declare global Imports for namespaces in referenced metadata files. *import_list* is *namespace*`,`...
| `/langversion:?` | Display the allowed values for language version
| `/langversion`:*string* | Specify language version such as `default` (latest major version), or `latest` (latest version, including minor versions)
| `/optionexplicit`{`+`|`-`} | Require explicit declaration of variables.
| `/optioninfer`{`+`|`-`} | Allow type inference of variables.
| `/rootnamespace`:*string* | Specifies the root Namespace for all top-level type declarations.
| `/optionstrict`{`+`|`-`} | Enforce strict language semantics.
| `/optionstrict:custom` | Warn when strict language semantics are not respected.
| `/optioncompare:binary` | Specifies binary-style string comparisons. This is the default.
| `/optioncompare:text` | Specifies text-style string comparisons.
| **MISCELLANEOUS**
| `/help` | Display a usage message. (Short form: `/?`)
| `/noconfig` | Do not auto-include VBC.RSP file.
| `/nologo` | Do not display compiler copyright banner.
| `/quiet` | Quiet output mode.
| `/verbose` | Display verbose messages.
| `/parallel`{`+`|`-`} | Concurrent build.
| **ADVANCED**
| `/baseaddress:`*number* | The base address for a library or module (hex).
| `/bugreport:`*file* | Create bug report file.
| `/checksumalgorithm:`*alg* | Specify algorithm for calculating source file checksum stored in PDB. Supported values are: `SHA1` (default) or `SHA256`.
| `/codepage:`*number* | Specifies the codepage to use when opening source files.
| `/delaysign`{`+`|`-`} | Delay-sign the assembly using only the public portion of the strong name key.
| `/errorreport:`*string* | Specifies how to handle internal compiler errors; must be `prompt`, `send`, `none`, or `queue` (default).
| `/filealign:`*number* | Specify the alignment used for output file sections.
| `/highentropyva`{`+`|`-`} | Enable high-entropy ASLR.
| `/keycontainer:`*string* | Specifies a strong name key container.
| `/keyfile:`*file* | Specifies a strong name key file.
| `/libpath:`*path_list* | List of directories to search for metadata references. (Semi-colon delimited.)
| `/main:`*class* | Specifies the Class or Module that contains Sub Main. It can also be a Class that inherits from System.Windows.Forms.Form. (Short form: `/m`)
| `/moduleassemblyname:`*string* | Name of the assembly which this module will be a part of.
| `/netcf` | Target the .NET Compact Framework.
| `/nostdlib` | Do not reference standard libraries (`system.dll` and `VBC.RSP` file).
| `/pathmap:`*k1*=*v1*,*k2*=*v2*,... | Specify a mapping for source path names output by the compiler. Two consecutive separator characters are treated as a single character that is part of the key or value (i.e. `==` stands for `=` and `,,` for `,`).
| `/platform:`*string* | Limit which platforms this code can run on; must be `x86`, `x64`, `Itanium`, `arm`, `AnyCPU32BitPreferred` or `anycpu` (default).
| `/preferreduilang` | Specify the preferred output language name.
| `/sdkpath:`*path* | Location of the .NET Framework SDK directory (`mscorlib.dll`).
| `/subsystemversion:`*version* | Specify subsystem version of the output PE. *version* is *number*{.*number*}
| `/utf8output`{`+`|`-`} | Emit compiler output in UTF8 character encoding.
| `@`*file* | Insert command-line settings from a text file
| `/vbruntime`{+|-|*} | Compile with/without the default Visual Basic runtime.
| `/vbruntime:`*file* | Compile with the alternate Visual Basic runtime in *file*.
| # Visual Basic Compiler Options
| FLAG | DESCRIPTION |
| ---- | ---- |
| **OUTPUT FILE**
| `/out:`*file* | Specifies the output file name.
| `/refout:`*file* | Specify the reference assembly's output file name
| `/target:exe` | Create a console application (default). (Short form: `/t`)
| `/target:winexe` | Create a Windows application.
| `/target:library` | Create a library assembly.
| `/target:module` | Create a module that can be added to an assembly.
| `/target:appcontainerexe` | Create a Windows application that runs in AppContainer.
| `/target:winmdobj` | Create a Windows Metadata intermediate file
| `/doc`{`+`|`-`} | Generates XML documentation file.
| `/doc:`*file* | Generates XML documentation file to *file*.
| **INPUT FILES**
| `/addmodule:`*file_list* | Reference metadata from the specified modules
| `/link:`*file_list* | Embed metadata from the specified interop assembly. (Short form: `/l`)
| `/recurse:`*wildcard* | Include all files in the current directory and subdirectories according to the wildcard specifications.
| `/reference:`*file_list* | Reference metadata from the specified assembly. (Short form: `/r`)
| `/analyzer:`*file_list* | Run the analyzers from this assembly (Short form: `/a`)
| `/additionalfile:`*file list* | Additional files that don't directly affect code generation but may be used by analyzers for producing errors or warnings.
| **RESOURCES**
| `/linkresource`:*resinfo* | Link the specified resource to this assembly (Short form: `/linkres`) Where the *resinfo* format is *file*{`,`*string name*{`,``public``|``private`}}
| `/resource`:*resinfo* | Embed the specified resource (Short form: `/res`)
| `/nowin32manifest` | The default manifest should not be embedded in the manifest section of the output PE.
| `/win32icon:`*file* | Specifies a Win32 icon file (.ico) for the default Win32 resources.
| `/win32manifest:`*file* | The provided file is embedded in the manifest section of the output PE.
| `/win32resource:`*file* | Specifies a Win32 resource file (.res).
| **CODE GENERATION**
| `/debug`{`+`|`-`} | Emit debugging information.
| `/debug`:`full` | Emit debugging information to .pdb file using default format for the current platform: _Windows PDB_ on Windows, _Portable PDB_ on other systems
| `/debug`:`pdbonly` | Same as `/debug:full`. For backward compatibility.
| `/debug`:`portable` | Emit debugging information to to .pdb file using cross-platform [Portable PDB format](https://github.com/dotnet/core/blob/main/Documentation/diagnostics/portable_pdb.md)
| `/debug`:`embedded` | Emit debugging information into the .dll/.exe itself (.pdb file is not produced) using [Portable PDB format](https://github.com/dotnet/core/blob/main/Documentation/diagnostics/portable_pdb.md).
| `/sourcelink`:*file* | [Source link](https://github.com/dotnet/core/blob/main/Documentation/diagnostics/source_link.md) info to embed into PDB.
| `/optimize`{`+`|`-`} | Enable optimizations.
| `/removeintchecks`{`+`|`-`} | Remove integer checks. Default off.
| `/debug:full` | Emit full debugging information (default).
| `/debug:portable` | Emit debugging information in the portable format.
| `/debug:pdbonly` | Emit PDB file only.
| `/deterministic` | Produce a deterministic assembly (including module version GUID and timestamp)
| `/refonly | Produce a reference assembly, instead of a full assembly, as the primary output
| **ERRORS AND WARNINGS**
| `/nowarn` | Disable all warnings.
| `/nowarn:`*number_list* | Disable a list of individual warnings.
| `/warnaserror`{`+`|`-`} | Treat all warnings as errors.
| `/warnaserror`{`+`|`-`}:*number_list* | Treat a list of warnings as errors.
| `/ruleset:`*file* | Specify a ruleset file that disables specific diagnostics.
| `/errorlog:`*file* | Specify a file to log all compiler and analyzer diagnostics.
| `/reportanalyzer` | Report additional analyzer information, such as execution time.
| **LANGUAGE**
| `/define:`*symbol_list* | Declare global conditional compilation symbol(s). *symbol_list* is *name*`=`*value*`,`... (Short form: `/d`)
| `/imports:`*import_list* | Declare global Imports for namespaces in referenced metadata files. *import_list* is *namespace*`,`...
| `/langversion:?` | Display the allowed values for language version
| `/langversion`:*string* | Specify language version such as `default` (latest major version), or `latest` (latest version, including minor versions)
| `/optionexplicit`{`+`|`-`} | Require explicit declaration of variables.
| `/optioninfer`{`+`|`-`} | Allow type inference of variables.
| `/rootnamespace`:*string* | Specifies the root Namespace for all top-level type declarations.
| `/optionstrict`{`+`|`-`} | Enforce strict language semantics.
| `/optionstrict:custom` | Warn when strict language semantics are not respected.
| `/optioncompare:binary` | Specifies binary-style string comparisons. This is the default.
| `/optioncompare:text` | Specifies text-style string comparisons.
| **MISCELLANEOUS**
| `/help` | Display a usage message. (Short form: `/?`)
| `/noconfig` | Do not auto-include VBC.RSP file.
| `/nologo` | Do not display compiler copyright banner.
| `/quiet` | Quiet output mode.
| `/verbose` | Display verbose messages.
| `/parallel`{`+`|`-`} | Concurrent build.
| **ADVANCED**
| `/baseaddress:`*number* | The base address for a library or module (hex).
| `/bugreport:`*file* | Create bug report file.
| `/checksumalgorithm:`*alg* | Specify algorithm for calculating source file checksum stored in PDB. Supported values are: `SHA1` (default) or `SHA256`.
| `/codepage:`*number* | Specifies the codepage to use when opening source files.
| `/delaysign`{`+`|`-`} | Delay-sign the assembly using only the public portion of the strong name key.
| `/errorreport:`*string* | Specifies how to handle internal compiler errors; must be `prompt`, `send`, `none`, or `queue` (default).
| `/filealign:`*number* | Specify the alignment used for output file sections.
| `/highentropyva`{`+`|`-`} | Enable high-entropy ASLR.
| `/keycontainer:`*string* | Specifies a strong name key container.
| `/keyfile:`*file* | Specifies a strong name key file.
| `/libpath:`*path_list* | List of directories to search for metadata references. (Semi-colon delimited.)
| `/main:`*class* | Specifies the Class or Module that contains Sub Main. It can also be a Class that inherits from System.Windows.Forms.Form. (Short form: `/m`)
| `/moduleassemblyname:`*string* | Name of the assembly which this module will be a part of.
| `/netcf` | Target the .NET Compact Framework.
| `/nostdlib` | Do not reference standard libraries (`system.dll` and `VBC.RSP` file).
| `/pathmap:`*k1*=*v1*,*k2*=*v2*,... | Specify a mapping for source path names output by the compiler. Two consecutive separator characters are treated as a single character that is part of the key or value (i.e. `==` stands for `=` and `,,` for `,`).
| `/platform:`*string* | Limit which platforms this code can run on; must be `x86`, `x64`, `Itanium`, `arm`, `AnyCPU32BitPreferred` or `anycpu` (default).
| `/preferreduilang` | Specify the preferred output language name.
| `/sdkpath:`*path* | Location of the .NET Framework SDK directory (`mscorlib.dll`).
| `/subsystemversion:`*version* | Specify subsystem version of the output PE. *version* is *number*{.*number*}
| `/utf8output`{`+`|`-`} | Emit compiler output in UTF8 character encoding.
| `@`*file* | Insert command-line settings from a text file
| `/vbruntime`{+|-|*} | Compile with/without the default Visual Basic runtime.
| `/vbruntime:`*file* | Compile with the alternate Visual Basic runtime in *file*.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/CSharp/Unicode Version.md | Unicode Version Change in C# 6
==============================
The Roslyn compilers depend on the underlying platform for their Unicode behavior. As a practical matter, that means that the new compiler will reflect changes in the Unicode standard.
For example, the Unicode Katakana Middle Dot "・" (U+30FB) no longer works in identifiers in C# 6.
Its Unicode class was Pc (Punctuation, Connector) in Unicode 5.1 or older, but it changed to Po (Punctuation, Other) in Unicode 6.0.
See also https://github.com/ufcpp/UfcppSample/blob/master/BreakingChanges/VS2015_CS6/KatakanaMiddleDot.cs
| Unicode Version Change in C# 6
==============================
The Roslyn compilers depend on the underlying platform for their Unicode behavior. As a practical matter, that means that the new compiler will reflect changes in the Unicode standard.
For example, the Unicode Katakana Middle Dot "・" (U+30FB) no longer works in identifiers in C# 6.
Its Unicode class was Pc (Punctuation, Connector) in Unicode 5.1 or older, but it changed to Po (Punctuation, Other) in Unicode 6.0.
See also https://github.com/ufcpp/UfcppSample/blob/master/BreakingChanges/VS2015_CS6/KatakanaMiddleDot.cs
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/Compiler Toolset NuPkgs.md | Compiler Toolset NuPkgs
===
## Summary
The compiler produces the [Microsoft.Net.Compilers.Toolset NuPkg](https://www.nuget.org/packages/Microsoft.Net.Compilers.Toolset)
from all of Roslyn's main branches. When this NuPkg is installed it will
override the compiler that comes with MSBuild with the version from the branch
it was built in.
This package is meant to support the following scenarios:
1. Allows compiler team to provide rapid hot fixes to customers who hit a blocking
issue. This package can be installed until the fix is available in .NET SDK or
Visual Studio servicing.
1. Serves as a transport mechanism for the Roslyn binaries in the greater .NET
SDK build process.
1. Allows customers to conduct experiments on various Roslyn builds, many of
which aren't in an official shipping product yet.
This package is **not** meant to support using newer compiler versions in an
older version of MSBuild. For example using Microsoft.Net.Compilers.Toolset
3.5 (C# 8) inside MSBuild 15 is explicitly not a supported scenario.
Customers who want to use the compiler as a part of their supported build
infrastructure should use the [Visual Studio Build Tools SKU](https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-build-tools?view=vs-2022])
) or [.NET SDK](https://dotnet.microsoft.com/download/visual-studio-sdks)
## NuPkg Installation
To install the NuPgk run the following:
```cmd
> nuget install Microsoft.Net.Compilers.Toolset # Install C# and VB compilers
```
Daily NuGet builds of the project are also available in our [Azure DevOps feed](https://dev.azure.com/dnceng/public/_packaging?_a=feed&feed=dotnet-tools):
> https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json
## Microsoft.Net.Compilers
The [Microsoft.Net.Compilers](https://www.nuget.org/packages/Microsoft.Net.Compilers)
NuPkg is deprecated. It is a .NET Desktop specific version of
Microsoft.Net.Compilers.Toolset and will not be produced anymore after the
3.6.0 release. The Microsoft.Net.Compilers.Toolset package is a drop in
replacement for it for all supported scenarios.
| Compiler Toolset NuPkgs
===
## Summary
The compiler produces the [Microsoft.Net.Compilers.Toolset NuPkg](https://www.nuget.org/packages/Microsoft.Net.Compilers.Toolset)
from all of Roslyn's main branches. When this NuPkg is installed it will
override the compiler that comes with MSBuild with the version from the branch
it was built in.
This package is meant to support the following scenarios:
1. Allows compiler team to provide rapid hot fixes to customers who hit a blocking
issue. This package can be installed until the fix is available in .NET SDK or
Visual Studio servicing.
1. Serves as a transport mechanism for the Roslyn binaries in the greater .NET
SDK build process.
1. Allows customers to conduct experiments on various Roslyn builds, many of
which aren't in an official shipping product yet.
This package is **not** meant to support using newer compiler versions in an
older version of MSBuild. For example using Microsoft.Net.Compilers.Toolset
3.5 (C# 8) inside MSBuild 15 is explicitly not a supported scenario.
Customers who want to use the compiler as a part of their supported build
infrastructure should use the [Visual Studio Build Tools SKU](https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-build-tools?view=vs-2022])
) or [.NET SDK](https://dotnet.microsoft.com/download/visual-studio-sdks)
## NuPkg Installation
To install the NuPgk run the following:
```cmd
> nuget install Microsoft.Net.Compilers.Toolset # Install C# and VB compilers
```
Daily NuGet builds of the project are also available in our [Azure DevOps feed](https://dev.azure.com/dnceng/public/_packaging?_a=feed&feed=dotnet-tools):
> https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json
## Microsoft.Net.Compilers
The [Microsoft.Net.Compilers](https://www.nuget.org/packages/Microsoft.Net.Compilers)
NuPkg is deprecated. It is a .NET Desktop specific version of
Microsoft.Net.Compilers.Toolset and will not be produced anymore after the
3.6.0 release. The Microsoft.Net.Compilers.Toolset package is a drop in
replacement for it for all supported scenarios.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/Error Log Format.md | The C# and Visual Basic compilers support a /errorlog:<file> switch on
the command line to log all diagnostics in a structured, JSON format.
The log format is SARIF (Static Analysis Results Interchange Format):
See https://sarifweb.azurewebsites.net/ for the format specification,
JSON schema, and other related resources. | The C# and Visual Basic compilers support a /errorlog:<file> switch on
the command line to log all diagnostics in a structured, JSON format.
The log format is SARIF (Static Analysis Results Interchange Format):
See https://sarifweb.azurewebsites.net/ for the format specification,
JSON schema, and other related resources. | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/compilers/Boolean Representation.md | Representation of Boolean Values
================================
The C# and VB compilers represent `true` (`True`) and `false` (`False`) `bool` (`Boolean`) values with the single byte values `1` and `0`, respectively, and assume that any boolean values that they are working with are restricted to being represented by these two underlying values. The ECMA 335 CLI specification permits a "true" boolean value to be represented by any nonzero value. If you use boolean values that have an underlying representation other than `0` or `1`, you can get unexpected results. This can occur in `unsafe` code in C#, or by interoperating with a language that permits other values. To avoid these unexpected results, it is the programmer's responsibility to normalize such incoming values.
See also https://github.com/dotnet/roslyn/issues/24652
| Representation of Boolean Values
================================
The C# and VB compilers represent `true` (`True`) and `false` (`False`) `bool` (`Boolean`) values with the single byte values `1` and `0`, respectively, and assume that any boolean values that they are working with are restricted to being represented by these two underlying values. The ECMA 335 CLI specification permits a "true" boolean value to be represented by any nonzero value. If you use boolean values that have an underlying representation other than `0` or `1`, you can get unexpected results. This can occur in `unsafe` code in C#, or by interoperating with a language that permits other values. To avoid these unexpected results, it is the programmer's responsibility to normalize such incoming values.
See also https://github.com/dotnet/roslyn/issues/24652
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/wiki/VS-2015-CTP-5-API-Changes.md | #API changes between VS 2015 Preview and VS 2015 CTP5
##Diagnostics and CodeFix API Changes
We have made some changes to the APIs to better support localization of the various strings that can be returned by analyzers. There are some useful overloads for some common cases that have been added. The `Microsoft.CodeAnalysis.Diagnostics.Internal` namespace and all types there have been made internal as those APIs were just an implementation detail.
```diff
assembly Microsoft.CodeAnalysis {
namespace Microsoft.CodeAnalysis {
public abstract class Diagnostic : IEquatable<Diagnostic>, IFormattable {
- public abstract string Category { get; }
- public abstract IReadOnlyList<string> CustomTags { get; }
- public abstract DiagnosticSeverity DefaultSeverity { get; }
+ public virtual DiagnosticSeverity DefaultSeverity { get; }
- public abstract string Description { get; }
+ public abstract DiagnosticDescriptor Descriptor { get; }
- public abstract string HelpLink { get; }
- public abstract bool IsEnabledByDefault { get; }
+ public static Diagnostic Create(string id, string category, LocalizableString message, DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, int warningLevel, LocalizableString title=null, LocalizableString description=null, string helpLink=null, Location location=null, IEnumerable<Location> additionalLocations=null, IEnumerable<string> customTags=null);
- public static Diagnostic Create(string id, string category, string message, DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, int warningLevel, string description=null, string helpLink=null, Location location=null, IEnumerable<Location> additionalLocations=null, IEnumerable<string> customTags=null);
- public abstract string GetMessage(CultureInfo culture=null);
+ public abstract string GetMessage(IFormatProvider formatProvider=null);
+ string System.IFormattable.ToString(string ignored, IFormatProvider formatProvider);
}
public class DiagnosticDescriptor {
+ public DiagnosticDescriptor(string id, LocalizableString title, LocalizableString messageFormat, string category, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, LocalizableString description=null, string helpLink=null, params string[] customTags);
- public string Description { get; }
+ public LocalizableString Description { get; }
- public string MessageFormat { get; }
+ public LocalizableString MessageFormat { get; }
- public string Title { get; }
+ public LocalizableString Title { get; }
+ public override bool Equals(object obj);
+ public override int GetHashCode();
}
+ public sealed class LocalizableResourceString : LocalizableString {
+ public LocalizableResourceString(string nameOfLocalizableResource, ResourceManager resourceManager, Type resourceSource, params string[] formatArguments);
+ public override string ToString(IFormatProvider formatProvider);
}
+ public abstract class LocalizableString : IFormattable {
+ protected LocalizableString();
+ public static explicit operator string (LocalizableString localizableResource);
+ public static implicit operator LocalizableString (string fixedResource);
+ string System.IFormattable.ToString(string ignored, IFormatProvider formatProvider);
+ public sealed override string ToString();
+ public abstract string ToString(IFormatProvider formatProvider);
}
}
namespace Microsoft.CodeAnalysis.Diagnostics {
public struct AnalysisContext {
- public AnalysisContext(SessionStartAnalysisScope scope);
public void RegisterCodeBlockEndAction<TLanguageKindEnum>(Action<CodeBlockEndAnalysisContext> action) where TLanguageKindEnum : struct, ValueType;
public void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct, ValueType;
+ public void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds);
+ public void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct, ValueType;
public void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, params TLanguageKindEnum[] syntaxKinds) where TLanguageKindEnum : struct, ValueType;
}
public class AnalyzerOptions {
- public AnalyzerOptions(IEnumerable<AdditionalStream> additionalStreams, IDictionary<string, string> globalOptions, CultureInfo culture=null);
+ public AnalyzerOptions(ImmutableArray<AdditionalStream> additionalStreams, ImmutableDictionary<string, string> globalOptions, CultureInfo culture=null);
+ public AnalyzerOptions WithAdditionalStreams(ImmutableArray<AdditionalStream> additionalStreams);
+ public AnalyzerOptions WithCulture(CultureInfo culture);
+ public AnalyzerOptions WithGlobalOptions(ImmutableDictionary<string, string> globalOptions);
}
public struct CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct, ValueType {
+ public void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds);
}
public struct CompilationEndAnalysisContext {
- public CompilationEndAnalysisContext(Compilation compilation, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
public struct CompilationStartAnalysisContext {
- public CompilationStartAnalysisContext(CompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken);
public void RegisterCodeBlockEndAction<TLanguageKindEnum>(Action<CodeBlockEndAnalysisContext> action) where TLanguageKindEnum : struct, ValueType;
public void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct, ValueType;
+ public void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds);
+ public void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct, ValueType;
public void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, params TLanguageKindEnum[] syntaxKinds) where TLanguageKindEnum : struct, ValueType;
}
public struct SemanticModelAnalysisContext {
- public SemanticModelAnalysisContext(SemanticModel semanticModel, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
public struct SymbolAnalysisContext {
- public SymbolAnalysisContext(ISymbol symbol, Compilation compilation, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
public struct SyntaxNodeAnalysisContext {
- public SyntaxNodeAnalysisContext(SyntaxNode node, SemanticModel semanticModel, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
public struct SyntaxTreeAnalysisContext {
- public SyntaxTreeAnalysisContext(SyntaxTree tree, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
}
}
assembly Microsoft.CodeAnalysis.Desktop {
namespace Microsoft.CodeAnalysis {
public class RuleSet {
- public RuleSet(string filePath, ReportDiagnostic generalOption, IDictionary<string, ReportDiagnostic> specificOptions, IEnumerable<RuleSetInclude> includes);
+ public RuleSet(string filePath, ReportDiagnostic generalOption, ImmutableDictionary<string, ReportDiagnostic> specificOptions, ImmutableArray<RuleSetInclude> includes);
}
}
}
assembly Microsoft.CodeAnalysis.Workspaces {
namespace Microsoft.CodeAnalysis {
public class Project {
+ public TextDocument AddAdditionalDocument(string name, SourceText text, IEnumerable<string> folders=null);
+ public TextDocument AddAdditionalDocument(string name, string text, IEnumerable<string> folders=null);
+ public Document AddDocument(string name, SyntaxNode syntaxRoot, IEnumerable<string> folders=null);
+ public Project RemoveAdditionalDocument(DocumentId documentId);
}
public class Solution {
+ public Solution AddAdditionalDocument(DocumentId documentId, string name, string text, IEnumerable<string> folders=null, string filePath=null);
+ public Solution AddDocument(DocumentId documentId, string name, SyntaxNode syntaxRoot, IEnumerable<string> folders=null, string filePath=null, bool isGenerated=false, PreservationMode preservationMode=(PreservationMode)(0));
}
public abstract class Workspace : IDisposable {
public virtual Solution CurrentSolution { get; }
- protected virtual void AddAdditionalDocument(DocumentId documentId, IEnumerable<string> folders, string name, SourceText text=null);
+ protected virtual void AddAdditionalDocument(DocumentInfo info, SourceText text);
- protected virtual void AddDocument(DocumentId documentId, IEnumerable<string> folders, string name, SourceText text=null, SourceCodeKind sourceCodeKind=(SourceCodeKind)(0));
+ protected virtual void AddDocument(DocumentInfo info, SourceText text);
}
}
namespace Microsoft.CodeAnalysis.CodeFixes {
public struct CodeFixContext {
- public CodeFixContext(Document document, Diagnostic diagnostic, Action<CodeAction, IEnumerable<Diagnostic>> registerFix, CancellationToken cancellationToken);
+ public CodeFixContext(Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerFix, CancellationToken cancellationToken);
- public CodeFixContext(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, Action<CodeAction, IEnumerable<Diagnostic>> registerFix, CancellationToken cancellationToken);
+ public CodeFixContext(Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerFix, CancellationToken cancellationToken);
public IEnumerable<Diagnostic>ImmutableArray<Diagnostic> Diagnostics { get; }
+ public void RegisterFix(CodeAction action, ImmutableArray<Diagnostic> diagnostics);
}
public abstract class CodeFixProvider {
- public abstract FixAllProvider GetFixAllProvider();
+ public virtual FixAllProvider GetFixAllProvider();
}
}
}
```
##Changes caused by language features
We've been continuing to work on adding\refining String Interpolation and nameof in both languages and that's changed some APIs.
```diff
assembly Microsoft.CodeAnalysis {
namespace Microsoft.CodeAnalysis {
public enum CandidateReason {
+ MemberGroup = 16,
}
}
assembly Microsoft.CodeAnalysis.CSharp {
namespace Microsoft.CodeAnalysis {
public static class CSharpExtensions {
+ public static int IndexOf(this SyntaxTokenList list, SyntaxKind kind);
+ public static int IndexOf(this SyntaxTriviaList list, SyntaxKind kind);
+ public static int IndexOf<TNode>(this SeparatedSyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
+ public static int IndexOf<TNode>(this SyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
}
}
namespace Microsoft.CodeAnalysis.CSharp {
public sealed class CSharpCompilation : Compilation {
+ public override bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
+ public override IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
}
public sealed class CSharpParseOptions : ParseOptions, IEquatable<CSharpParseOptions> {
+ public override IReadOnlyDictionary<string, string> Features { get; }
+ protected override ParseOptions CommonWithFeatures(IEnumerable<KeyValuePair<string, string>> features);
+ public new CSharpParseOptions WithFeatures(IEnumerable<KeyValuePair<string, string>> features);
}
public abstract class CSharpSyntaxRewriter : CSharpSyntaxVisitor<SyntaxNode> {
- public override SyntaxNode VisitNameOfExpression(NameOfExpressionSyntax node);
}
public abstract class CSharpSyntaxVisitor {
- public virtual void VisitNameOfExpression(NameOfExpressionSyntax node);
}
public abstract class CSharpSyntaxVisitor<TResult> {
- public virtual TResult VisitNameOfExpression(NameOfExpressionSyntax node);
}
public enum LanguageVersion {
- Experimental = 2147483647,
}
public static class SyntaxFactory {
+ public static InterpolatedStringInsertSyntax InterpolatedStringInsert(ExpressionSyntax expression, SyntaxToken comma, ExpressionSyntax alignment, SyntaxToken format);
- public static InterpolatedStringInsertSyntax InterpolatedStringInsert(ExpressionSyntax expression, SyntaxToken comma, ExpressionSyntax alignment, SyntaxToken colon, SyntaxToken format);
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimalDecimal value, SyntaxTriviaList trailing);
public static SyntaxToken Literal(decimalDecimal value);
public static SyntaxToken Literal(string text, decimalDecimal value);
- public static NameOfExpressionSyntax NameOfExpression(IdentifierNameSyntax nameOfIdentifier, ExpressionSyntax argument);
- public static NameOfExpressionSyntax NameOfExpression(IdentifierNameSyntax nameOfIdentifier, SyntaxToken openParenToken, ExpressionSyntax argument, SyntaxToken closeParenToken);
- public static NameOfExpressionSyntax NameOfExpression(string nameOfIdentifier, ExpressionSyntax argument);
+ public static UsingDirectiveSyntax UsingDirective(SyntaxToken staticKeyword, NameEqualsSyntax alias, NameSyntax name);
- public static UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, NameEqualsSyntax alias, NameSyntax name, SyntaxToken semicolonToken);
+ public static UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax alias, NameSyntax name, SyntaxToken semicolonToken);
}
public enum SyntaxKind : ushort {
- NameOfExpression = (ushort)8768,
}
}
namespace Microsoft.CodeAnalysis.CSharp.Syntax {
public sealed class InterpolatedStringInsertSyntax : CSharpSyntaxNode {
- public SyntaxToken Colon { get; }
+ public InterpolatedStringInsertSyntax Update(ExpressionSyntax expression, SyntaxToken comma, ExpressionSyntax alignment, SyntaxToken format);
- public InterpolatedStringInsertSyntax Update(ExpressionSyntax expression, SyntaxToken comma, ExpressionSyntax alignment, SyntaxToken colon, SyntaxToken format);
- public InterpolatedStringInsertSyntax WithColon(SyntaxToken colon);
}
- public sealed class NameOfExpressionSyntax : ExpressionSyntax {
- public ExpressionSyntax Argument { get; }
- public SyntaxToken CloseParenToken { get; }
- public IdentifierNameSyntax NameOfIdentifier { get; }
- public SyntaxToken OpenParenToken { get; }
- public override void Accept(CSharpSyntaxVisitor visitor);
- public override TResult Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor);
- public NameOfExpressionSyntax Update(IdentifierNameSyntax nameOfIdentifier, SyntaxToken openParenToken, ExpressionSyntax argument, SyntaxToken closeParenToken);
- public NameOfExpressionSyntax WithArgument(ExpressionSyntax argument);
- public NameOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken);
- public NameOfExpressionSyntax WithNameOfIdentifier(IdentifierNameSyntax nameOfIdentifier);
- public NameOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken);
}
public sealed class UsingDirectiveSyntax : CSharpSyntaxNode {
+ public SyntaxToken StaticKeyword { get; }
- public UsingDirectiveSyntax Update(SyntaxToken usingKeyword, NameEqualsSyntax alias, NameSyntax name, SyntaxToken semicolonToken);
+ public UsingDirectiveSyntax Update(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax alias, NameSyntax name, SyntaxToken semicolonToken);
+ public UsingDirectiveSyntax WithStaticKeyword(SyntaxToken staticKeyword);
}
}
}
assembly Microsoft.CodeAnalysis.VisualBasic {
namespace Microsoft.CodeAnalysis {
public sealed class VisualBasicExtensions {
+ public static bool Any<TNode>(this SeparatedSyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
+ public static bool Any<TNode>(this SyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
+ public static int IndexOf(this SyntaxTokenList list, SyntaxKind kind);
+ public static int IndexOf(this SyntaxTriviaList list, SyntaxKind kind);
+ public static int IndexOf<TNode>(this SeparatedSyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
+ public static int IndexOf<TNode>(this SyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
}
}
namespace Microsoft.CodeAnalysis.VisualBasic {
public enum LanguageVersion {
- Experimental = 2147483647,
}
public class SyntaxFactory {
public static SyntaxToken DecimalLiteralToken(SyntaxTriviaList leadingTrivia, string text, TypeCharacter typeSuffix, decimalDecimal value, SyntaxTriviaList trailingTrivia);
public static SyntaxToken DecimalLiteralToken(string text, TypeCharacter typeSuffix, decimalDecimal value);
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimalDecimal value, SyntaxTriviaList trailing);
public static SyntaxToken Literal(decimalDecimal value);
public static SyntaxToken Literal(string text, decimalDecimal value);
+ public static NameOfExpressionSyntax NameOfExpression(SyntaxToken nameOfKeyword, SyntaxToken openParenToken, ExpressionSyntax argument, SyntaxToken closeParenToken);
+ public static NameOfExpressionSyntax NameOfExpression(ExpressionSyntax argument);
}
public enum SyntaxKind : ushort {
+ NameOfExpression = (ushort)779,
+ NameOfKeyword = (ushort)778,
}
public sealed class VisualBasicCompilation : Compilation {
+ public override bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
+ public override IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
}
public sealed class VisualBasicParseOptions : ParseOptions, IEquatable<VisualBasicParseOptions> {
+ public override IReadOnlyDictionary<string, string> Features { get; }
+ protected override ParseOptions CommonWithFeatures(IEnumerable<KeyValuePair<string, string>> features);
+ public new VisualBasicParseOptions WithFeatures(IEnumerable<KeyValuePair<string, string>> features);
}
public abstract class VisualBasicSyntaxRewriter : VisualBasicSyntaxVisitor<SyntaxNode> {
+ public override SyntaxNode VisitNameOfExpression(NameOfExpressionSyntax node);
}
public abstract class VisualBasicSyntaxVisitor {
+ public virtual void VisitNameOfExpression(NameOfExpressionSyntax node);
}
public abstract class VisualBasicSyntaxVisitor<TResult> {
+ public virtual TResult VisitNameOfExpression(NameOfExpressionSyntax node);
}
}
namespace Microsoft.CodeAnalysis.VisualBasic.Syntax {
+ public sealed class NameOfExpressionSyntax : ExpressionSyntax {
+ public ExpressionSyntax Argument { get; }
+ public SyntaxToken CloseParenToken { get; }
+ public SyntaxToken NameOfKeyword { get; }
+ public SyntaxToken OpenParenToken { get; }
+ public override void Accept(VisualBasicSyntaxVisitor visitor);
+ public override TResult Accept<TResult>(VisualBasicSyntaxVisitor<TResult> visitor);
+ public NameOfExpressionSyntax Update(SyntaxToken nameOfKeyword, SyntaxToken openParenToken, ExpressionSyntax argument, SyntaxToken closeParenToken);
+ public NameOfExpressionSyntax WithArgument(ExpressionSyntax argument);
+ public NameOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken);
+ public NameOfExpressionSyntax WithNameOfKeyword(SyntaxToken nameOfKeyword);
+ public NameOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken);
}
}
}
```
##New functionality
We've added some new APIs to make it easier to generate code from Code Fixes\Refactorings and some useful overloads in the SymbolFinder.
```diff
assembly Microsoft.CodeAnalysis.Workspaces {
namespace Microsoft.CodeAnalysis.CodeGeneration {
+ public enum DeclarationKind {
+ Attribute = 22,
+ Class = 2,
+ CompilationUnit = 1,
+ Constructor = 10,
+ ConversionOperator = 9,
+ CustomEvent = 17,
+ Delegate = 6,
+ Destructor = 11,
+ Enum = 5,
+ EnumMember = 15,
+ Event = 16,
+ Field = 12,
+ Indexer = 14,
+ Interface = 4,
+ LambdaExpression = 23,
+ LocalVariable = 21,
+ Method = 7,
+ Namespace = 18,
+ NamespaceImport = 19,
+ None = 0,
+ Operator = 8,
+ Parameter = 20,
+ Property = 13,
+ Struct = 3,
}
public struct DeclarationModifiers : IEquatable<DeclarationModifiers> {
+ public bool Equals(DeclarationModifiers modifiers);
+ public override bool Equals(object obj);
+ public override int GetHashCode();
+ public static bool operator ==(DeclarationModifiers left, DeclarationModifiers right);
+ public static bool operator !=(DeclarationModifiers left, DeclarationModifiers right);
+ public override string ToString();
}
+ public class SymbolEditor {
+ public SymbolEditor(Document document);
+ public SymbolEditor(Solution solution);
+ public Solution CurrentSolution { get; }
+ public Solution OriginalSolution { get; }
+ public Task<ISymbol> EditAllDeclarationsAsync(ISymbol symbol, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> declarationEditor, CancellationToken cancellationToken=null);
+ public Task<ISymbol> EditOneDeclarationAsync(ISymbol symbol, ISymbol member, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> declarationEditor, CancellationToken cancellationToken=null);
+ public Task<ISymbol> EditOneDeclarationAsync(ISymbol symbol, Location location, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> declarationEditor, CancellationToken cancellationToken=null);
+ public Task<ISymbol> EditOneDeclarationAsync(ISymbol symbol, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> declarationEditor, CancellationToken cancellationToken=null);
+ public IEnumerable<Document> GetChangedDocuments();
+ public Task<ISymbol> GetCurrentSymbolAsync(ISymbol symbol, CancellationToken cancellationToken=null);
}
public abstract class SyntaxGenerator : ILanguageService {
- protected static DeclarationModifiers constructorModifers;
- protected static DeclarationModifiers fieldModifiers;
- protected static DeclarationModifiers indexerModifiers;
- protected static DeclarationModifiers methodModifiers;
- protected static DeclarationModifiers propertyModifiers;
- protected static DeclarationModifiers typeModifiers;
+ public static SyntaxRemoveOptions DefaultRemoveOptions;
public abstract SyntaxNode AddAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes);
+ public SyntaxNode AddMembers(SyntaxNode declaration, params SyntaxNode[] members);
+ public SyntaxNode AddMembers(SyntaxNode declaration, IEnumerable<SyntaxNode> members);
+ public SyntaxNode AddNamespaceImports(SyntaxNode declaration, params SyntaxNode[] imports);
+ public SyntaxNode AddNamespaceImports(SyntaxNode declaration, IEnumerable<SyntaxNode> imports);
+ public SyntaxNode AddParameters(SyntaxNode declaration, IEnumerable<SyntaxNode> parameters);
public SyntaxNode AddReturnAttributes(SyntaxNode methodDeclarationdeclaration, params SyntaxNode[] attributes);
public abstract SyntaxNode AddReturnAttributes(SyntaxNode methodDeclarationdeclaration, IEnumerable<SyntaxNode> attributes);
- public SyntaxNode AsExpression(SyntaxNode expression, ITypeSymbol type);
- public abstract SyntaxNode AsExpression(SyntaxNode expression, SyntaxNode type);
+ protected IEnumerable<TNode> ClearTrivia<TNode>(IEnumerable<TNode> nodes) where TNode : SyntaxNode;
+ protected abstract TNode ClearTrivia<TNode>(TNode node) where TNode : SyntaxNode;
public abstract SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations=null);
+ public SyntaxNode CustomEventDeclaration(IEventSymbol symbol, IEnumerable<SyntaxNode> addAccessorStatements=null, IEnumerable<SyntaxNode> removeAccessorStatements=null);
+ public abstract SyntaxNode CustomEventDeclaration(string name, SyntaxNode type, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null, IEnumerable<SyntaxNode> parameters=null, IEnumerable<SyntaxNode> addAccessorStatements=null, IEnumerable<SyntaxNode> removeAccessorStatements=null);
+ public abstract SyntaxNode DelegateDeclaration(string name, IEnumerable<SyntaxNode> parameters=null, IEnumerable<string> typeParameters=null, SyntaxNode returnType=null, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null);
+ public abstract SyntaxNode EnumDeclaration(string name, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null, IEnumerable<SyntaxNode> members=null);
- public abstract SyntaxNode EnumDeclaration(string name, Accessibility accessibility=(Accessibility)(0), IEnumerable<SyntaxNode> members=null);
+ public SyntaxNode EventDeclaration(IEventSymbol symbol);
+ public abstract SyntaxNode EventDeclaration(string name, SyntaxNode type, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null);
+ public SyntaxNode FieldDeclaration(IFieldSymbol field);
public SyntaxNode FieldDeclaration(IFieldSymbol field, SyntaxNode initializer=null);
+ public abstract Accessibility GetAccessibility(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration);
+ public SyntaxNode GetDeclaration(SyntaxNode node);
+ public SyntaxNode GetDeclaration(SyntaxNode node, DeclarationKind kind);
+ public abstract DeclarationKind GetDeclarationKind(SyntaxNode declaration);
+ public abstract SyntaxNode GetExpression(SyntaxNode declaration);
+ public static SyntaxGenerator GetGenerator(Document document);
+ public abstract IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration);
+ public abstract DeclarationModifiers GetModifiers(SyntaxNode declaration);
+ public abstract string GetName(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration);
+ public abstract SyntaxNode GetType(SyntaxNode declaration);
public SyntaxNode IndexerDeclaration(IPropertySymbol indexer, IEnumerable<SyntaxNode> getterStatementsgetAccessorStatements=null, IEnumerable<SyntaxNode> setterStatementssetAccessorStatements=null);
public abstract SyntaxNode IndexerDeclaration(IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null, IEnumerable<SyntaxNode> getterStatementsgetAccessorStatements=null, IEnumerable<SyntaxNode> setterStatementssetAccessorStatements=null);
+ public SyntaxNode InsertAttributes(SyntaxNode declaration, int index, params SyntaxNode[] attributes);
+ public abstract SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes);
+ public SyntaxNode InsertMembers(SyntaxNode declaration, int index, params SyntaxNode[] members);
+ public abstract SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members);
+ public SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, params SyntaxNode[] imports);
+ public abstract SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports);
+ public abstract SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters);
+ public SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, params SyntaxNode[] attributes);
+ public abstract SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes);
- public SyntaxNode IsExpression(SyntaxNode expression, ITypeSymbol type);
- public abstract SyntaxNode IsExpression(SyntaxNode expression, SyntaxNode type);
+ public SyntaxNode IsTypeExpression(SyntaxNode expression, ITypeSymbol type);
+ public abstract SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type);
public abstract SyntaxNode MemberAccessExpression(SyntaxNode expression, SyntaxNode simpleNamememberName);
public SyntaxNode MemberAccessExpression(SyntaxNode expression, string identifermemberName);
+ protected static SyntaxNode PreserveTrivia<TNode>(TNode node, Func<TNode, SyntaxNode> nodeChanger) where TNode : SyntaxNode;
public SyntaxNode PropertyDeclaration(IPropertySymbol property, IEnumerable<SyntaxNode> getterStatementsgetAccessorStatements=null, IEnumerable<SyntaxNode> setterStatementssetAccessorStatements=null);
public abstract SyntaxNode PropertyDeclaration(string name, SyntaxNode type, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null, IEnumerable<SyntaxNode> getterStatementsgetAccessorStatements=null, IEnumerable<SyntaxNode> setterStatementssetAccessorStatements=null);
+ public abstract SyntaxNode RemoveAllAttributes(SyntaxNode declaration);
+ public abstract SyntaxNode RemoveAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes);
+ public SyntaxNode RemoveMembers(SyntaxNode declaration, params SyntaxNode[] members);
+ public SyntaxNode RemoveMembers(SyntaxNode declaration, IEnumerable<SyntaxNode> members);
+ public SyntaxNode RemoveNamespaceImports(SyntaxNode declaration, params SyntaxNode[] imports);
+ public SyntaxNode RemoveNamespaceImports(SyntaxNode declaration, IEnumerable<SyntaxNode> imports);
+ public SyntaxNode RemoveParameters(SyntaxNode declaration, IEnumerable<SyntaxNode> parameters);
+ public abstract SyntaxNode RemoveReturnAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes);
+ protected static SyntaxNode ReplaceWithTrivia(SyntaxNode root, SyntaxNode original, SyntaxNode replacement);
+ protected static SyntaxNode ReplaceWithTrivia(SyntaxNode root, SyntaxToken original, SyntaxToken replacement);
+ protected static SyntaxNode ReplaceWithTrivia<TNode>(SyntaxNode root, TNode original, Func<TNode, SyntaxNode> replacer) where TNode : SyntaxNode;
+ public SyntaxNode TryCastExpression(SyntaxNode expression, ITypeSymbol type);
+ public abstract SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type);
+ public SyntaxNode ValueReturningLambdaExpression(SyntaxNode expression);
+ public SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> statements);
+ public SyntaxNode VoidReturningLambdaExpression(SyntaxNode expression);
+ public SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> statements);
+ public abstract SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility);
+ public abstract SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression);
+ public abstract SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements);
+ public abstract SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers);
+ public abstract SyntaxNode WithName(SyntaxNode declaration, string name);
+ public abstract SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements);
+ public abstract SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements);
+ public abstract SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type);
public abstract SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameterNamestypeParameters);
public SyntaxNode WithTypeParameters(SyntaxNode declaration, params string[] typeParameterNamestypeParameters);
}
}
namespace Microsoft.CodeAnalysis.FindSymbols {
public static class SymbolFinder {
+ public static Task<IEnumerable<ISymbol>> FindDeclarationsAsync(Project project, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken=null);
+ public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Project project, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken=null);
+ public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Project project, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken=null);
+ public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Solution solution, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken=null);
+ public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Solution solution, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken=null);
}
}
}
```
## Miscellaneous
Changes that hide some APIs that shouldn't have been public or weren't fully thought through and changes that add some more useful overloads.
```diff
assembly Microsoft.CodeAnalysis {
namespace Microsoft.CodeAnalysis {
public abstract class Compilation {
+ public abstract bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
+ public EmitDifferenceResult EmitDifference(EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, ICollection<MethodDefinitionHandle> updatedMethods, CancellationToken cancellationToken=null);
+ public abstract IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
}
public abstract class ParseOptions {
+ public abstract IReadOnlyDictionary<string, string> Features { get; }
+ protected abstract ParseOptions CommonWithFeatures(IEnumerable<KeyValuePair<string, string>> features);
+ public ParseOptions WithFeatures(IEnumerable<KeyValuePair<string, string>> features);
}
public enum SymbolDisplayExtensionMethodStyle {
+ Default = 0,
StaticMethod = 02,
}
+ public enum SymbolFilter {
+ All = 7,
+ Member = 4,
+ Namespace = 1,
+ None = 0,
+ Type = 2,
+ TypeAndMember = 6,
}
public static class SyntaxNodeExtensions {
- public static TRoot ReplaceNode<TRoot, TNode>(this TRoot root, TNode oldNode, IEnumerable<TNode> newNodes) where TRoot : SyntaxNode where TNode : SyntaxNode;
- public static TRoot ReplaceNode<TRoot, TNode>(this TRoot root, TNode oldNode, TNode newNode) where TRoot : SyntaxNode where TNode : SyntaxNode;
+ public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, SyntaxNode newNode) where TRoot : SyntaxNode;
+ public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, IEnumerable<SyntaxNode> newNodes) where TRoot : SyntaxNode;
}
public enum SyntaxRemoveOptions {
+ AddElasticMarker = 32,
}
}
assembly Microsoft.CodeAnalysis.CSharp.Features {
- namespace Microsoft.CodeAnalysis.CSharp.CodeStyle {
- public static class CSharpCodeStyleOptions {
- public static readonly Option<bool> UseVarWhenDeclaringLocals;
}
}
}
assembly Microsoft.CodeAnalysis.EditorFeatures {
+ namespace Microsoft.CodeAnalysis.Editor.Peek {
+ public interface IPeekableItemFactory {
+ Task<IEnumerable<IPeekableItem>> GetPeekableItemsAsync(ISymbol symbol, Project project, IPeekResultFactory peekResultFactory, CancellationToken cancellationToken);
}
}
}
assembly Microsoft.CodeAnalysis.Workspaces {
namespace Microsoft.CodeAnalysis {
public class CustomWorkspace : Workspace {
+ public override bool CanApplyChange(ApplyChangesKind feature);
}
public sealed class DocumentInfo {
+ public DocumentInfo WithDefaultEncoding(Encoding encoding);
+ public DocumentInfo WithId(DocumentId id);
+ public DocumentInfo WithName(string name);
}
namespace Microsoft.CodeAnalysis.Differencing {
- public abstract class LongestCommonSubsequence<TSequence> {
- protected LongestCommonSubsequence();
- protected double ComputeDistance(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB);
- protected IEnumerable<LongestCommonSubsequence<TSequence>.Edit> GetEdits(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB);
- protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB);
- protected abstract bool ItemsEqual(TSequence sequenceA, int indexA, TSequence sequenceB, int indexB);
- protected struct Edit {
- public readonly EditKind Kind;
- public readonly int IndexA;
- public readonly int IndexB;
}
}
- public sealed class LongestCommonSubstring {
- public static double ComputeDistance(string s1, string s2);
- protected override bool ItemsEqual(string sequenceA, int indexA, string sequenceB, int indexB);
}
public abstract class TreeComparer<TNode> {
public abstract double GetDistance(TNode leftoldNode, TNode rightnewNode);
protected internal abstract bool TreesEqual(TNode leftoldNode, TNode rightnewNode);
}
}
namespace Microsoft.CodeAnalysis.Host {
public abstract class HostLanguageServices {
+ public TLanguageService GetRequiredService<TLanguageService>() where TLanguageService : ILanguageService;
}
public abstract class HostWorkspaceServices {
+ public TWorkspaceService GetRequiredService<TWorkspaceService>() where TWorkspaceService : IWorkspaceService;
}
}
namespace Microsoft.CodeAnalysis.Host.Mef {
public static class ServiceLayer {
+ public const string Desktop = "Desktop";
}
}
}
assembly Microsoft.CodeAnalysis.Workspaces.Desktop {
namespace Microsoft.CodeAnalysis {
public static class CommandLineProject {
- public static ProjectInfo CreateProjectInfo(Workspace workspace, string projectName, string language, IEnumerable<string> commandLineArgs, string projectDirectory);
- public static ProjectInfo CreateProjectInfo(Workspace workspace, string projectName, string language, string commandLine, string baseDirectory);
+ public static ProjectInfo CreateProjectInfo(string projectName, string language, IEnumerable<string> commandLineArgs, string projectDirectory, Workspace workspace=null);
+ public static ProjectInfo CreateProjectInfo(string projectName, string language, string commandLine, string baseDirectory, Workspace workspace=null);
}
}
namespace Microsoft.CodeAnalysis.Host.Mef {
+ public static class DesktopMefHostServices {
+ public static MefHostServices DefaultServices { get; }
}
}
namespace Microsoft.CodeAnalysis.MSBuild {
public sealed class MSBuildWorkspace : Workspace {
- protected override void AddAdditionalDocument(DocumentId documentId, IEnumerable<string> folders, string name, SourceText text=null);
- protected override void AddDocument(DocumentId documentId, IEnumerable<string> folders, string name, SourceText text=null, SourceCodeKind sourceCodeKind=(SourceCodeKind)(0));
+ protected override void AddDocument(DocumentInfo info, SourceText text);
- protected override void ChangedAdditionalDocumentText(DocumentId documentId, SourceText text);
}
}
}
```
| #API changes between VS 2015 Preview and VS 2015 CTP5
##Diagnostics and CodeFix API Changes
We have made some changes to the APIs to better support localization of the various strings that can be returned by analyzers. There are some useful overloads for some common cases that have been added. The `Microsoft.CodeAnalysis.Diagnostics.Internal` namespace and all types there have been made internal as those APIs were just an implementation detail.
```diff
assembly Microsoft.CodeAnalysis {
namespace Microsoft.CodeAnalysis {
public abstract class Diagnostic : IEquatable<Diagnostic>, IFormattable {
- public abstract string Category { get; }
- public abstract IReadOnlyList<string> CustomTags { get; }
- public abstract DiagnosticSeverity DefaultSeverity { get; }
+ public virtual DiagnosticSeverity DefaultSeverity { get; }
- public abstract string Description { get; }
+ public abstract DiagnosticDescriptor Descriptor { get; }
- public abstract string HelpLink { get; }
- public abstract bool IsEnabledByDefault { get; }
+ public static Diagnostic Create(string id, string category, LocalizableString message, DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, int warningLevel, LocalizableString title=null, LocalizableString description=null, string helpLink=null, Location location=null, IEnumerable<Location> additionalLocations=null, IEnumerable<string> customTags=null);
- public static Diagnostic Create(string id, string category, string message, DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, int warningLevel, string description=null, string helpLink=null, Location location=null, IEnumerable<Location> additionalLocations=null, IEnumerable<string> customTags=null);
- public abstract string GetMessage(CultureInfo culture=null);
+ public abstract string GetMessage(IFormatProvider formatProvider=null);
+ string System.IFormattable.ToString(string ignored, IFormatProvider formatProvider);
}
public class DiagnosticDescriptor {
+ public DiagnosticDescriptor(string id, LocalizableString title, LocalizableString messageFormat, string category, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault, LocalizableString description=null, string helpLink=null, params string[] customTags);
- public string Description { get; }
+ public LocalizableString Description { get; }
- public string MessageFormat { get; }
+ public LocalizableString MessageFormat { get; }
- public string Title { get; }
+ public LocalizableString Title { get; }
+ public override bool Equals(object obj);
+ public override int GetHashCode();
}
+ public sealed class LocalizableResourceString : LocalizableString {
+ public LocalizableResourceString(string nameOfLocalizableResource, ResourceManager resourceManager, Type resourceSource, params string[] formatArguments);
+ public override string ToString(IFormatProvider formatProvider);
}
+ public abstract class LocalizableString : IFormattable {
+ protected LocalizableString();
+ public static explicit operator string (LocalizableString localizableResource);
+ public static implicit operator LocalizableString (string fixedResource);
+ string System.IFormattable.ToString(string ignored, IFormatProvider formatProvider);
+ public sealed override string ToString();
+ public abstract string ToString(IFormatProvider formatProvider);
}
}
namespace Microsoft.CodeAnalysis.Diagnostics {
public struct AnalysisContext {
- public AnalysisContext(SessionStartAnalysisScope scope);
public void RegisterCodeBlockEndAction<TLanguageKindEnum>(Action<CodeBlockEndAnalysisContext> action) where TLanguageKindEnum : struct, ValueType;
public void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct, ValueType;
+ public void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds);
+ public void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct, ValueType;
public void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, params TLanguageKindEnum[] syntaxKinds) where TLanguageKindEnum : struct, ValueType;
}
public class AnalyzerOptions {
- public AnalyzerOptions(IEnumerable<AdditionalStream> additionalStreams, IDictionary<string, string> globalOptions, CultureInfo culture=null);
+ public AnalyzerOptions(ImmutableArray<AdditionalStream> additionalStreams, ImmutableDictionary<string, string> globalOptions, CultureInfo culture=null);
+ public AnalyzerOptions WithAdditionalStreams(ImmutableArray<AdditionalStream> additionalStreams);
+ public AnalyzerOptions WithCulture(CultureInfo culture);
+ public AnalyzerOptions WithGlobalOptions(ImmutableDictionary<string, string> globalOptions);
}
public struct CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct, ValueType {
+ public void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds);
}
public struct CompilationEndAnalysisContext {
- public CompilationEndAnalysisContext(Compilation compilation, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
public struct CompilationStartAnalysisContext {
- public CompilationStartAnalysisContext(CompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken);
public void RegisterCodeBlockEndAction<TLanguageKindEnum>(Action<CodeBlockEndAnalysisContext> action) where TLanguageKindEnum : struct, ValueType;
public void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct, ValueType;
+ public void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds);
+ public void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct, ValueType;
public void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, params TLanguageKindEnum[] syntaxKinds) where TLanguageKindEnum : struct, ValueType;
}
public struct SemanticModelAnalysisContext {
- public SemanticModelAnalysisContext(SemanticModel semanticModel, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
public struct SymbolAnalysisContext {
- public SymbolAnalysisContext(ISymbol symbol, Compilation compilation, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
public struct SyntaxNodeAnalysisContext {
- public SyntaxNodeAnalysisContext(SyntaxNode node, SemanticModel semanticModel, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
public struct SyntaxTreeAnalysisContext {
- public SyntaxTreeAnalysisContext(SyntaxTree tree, AnalyzerOptions options, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken);
}
}
}
assembly Microsoft.CodeAnalysis.Desktop {
namespace Microsoft.CodeAnalysis {
public class RuleSet {
- public RuleSet(string filePath, ReportDiagnostic generalOption, IDictionary<string, ReportDiagnostic> specificOptions, IEnumerable<RuleSetInclude> includes);
+ public RuleSet(string filePath, ReportDiagnostic generalOption, ImmutableDictionary<string, ReportDiagnostic> specificOptions, ImmutableArray<RuleSetInclude> includes);
}
}
}
assembly Microsoft.CodeAnalysis.Workspaces {
namespace Microsoft.CodeAnalysis {
public class Project {
+ public TextDocument AddAdditionalDocument(string name, SourceText text, IEnumerable<string> folders=null);
+ public TextDocument AddAdditionalDocument(string name, string text, IEnumerable<string> folders=null);
+ public Document AddDocument(string name, SyntaxNode syntaxRoot, IEnumerable<string> folders=null);
+ public Project RemoveAdditionalDocument(DocumentId documentId);
}
public class Solution {
+ public Solution AddAdditionalDocument(DocumentId documentId, string name, string text, IEnumerable<string> folders=null, string filePath=null);
+ public Solution AddDocument(DocumentId documentId, string name, SyntaxNode syntaxRoot, IEnumerable<string> folders=null, string filePath=null, bool isGenerated=false, PreservationMode preservationMode=(PreservationMode)(0));
}
public abstract class Workspace : IDisposable {
public virtual Solution CurrentSolution { get; }
- protected virtual void AddAdditionalDocument(DocumentId documentId, IEnumerable<string> folders, string name, SourceText text=null);
+ protected virtual void AddAdditionalDocument(DocumentInfo info, SourceText text);
- protected virtual void AddDocument(DocumentId documentId, IEnumerable<string> folders, string name, SourceText text=null, SourceCodeKind sourceCodeKind=(SourceCodeKind)(0));
+ protected virtual void AddDocument(DocumentInfo info, SourceText text);
}
}
namespace Microsoft.CodeAnalysis.CodeFixes {
public struct CodeFixContext {
- public CodeFixContext(Document document, Diagnostic diagnostic, Action<CodeAction, IEnumerable<Diagnostic>> registerFix, CancellationToken cancellationToken);
+ public CodeFixContext(Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerFix, CancellationToken cancellationToken);
- public CodeFixContext(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, Action<CodeAction, IEnumerable<Diagnostic>> registerFix, CancellationToken cancellationToken);
+ public CodeFixContext(Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerFix, CancellationToken cancellationToken);
public IEnumerable<Diagnostic>ImmutableArray<Diagnostic> Diagnostics { get; }
+ public void RegisterFix(CodeAction action, ImmutableArray<Diagnostic> diagnostics);
}
public abstract class CodeFixProvider {
- public abstract FixAllProvider GetFixAllProvider();
+ public virtual FixAllProvider GetFixAllProvider();
}
}
}
```
##Changes caused by language features
We've been continuing to work on adding\refining String Interpolation and nameof in both languages and that's changed some APIs.
```diff
assembly Microsoft.CodeAnalysis {
namespace Microsoft.CodeAnalysis {
public enum CandidateReason {
+ MemberGroup = 16,
}
}
assembly Microsoft.CodeAnalysis.CSharp {
namespace Microsoft.CodeAnalysis {
public static class CSharpExtensions {
+ public static int IndexOf(this SyntaxTokenList list, SyntaxKind kind);
+ public static int IndexOf(this SyntaxTriviaList list, SyntaxKind kind);
+ public static int IndexOf<TNode>(this SeparatedSyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
+ public static int IndexOf<TNode>(this SyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
}
}
namespace Microsoft.CodeAnalysis.CSharp {
public sealed class CSharpCompilation : Compilation {
+ public override bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
+ public override IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
}
public sealed class CSharpParseOptions : ParseOptions, IEquatable<CSharpParseOptions> {
+ public override IReadOnlyDictionary<string, string> Features { get; }
+ protected override ParseOptions CommonWithFeatures(IEnumerable<KeyValuePair<string, string>> features);
+ public new CSharpParseOptions WithFeatures(IEnumerable<KeyValuePair<string, string>> features);
}
public abstract class CSharpSyntaxRewriter : CSharpSyntaxVisitor<SyntaxNode> {
- public override SyntaxNode VisitNameOfExpression(NameOfExpressionSyntax node);
}
public abstract class CSharpSyntaxVisitor {
- public virtual void VisitNameOfExpression(NameOfExpressionSyntax node);
}
public abstract class CSharpSyntaxVisitor<TResult> {
- public virtual TResult VisitNameOfExpression(NameOfExpressionSyntax node);
}
public enum LanguageVersion {
- Experimental = 2147483647,
}
public static class SyntaxFactory {
+ public static InterpolatedStringInsertSyntax InterpolatedStringInsert(ExpressionSyntax expression, SyntaxToken comma, ExpressionSyntax alignment, SyntaxToken format);
- public static InterpolatedStringInsertSyntax InterpolatedStringInsert(ExpressionSyntax expression, SyntaxToken comma, ExpressionSyntax alignment, SyntaxToken colon, SyntaxToken format);
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimalDecimal value, SyntaxTriviaList trailing);
public static SyntaxToken Literal(decimalDecimal value);
public static SyntaxToken Literal(string text, decimalDecimal value);
- public static NameOfExpressionSyntax NameOfExpression(IdentifierNameSyntax nameOfIdentifier, ExpressionSyntax argument);
- public static NameOfExpressionSyntax NameOfExpression(IdentifierNameSyntax nameOfIdentifier, SyntaxToken openParenToken, ExpressionSyntax argument, SyntaxToken closeParenToken);
- public static NameOfExpressionSyntax NameOfExpression(string nameOfIdentifier, ExpressionSyntax argument);
+ public static UsingDirectiveSyntax UsingDirective(SyntaxToken staticKeyword, NameEqualsSyntax alias, NameSyntax name);
- public static UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, NameEqualsSyntax alias, NameSyntax name, SyntaxToken semicolonToken);
+ public static UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax alias, NameSyntax name, SyntaxToken semicolonToken);
}
public enum SyntaxKind : ushort {
- NameOfExpression = (ushort)8768,
}
}
namespace Microsoft.CodeAnalysis.CSharp.Syntax {
public sealed class InterpolatedStringInsertSyntax : CSharpSyntaxNode {
- public SyntaxToken Colon { get; }
+ public InterpolatedStringInsertSyntax Update(ExpressionSyntax expression, SyntaxToken comma, ExpressionSyntax alignment, SyntaxToken format);
- public InterpolatedStringInsertSyntax Update(ExpressionSyntax expression, SyntaxToken comma, ExpressionSyntax alignment, SyntaxToken colon, SyntaxToken format);
- public InterpolatedStringInsertSyntax WithColon(SyntaxToken colon);
}
- public sealed class NameOfExpressionSyntax : ExpressionSyntax {
- public ExpressionSyntax Argument { get; }
- public SyntaxToken CloseParenToken { get; }
- public IdentifierNameSyntax NameOfIdentifier { get; }
- public SyntaxToken OpenParenToken { get; }
- public override void Accept(CSharpSyntaxVisitor visitor);
- public override TResult Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor);
- public NameOfExpressionSyntax Update(IdentifierNameSyntax nameOfIdentifier, SyntaxToken openParenToken, ExpressionSyntax argument, SyntaxToken closeParenToken);
- public NameOfExpressionSyntax WithArgument(ExpressionSyntax argument);
- public NameOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken);
- public NameOfExpressionSyntax WithNameOfIdentifier(IdentifierNameSyntax nameOfIdentifier);
- public NameOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken);
}
public sealed class UsingDirectiveSyntax : CSharpSyntaxNode {
+ public SyntaxToken StaticKeyword { get; }
- public UsingDirectiveSyntax Update(SyntaxToken usingKeyword, NameEqualsSyntax alias, NameSyntax name, SyntaxToken semicolonToken);
+ public UsingDirectiveSyntax Update(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax alias, NameSyntax name, SyntaxToken semicolonToken);
+ public UsingDirectiveSyntax WithStaticKeyword(SyntaxToken staticKeyword);
}
}
}
assembly Microsoft.CodeAnalysis.VisualBasic {
namespace Microsoft.CodeAnalysis {
public sealed class VisualBasicExtensions {
+ public static bool Any<TNode>(this SeparatedSyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
+ public static bool Any<TNode>(this SyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
+ public static int IndexOf(this SyntaxTokenList list, SyntaxKind kind);
+ public static int IndexOf(this SyntaxTriviaList list, SyntaxKind kind);
+ public static int IndexOf<TNode>(this SeparatedSyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
+ public static int IndexOf<TNode>(this SyntaxList<TNode> list, SyntaxKind kind) where TNode : SyntaxNode;
}
}
namespace Microsoft.CodeAnalysis.VisualBasic {
public enum LanguageVersion {
- Experimental = 2147483647,
}
public class SyntaxFactory {
public static SyntaxToken DecimalLiteralToken(SyntaxTriviaList leadingTrivia, string text, TypeCharacter typeSuffix, decimalDecimal value, SyntaxTriviaList trailingTrivia);
public static SyntaxToken DecimalLiteralToken(string text, TypeCharacter typeSuffix, decimalDecimal value);
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimalDecimal value, SyntaxTriviaList trailing);
public static SyntaxToken Literal(decimalDecimal value);
public static SyntaxToken Literal(string text, decimalDecimal value);
+ public static NameOfExpressionSyntax NameOfExpression(SyntaxToken nameOfKeyword, SyntaxToken openParenToken, ExpressionSyntax argument, SyntaxToken closeParenToken);
+ public static NameOfExpressionSyntax NameOfExpression(ExpressionSyntax argument);
}
public enum SyntaxKind : ushort {
+ NameOfExpression = (ushort)779,
+ NameOfKeyword = (ushort)778,
}
public sealed class VisualBasicCompilation : Compilation {
+ public override bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
+ public override IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
}
public sealed class VisualBasicParseOptions : ParseOptions, IEquatable<VisualBasicParseOptions> {
+ public override IReadOnlyDictionary<string, string> Features { get; }
+ protected override ParseOptions CommonWithFeatures(IEnumerable<KeyValuePair<string, string>> features);
+ public new VisualBasicParseOptions WithFeatures(IEnumerable<KeyValuePair<string, string>> features);
}
public abstract class VisualBasicSyntaxRewriter : VisualBasicSyntaxVisitor<SyntaxNode> {
+ public override SyntaxNode VisitNameOfExpression(NameOfExpressionSyntax node);
}
public abstract class VisualBasicSyntaxVisitor {
+ public virtual void VisitNameOfExpression(NameOfExpressionSyntax node);
}
public abstract class VisualBasicSyntaxVisitor<TResult> {
+ public virtual TResult VisitNameOfExpression(NameOfExpressionSyntax node);
}
}
namespace Microsoft.CodeAnalysis.VisualBasic.Syntax {
+ public sealed class NameOfExpressionSyntax : ExpressionSyntax {
+ public ExpressionSyntax Argument { get; }
+ public SyntaxToken CloseParenToken { get; }
+ public SyntaxToken NameOfKeyword { get; }
+ public SyntaxToken OpenParenToken { get; }
+ public override void Accept(VisualBasicSyntaxVisitor visitor);
+ public override TResult Accept<TResult>(VisualBasicSyntaxVisitor<TResult> visitor);
+ public NameOfExpressionSyntax Update(SyntaxToken nameOfKeyword, SyntaxToken openParenToken, ExpressionSyntax argument, SyntaxToken closeParenToken);
+ public NameOfExpressionSyntax WithArgument(ExpressionSyntax argument);
+ public NameOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken);
+ public NameOfExpressionSyntax WithNameOfKeyword(SyntaxToken nameOfKeyword);
+ public NameOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken);
}
}
}
```
##New functionality
We've added some new APIs to make it easier to generate code from Code Fixes\Refactorings and some useful overloads in the SymbolFinder.
```diff
assembly Microsoft.CodeAnalysis.Workspaces {
namespace Microsoft.CodeAnalysis.CodeGeneration {
+ public enum DeclarationKind {
+ Attribute = 22,
+ Class = 2,
+ CompilationUnit = 1,
+ Constructor = 10,
+ ConversionOperator = 9,
+ CustomEvent = 17,
+ Delegate = 6,
+ Destructor = 11,
+ Enum = 5,
+ EnumMember = 15,
+ Event = 16,
+ Field = 12,
+ Indexer = 14,
+ Interface = 4,
+ LambdaExpression = 23,
+ LocalVariable = 21,
+ Method = 7,
+ Namespace = 18,
+ NamespaceImport = 19,
+ None = 0,
+ Operator = 8,
+ Parameter = 20,
+ Property = 13,
+ Struct = 3,
}
public struct DeclarationModifiers : IEquatable<DeclarationModifiers> {
+ public bool Equals(DeclarationModifiers modifiers);
+ public override bool Equals(object obj);
+ public override int GetHashCode();
+ public static bool operator ==(DeclarationModifiers left, DeclarationModifiers right);
+ public static bool operator !=(DeclarationModifiers left, DeclarationModifiers right);
+ public override string ToString();
}
+ public class SymbolEditor {
+ public SymbolEditor(Document document);
+ public SymbolEditor(Solution solution);
+ public Solution CurrentSolution { get; }
+ public Solution OriginalSolution { get; }
+ public Task<ISymbol> EditAllDeclarationsAsync(ISymbol symbol, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> declarationEditor, CancellationToken cancellationToken=null);
+ public Task<ISymbol> EditOneDeclarationAsync(ISymbol symbol, ISymbol member, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> declarationEditor, CancellationToken cancellationToken=null);
+ public Task<ISymbol> EditOneDeclarationAsync(ISymbol symbol, Location location, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> declarationEditor, CancellationToken cancellationToken=null);
+ public Task<ISymbol> EditOneDeclarationAsync(ISymbol symbol, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> declarationEditor, CancellationToken cancellationToken=null);
+ public IEnumerable<Document> GetChangedDocuments();
+ public Task<ISymbol> GetCurrentSymbolAsync(ISymbol symbol, CancellationToken cancellationToken=null);
}
public abstract class SyntaxGenerator : ILanguageService {
- protected static DeclarationModifiers constructorModifers;
- protected static DeclarationModifiers fieldModifiers;
- protected static DeclarationModifiers indexerModifiers;
- protected static DeclarationModifiers methodModifiers;
- protected static DeclarationModifiers propertyModifiers;
- protected static DeclarationModifiers typeModifiers;
+ public static SyntaxRemoveOptions DefaultRemoveOptions;
public abstract SyntaxNode AddAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes);
+ public SyntaxNode AddMembers(SyntaxNode declaration, params SyntaxNode[] members);
+ public SyntaxNode AddMembers(SyntaxNode declaration, IEnumerable<SyntaxNode> members);
+ public SyntaxNode AddNamespaceImports(SyntaxNode declaration, params SyntaxNode[] imports);
+ public SyntaxNode AddNamespaceImports(SyntaxNode declaration, IEnumerable<SyntaxNode> imports);
+ public SyntaxNode AddParameters(SyntaxNode declaration, IEnumerable<SyntaxNode> parameters);
public SyntaxNode AddReturnAttributes(SyntaxNode methodDeclarationdeclaration, params SyntaxNode[] attributes);
public abstract SyntaxNode AddReturnAttributes(SyntaxNode methodDeclarationdeclaration, IEnumerable<SyntaxNode> attributes);
- public SyntaxNode AsExpression(SyntaxNode expression, ITypeSymbol type);
- public abstract SyntaxNode AsExpression(SyntaxNode expression, SyntaxNode type);
+ protected IEnumerable<TNode> ClearTrivia<TNode>(IEnumerable<TNode> nodes) where TNode : SyntaxNode;
+ protected abstract TNode ClearTrivia<TNode>(TNode node) where TNode : SyntaxNode;
public abstract SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations=null);
+ public SyntaxNode CustomEventDeclaration(IEventSymbol symbol, IEnumerable<SyntaxNode> addAccessorStatements=null, IEnumerable<SyntaxNode> removeAccessorStatements=null);
+ public abstract SyntaxNode CustomEventDeclaration(string name, SyntaxNode type, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null, IEnumerable<SyntaxNode> parameters=null, IEnumerable<SyntaxNode> addAccessorStatements=null, IEnumerable<SyntaxNode> removeAccessorStatements=null);
+ public abstract SyntaxNode DelegateDeclaration(string name, IEnumerable<SyntaxNode> parameters=null, IEnumerable<string> typeParameters=null, SyntaxNode returnType=null, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null);
+ public abstract SyntaxNode EnumDeclaration(string name, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null, IEnumerable<SyntaxNode> members=null);
- public abstract SyntaxNode EnumDeclaration(string name, Accessibility accessibility=(Accessibility)(0), IEnumerable<SyntaxNode> members=null);
+ public SyntaxNode EventDeclaration(IEventSymbol symbol);
+ public abstract SyntaxNode EventDeclaration(string name, SyntaxNode type, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null);
+ public SyntaxNode FieldDeclaration(IFieldSymbol field);
public SyntaxNode FieldDeclaration(IFieldSymbol field, SyntaxNode initializer=null);
+ public abstract Accessibility GetAccessibility(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration);
+ public SyntaxNode GetDeclaration(SyntaxNode node);
+ public SyntaxNode GetDeclaration(SyntaxNode node, DeclarationKind kind);
+ public abstract DeclarationKind GetDeclarationKind(SyntaxNode declaration);
+ public abstract SyntaxNode GetExpression(SyntaxNode declaration);
+ public static SyntaxGenerator GetGenerator(Document document);
+ public abstract IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration);
+ public abstract DeclarationModifiers GetModifiers(SyntaxNode declaration);
+ public abstract string GetName(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration);
+ public abstract IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration);
+ public abstract SyntaxNode GetType(SyntaxNode declaration);
public SyntaxNode IndexerDeclaration(IPropertySymbol indexer, IEnumerable<SyntaxNode> getterStatementsgetAccessorStatements=null, IEnumerable<SyntaxNode> setterStatementssetAccessorStatements=null);
public abstract SyntaxNode IndexerDeclaration(IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null, IEnumerable<SyntaxNode> getterStatementsgetAccessorStatements=null, IEnumerable<SyntaxNode> setterStatementssetAccessorStatements=null);
+ public SyntaxNode InsertAttributes(SyntaxNode declaration, int index, params SyntaxNode[] attributes);
+ public abstract SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes);
+ public SyntaxNode InsertMembers(SyntaxNode declaration, int index, params SyntaxNode[] members);
+ public abstract SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members);
+ public SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, params SyntaxNode[] imports);
+ public abstract SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports);
+ public abstract SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters);
+ public SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, params SyntaxNode[] attributes);
+ public abstract SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes);
- public SyntaxNode IsExpression(SyntaxNode expression, ITypeSymbol type);
- public abstract SyntaxNode IsExpression(SyntaxNode expression, SyntaxNode type);
+ public SyntaxNode IsTypeExpression(SyntaxNode expression, ITypeSymbol type);
+ public abstract SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type);
public abstract SyntaxNode MemberAccessExpression(SyntaxNode expression, SyntaxNode simpleNamememberName);
public SyntaxNode MemberAccessExpression(SyntaxNode expression, string identifermemberName);
+ protected static SyntaxNode PreserveTrivia<TNode>(TNode node, Func<TNode, SyntaxNode> nodeChanger) where TNode : SyntaxNode;
public SyntaxNode PropertyDeclaration(IPropertySymbol property, IEnumerable<SyntaxNode> getterStatementsgetAccessorStatements=null, IEnumerable<SyntaxNode> setterStatementssetAccessorStatements=null);
public abstract SyntaxNode PropertyDeclaration(string name, SyntaxNode type, Accessibility accessibility=(Accessibility)(0), DeclarationModifiers modifiers=null, IEnumerable<SyntaxNode> getterStatementsgetAccessorStatements=null, IEnumerable<SyntaxNode> setterStatementssetAccessorStatements=null);
+ public abstract SyntaxNode RemoveAllAttributes(SyntaxNode declaration);
+ public abstract SyntaxNode RemoveAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes);
+ public SyntaxNode RemoveMembers(SyntaxNode declaration, params SyntaxNode[] members);
+ public SyntaxNode RemoveMembers(SyntaxNode declaration, IEnumerable<SyntaxNode> members);
+ public SyntaxNode RemoveNamespaceImports(SyntaxNode declaration, params SyntaxNode[] imports);
+ public SyntaxNode RemoveNamespaceImports(SyntaxNode declaration, IEnumerable<SyntaxNode> imports);
+ public SyntaxNode RemoveParameters(SyntaxNode declaration, IEnumerable<SyntaxNode> parameters);
+ public abstract SyntaxNode RemoveReturnAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes);
+ protected static SyntaxNode ReplaceWithTrivia(SyntaxNode root, SyntaxNode original, SyntaxNode replacement);
+ protected static SyntaxNode ReplaceWithTrivia(SyntaxNode root, SyntaxToken original, SyntaxToken replacement);
+ protected static SyntaxNode ReplaceWithTrivia<TNode>(SyntaxNode root, TNode original, Func<TNode, SyntaxNode> replacer) where TNode : SyntaxNode;
+ public SyntaxNode TryCastExpression(SyntaxNode expression, ITypeSymbol type);
+ public abstract SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type);
+ public SyntaxNode ValueReturningLambdaExpression(SyntaxNode expression);
+ public SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> statements);
+ public SyntaxNode VoidReturningLambdaExpression(SyntaxNode expression);
+ public SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> statements);
+ public abstract SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility);
+ public abstract SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression);
+ public abstract SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements);
+ public abstract SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers);
+ public abstract SyntaxNode WithName(SyntaxNode declaration, string name);
+ public abstract SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements);
+ public abstract SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements);
+ public abstract SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type);
public abstract SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameterNamestypeParameters);
public SyntaxNode WithTypeParameters(SyntaxNode declaration, params string[] typeParameterNamestypeParameters);
}
}
namespace Microsoft.CodeAnalysis.FindSymbols {
public static class SymbolFinder {
+ public static Task<IEnumerable<ISymbol>> FindDeclarationsAsync(Project project, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken=null);
+ public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Project project, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken=null);
+ public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Project project, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken=null);
+ public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Solution solution, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken=null);
+ public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Solution solution, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken=null);
}
}
}
```
## Miscellaneous
Changes that hide some APIs that shouldn't have been public or weren't fully thought through and changes that add some more useful overloads.
```diff
assembly Microsoft.CodeAnalysis {
namespace Microsoft.CodeAnalysis {
public abstract class Compilation {
+ public abstract bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
+ public EmitDifferenceResult EmitDifference(EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, ICollection<MethodDefinitionHandle> updatedMethods, CancellationToken cancellationToken=null);
+ public abstract IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter=(SymbolFilter)(6), CancellationToken cancellationToken=null);
}
public abstract class ParseOptions {
+ public abstract IReadOnlyDictionary<string, string> Features { get; }
+ protected abstract ParseOptions CommonWithFeatures(IEnumerable<KeyValuePair<string, string>> features);
+ public ParseOptions WithFeatures(IEnumerable<KeyValuePair<string, string>> features);
}
public enum SymbolDisplayExtensionMethodStyle {
+ Default = 0,
StaticMethod = 02,
}
+ public enum SymbolFilter {
+ All = 7,
+ Member = 4,
+ Namespace = 1,
+ None = 0,
+ Type = 2,
+ TypeAndMember = 6,
}
public static class SyntaxNodeExtensions {
- public static TRoot ReplaceNode<TRoot, TNode>(this TRoot root, TNode oldNode, IEnumerable<TNode> newNodes) where TRoot : SyntaxNode where TNode : SyntaxNode;
- public static TRoot ReplaceNode<TRoot, TNode>(this TRoot root, TNode oldNode, TNode newNode) where TRoot : SyntaxNode where TNode : SyntaxNode;
+ public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, SyntaxNode newNode) where TRoot : SyntaxNode;
+ public static TRoot ReplaceNode<TRoot>(this TRoot root, SyntaxNode oldNode, IEnumerable<SyntaxNode> newNodes) where TRoot : SyntaxNode;
}
public enum SyntaxRemoveOptions {
+ AddElasticMarker = 32,
}
}
assembly Microsoft.CodeAnalysis.CSharp.Features {
- namespace Microsoft.CodeAnalysis.CSharp.CodeStyle {
- public static class CSharpCodeStyleOptions {
- public static readonly Option<bool> UseVarWhenDeclaringLocals;
}
}
}
assembly Microsoft.CodeAnalysis.EditorFeatures {
+ namespace Microsoft.CodeAnalysis.Editor.Peek {
+ public interface IPeekableItemFactory {
+ Task<IEnumerable<IPeekableItem>> GetPeekableItemsAsync(ISymbol symbol, Project project, IPeekResultFactory peekResultFactory, CancellationToken cancellationToken);
}
}
}
assembly Microsoft.CodeAnalysis.Workspaces {
namespace Microsoft.CodeAnalysis {
public class CustomWorkspace : Workspace {
+ public override bool CanApplyChange(ApplyChangesKind feature);
}
public sealed class DocumentInfo {
+ public DocumentInfo WithDefaultEncoding(Encoding encoding);
+ public DocumentInfo WithId(DocumentId id);
+ public DocumentInfo WithName(string name);
}
namespace Microsoft.CodeAnalysis.Differencing {
- public abstract class LongestCommonSubsequence<TSequence> {
- protected LongestCommonSubsequence();
- protected double ComputeDistance(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB);
- protected IEnumerable<LongestCommonSubsequence<TSequence>.Edit> GetEdits(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB);
- protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB);
- protected abstract bool ItemsEqual(TSequence sequenceA, int indexA, TSequence sequenceB, int indexB);
- protected struct Edit {
- public readonly EditKind Kind;
- public readonly int IndexA;
- public readonly int IndexB;
}
}
- public sealed class LongestCommonSubstring {
- public static double ComputeDistance(string s1, string s2);
- protected override bool ItemsEqual(string sequenceA, int indexA, string sequenceB, int indexB);
}
public abstract class TreeComparer<TNode> {
public abstract double GetDistance(TNode leftoldNode, TNode rightnewNode);
protected internal abstract bool TreesEqual(TNode leftoldNode, TNode rightnewNode);
}
}
namespace Microsoft.CodeAnalysis.Host {
public abstract class HostLanguageServices {
+ public TLanguageService GetRequiredService<TLanguageService>() where TLanguageService : ILanguageService;
}
public abstract class HostWorkspaceServices {
+ public TWorkspaceService GetRequiredService<TWorkspaceService>() where TWorkspaceService : IWorkspaceService;
}
}
namespace Microsoft.CodeAnalysis.Host.Mef {
public static class ServiceLayer {
+ public const string Desktop = "Desktop";
}
}
}
assembly Microsoft.CodeAnalysis.Workspaces.Desktop {
namespace Microsoft.CodeAnalysis {
public static class CommandLineProject {
- public static ProjectInfo CreateProjectInfo(Workspace workspace, string projectName, string language, IEnumerable<string> commandLineArgs, string projectDirectory);
- public static ProjectInfo CreateProjectInfo(Workspace workspace, string projectName, string language, string commandLine, string baseDirectory);
+ public static ProjectInfo CreateProjectInfo(string projectName, string language, IEnumerable<string> commandLineArgs, string projectDirectory, Workspace workspace=null);
+ public static ProjectInfo CreateProjectInfo(string projectName, string language, string commandLine, string baseDirectory, Workspace workspace=null);
}
}
namespace Microsoft.CodeAnalysis.Host.Mef {
+ public static class DesktopMefHostServices {
+ public static MefHostServices DefaultServices { get; }
}
}
namespace Microsoft.CodeAnalysis.MSBuild {
public sealed class MSBuildWorkspace : Workspace {
- protected override void AddAdditionalDocument(DocumentId documentId, IEnumerable<string> folders, string name, SourceText text=null);
- protected override void AddDocument(DocumentId documentId, IEnumerable<string> folders, string name, SourceText text=null, SourceCodeKind sourceCodeKind=(SourceCodeKind)(0));
+ protected override void AddDocument(DocumentInfo info, SourceText text);
- protected override void ChangedAdditionalDocumentText(DocumentId documentId, SourceText text);
}
}
}
```
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/wiki/Reporting-Visual-Studio-crashes-and-performance-issues.md | This document provides specific guidance and best practices for reporting crashes and performance issues in Visual Studio by gathering heap dumps / performance traces as part of Visual Studio's built-in Report a Problem workflow. For a general overview of how to report problems in Visual Studio, see "[How to Report a Problem with Visual Studio 2017](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017)".
:arrow_right: **The product teams review all feedback submitted through the [Report a Problem](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017) tool.** Users are not required to follow the steps in this document to provide feedback.
# Audience
This document describes the best known ways to report actionable product feedback, i.e. feedback for which the product team is most likely to diagnose and resolve quickly. It focuses on two categories of severe problems which are historically challenging to resolve.
:bulb: After identifying the case which best describes your issue, follow the feedback steps specific to that case.
* [**Crashes:**](#crashes) A crash occurs when when the process (Visual Studio) terminates unexpectedly.
* [**Performance issues:**](#performance-issues) Performance problems fall into several categories, but are typically handled the same way.
* Solution load
* Typing
* Open/closing documents
* Searching
* Analyzers and code fixes
* Any other specific action which is slower than desired
# Crashes
## Directly reproducible crashes
Directly reproducible crashes are cases which have all of the following characteristics:
1. Can be observed by following a known set of steps
2. Can be observed on multiple computers (if available)
3. If the steps involve opening a project or document, can be reproduced in sample code or a project which can be linked to or provided as part of the feedback
For these issues, follow the steps in "[How to Report a Problem](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017)" and be sure to include:
- The steps to reproduce the problem
- A standalone repro project as described above. If this is not possible, then please include:
- The language of the open projects (C#, C++, etc.)
- The kind of project (Console Application, ASP.NET, etc.)
- Any extensions that are installed
:bulb: **Most valuable feedback:** For this case, the most valuable feedback is the set of steps to reproduce the issue along with sample source code.
## Unknown crashes
If you're not sure what's causing your crashes or they seem random, then you can capture dumps locally each time Visual Studio crashes and attach those to separate feedback items. To save dumps locally when Visual Studio crashes, set the following registry entries:
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\devenv.exe]
"DumpFolder"="C:\\Crashdumps"
"DumpCount"=dword:00000005
"DumpType"=dword:00000002
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\ServiceHub.RoslynCodeAnalysisService32.exe]
"DumpFolder"="C:\\Crashdumps"
"DumpCount"=dword:00000005
"DumpType"=dword:00000002
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\ServiceHub.RoslynCodeAnalysisService.exe]
"DumpFolder"="C:\\Crashdumps"
"DumpCount"=dword:00000005
"DumpType"=dword:00000002
```
⚠️ Each dump file produced by this method will be up to 4GiB in size. Make sure to set `DumpFolder` to a location with adequate drive space or adjust the `DumpCount` appropriately.
Each time Visual Studio crashes, it will create a dump file **devenv.exe.[number].dmp** file in the configured location. If one of the helper processes crashes, it will create a dump file **ServiceHub.RoslynCodeAnalysisService32.exe.[number].dmp** or **ServiceHub.RoslynCodeAnalysisService.exe.[number].dmp** file in the configured location.
Then, use Visual Studio's "Report a Problem..." feature. It will allow you to attach the appropriate dump.
1. Locate the dump file for the crash you are reporting (look for a file with the correct Creation time)
2. If possible, zip the file (*.zip) to reduce its size before submitting feedback
3. Follow the steps in "[How to Report a Problem](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017)", and attach the heap dump to a new feedback item.
⚠️ Do not attach heap dumps to existing feedback items. Please create a new feedback item for each heap dump you would like to submit. If you were requested to provide a heap dump in order to resolve a previous feedback item, simply reply to the request with a link to the new feedback item where the heap dump is attached.
:bulb: **Most valuable feedback:** For this case, the most valuable feedback is the heap dump captured at the time of the crash.
# Performance Issues
When diagnosing performance issues, the goal is to capture a performance trace while performing the slow/hanging action.
:bulb: When possible, isolate each scenario in a separate, specific feedback report. For example, if typing and navigation are both slow, follow the steps below once per issue. This helps the product team isolate the cause of specific issues.
For best results in capturing the performance, follow these steps:
1. If not already running, have a copy of Visual Studio open where you will reproduce the problem
* Have everything set up to reproduce the problem. For example, if you need a particular project to be loaded with a specific file opened, then be sure both of those steps are complete before proceeding.
* If you are *not* reporting a problem specific to loading a solution, try to wait 5-10 minutes (or more, depending on solution size) after opening the solution before recording the performance trace. The solution load process produces a large amount of data, so waiting for a few minutes helps us focus on the specific problem you are reporting.
2. Start a second copy of Visual Studio *with no solution open*
3. In the new copy of Visual Studio, open the **Report a Problem** tool
4. Follow the steps in "[How to Report a Problem](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017)" until you reach the "Provide a trace and heap dump (optional)" step.
5. Choose to record the first copy of Visual Studio (the one encountering performance problems), and start recording.
* The Steps Recorder application will appear begin recording.
* **During the recording,** perform the problematic action in the separate copy of Visual Studio. It is very difficult for us to correct specific performance problems if they do not appear within the recorded time.
* If the action is shorter than 30 seconds and can be easily repeated, repeat the action to further demonstrate the problem.
* For most cases, a trace of 60 seconds is sufficient to demonstrate the problems, especially if the problematic action lasted (or was repeated) for more than 30 seconds. The duration can be adjusted as necessary to capture the behavior you would like fixed.
6. Click "Stop Record" in Steps Recorder. It may take a few minutes to process the performance trace.
7. Once complete, there will be several attachments to your feedback. Attach any additional files that may help reproduce the problem (a sample project, screenshots, videos, etc.).
8. Submit the feedback.
⚠️ Do not directly attach performance traces to existing feedback items on Developer Community website. Requesting/providing additional information is a supported workflow in Visual Studio's built-in Report a Problem tool. If a performance trace is required in order to resolve a previous feedback item, we will set the state of the feedback item to "Need More Info", which can be responded to in the same way as reporting a new problem. For detailed instruction, please refer to ["Need More Info" section](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017?view=vs-2017#when-further-information-is-needed-need-more-info) in Report a Problem tool's document.
:bulb: **Most valuable feedback:** For almost all performance issues, the most valuable feedback is a high-level description of what you were trying to do, along with the performance trace (*.etl.zip) which captures the behavior during that time.
## Advanced Performance Traces
Steps for manually recording performance traces using the PerfView tool can be found on the [Recording performance traces with PerfView](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Recording-performance-traces-with-PerfView.md) page.
| This document provides specific guidance and best practices for reporting crashes and performance issues in Visual Studio by gathering heap dumps / performance traces as part of Visual Studio's built-in Report a Problem workflow. For a general overview of how to report problems in Visual Studio, see "[How to Report a Problem with Visual Studio 2017](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017)".
:arrow_right: **The product teams review all feedback submitted through the [Report a Problem](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017) tool.** Users are not required to follow the steps in this document to provide feedback.
# Audience
This document describes the best known ways to report actionable product feedback, i.e. feedback for which the product team is most likely to diagnose and resolve quickly. It focuses on two categories of severe problems which are historically challenging to resolve.
:bulb: After identifying the case which best describes your issue, follow the feedback steps specific to that case.
* [**Crashes:**](#crashes) A crash occurs when when the process (Visual Studio) terminates unexpectedly.
* [**Performance issues:**](#performance-issues) Performance problems fall into several categories, but are typically handled the same way.
* Solution load
* Typing
* Open/closing documents
* Searching
* Analyzers and code fixes
* Any other specific action which is slower than desired
# Crashes
## Directly reproducible crashes
Directly reproducible crashes are cases which have all of the following characteristics:
1. Can be observed by following a known set of steps
2. Can be observed on multiple computers (if available)
3. If the steps involve opening a project or document, can be reproduced in sample code or a project which can be linked to or provided as part of the feedback
For these issues, follow the steps in "[How to Report a Problem](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017)" and be sure to include:
- The steps to reproduce the problem
- A standalone repro project as described above. If this is not possible, then please include:
- The language of the open projects (C#, C++, etc.)
- The kind of project (Console Application, ASP.NET, etc.)
- Any extensions that are installed
:bulb: **Most valuable feedback:** For this case, the most valuable feedback is the set of steps to reproduce the issue along with sample source code.
## Unknown crashes
If you're not sure what's causing your crashes or they seem random, then you can capture dumps locally each time Visual Studio crashes and attach those to separate feedback items. To save dumps locally when Visual Studio crashes, set the following registry entries:
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\devenv.exe]
"DumpFolder"="C:\\Crashdumps"
"DumpCount"=dword:00000005
"DumpType"=dword:00000002
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\ServiceHub.RoslynCodeAnalysisService32.exe]
"DumpFolder"="C:\\Crashdumps"
"DumpCount"=dword:00000005
"DumpType"=dword:00000002
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\ServiceHub.RoslynCodeAnalysisService.exe]
"DumpFolder"="C:\\Crashdumps"
"DumpCount"=dword:00000005
"DumpType"=dword:00000002
```
⚠️ Each dump file produced by this method will be up to 4GiB in size. Make sure to set `DumpFolder` to a location with adequate drive space or adjust the `DumpCount` appropriately.
Each time Visual Studio crashes, it will create a dump file **devenv.exe.[number].dmp** file in the configured location. If one of the helper processes crashes, it will create a dump file **ServiceHub.RoslynCodeAnalysisService32.exe.[number].dmp** or **ServiceHub.RoslynCodeAnalysisService.exe.[number].dmp** file in the configured location.
Then, use Visual Studio's "Report a Problem..." feature. It will allow you to attach the appropriate dump.
1. Locate the dump file for the crash you are reporting (look for a file with the correct Creation time)
2. If possible, zip the file (*.zip) to reduce its size before submitting feedback
3. Follow the steps in "[How to Report a Problem](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017)", and attach the heap dump to a new feedback item.
⚠️ Do not attach heap dumps to existing feedback items. Please create a new feedback item for each heap dump you would like to submit. If you were requested to provide a heap dump in order to resolve a previous feedback item, simply reply to the request with a link to the new feedback item where the heap dump is attached.
:bulb: **Most valuable feedback:** For this case, the most valuable feedback is the heap dump captured at the time of the crash.
# Performance Issues
When diagnosing performance issues, the goal is to capture a performance trace while performing the slow/hanging action.
:bulb: When possible, isolate each scenario in a separate, specific feedback report. For example, if typing and navigation are both slow, follow the steps below once per issue. This helps the product team isolate the cause of specific issues.
For best results in capturing the performance, follow these steps:
1. If not already running, have a copy of Visual Studio open where you will reproduce the problem
* Have everything set up to reproduce the problem. For example, if you need a particular project to be loaded with a specific file opened, then be sure both of those steps are complete before proceeding.
* If you are *not* reporting a problem specific to loading a solution, try to wait 5-10 minutes (or more, depending on solution size) after opening the solution before recording the performance trace. The solution load process produces a large amount of data, so waiting for a few minutes helps us focus on the specific problem you are reporting.
2. Start a second copy of Visual Studio *with no solution open*
3. In the new copy of Visual Studio, open the **Report a Problem** tool
4. Follow the steps in "[How to Report a Problem](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017)" until you reach the "Provide a trace and heap dump (optional)" step.
5. Choose to record the first copy of Visual Studio (the one encountering performance problems), and start recording.
* The Steps Recorder application will appear begin recording.
* **During the recording,** perform the problematic action in the separate copy of Visual Studio. It is very difficult for us to correct specific performance problems if they do not appear within the recorded time.
* If the action is shorter than 30 seconds and can be easily repeated, repeat the action to further demonstrate the problem.
* For most cases, a trace of 60 seconds is sufficient to demonstrate the problems, especially if the problematic action lasted (or was repeated) for more than 30 seconds. The duration can be adjusted as necessary to capture the behavior you would like fixed.
6. Click "Stop Record" in Steps Recorder. It may take a few minutes to process the performance trace.
7. Once complete, there will be several attachments to your feedback. Attach any additional files that may help reproduce the problem (a sample project, screenshots, videos, etc.).
8. Submit the feedback.
⚠️ Do not directly attach performance traces to existing feedback items on Developer Community website. Requesting/providing additional information is a supported workflow in Visual Studio's built-in Report a Problem tool. If a performance trace is required in order to resolve a previous feedback item, we will set the state of the feedback item to "Need More Info", which can be responded to in the same way as reporting a new problem. For detailed instruction, please refer to ["Need More Info" section](https://docs.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio-2017?view=vs-2017#when-further-information-is-needed-need-more-info) in Report a Problem tool's document.
:bulb: **Most valuable feedback:** For almost all performance issues, the most valuable feedback is a high-level description of what you were trying to do, along with the performance trace (*.etl.zip) which captures the behavior during that time.
## Advanced Performance Traces
Steps for manually recording performance traces using the PerfView tool can be found on the [Recording performance traces with PerfView](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Recording-performance-traces-with-PerfView.md) page.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/wiki/Performance-considerations-for-large-solutions.md | While we do our best to design Roslyn to work well for a wide range of solutions from small to very large, sometimes the defaults we choose in the balance between performance, memory usage, and useful information don't work in some solutions. In those cases, there are a number of options and in some cases registry keys that can be used to adjust things that may improve the experience.
1. **Disabling Full Solution Diagnostics** Visual Studio can analyze your entire solution in the background in order to populate the error list. This can provide a rich experience where you learn about errors before invoking Build, however, it does require significant resources. You can disable this analysis at Tools\Options\Text Editor\C#\Advanced (or Basic instead of C#). This option is available in VS 2015 RTM and later, but if you are running VS2015 Update 3 RC, the option is in the toolbar of the error list window, instead of below.

2. **Disabling CodeLens** In order to populate the Code Lens information, the IDE basically performs a Find All References operation for each method as it scrolls onto the screen. This is done in a separate process (named Microsoft.Alm.Shared.Remoting.RemoteContainer.dll), so that it won't affect Visual Studio's address space. This process also runs at Below Normal priority so as not to interfere with VS responsiveness. However, on memory constrained systems, systems with slow disk access, or on single core machines, it can still have an impact. CodeLens can be disabled at Tools\Options\Text Editor\All Languages\CodeLens, starting with VS 2013 RTM.

3. **Adjusting File Caching Threshold** We cache the syntax trees for files that have been analyzed in memory. We have the ability to serialize these files to disk to avoid running out of memory, however, there is an optimization in place to reduce disk utilization by keeping the entire contents of small files (under 4KB) in memory. Unfortunately, we've found that in some solutions with a large number of small files this can cause Visual Studio to run out of memory, since it's a 32-bit process, and therefore is limited to 4GB of memory on a 64-bit OS. The file size at which this optimization takes effect can be controlled by changing the registry.
To change it, create a registry key at `HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\Roslyn\Internal\Performance\Cache` , and within that, create a DWORD value named "`RecoverableTreeLengthThreshold`" and set its value to the maximum file size (in bytes) for which syntax trees should be cached. The default value (used if the key doesn't exist) is `4096`. This registry key works in VS 2015 RTM and later. (Note that some or all of the `Roslyn\Internal\Performance\Cache` keys may not exist and will need to be created)
4. **Disabling Solution Crawler** Even with Full Solution Analysis disabled, there are various operations that will cause Visual Studio to process all of the files in your solution. This analysis powers features like:
* Populating the task list with TODO comments
* Populating a cache of information for Find All References and Navigate To
* Determining whether files should be opened in the designer or code view,
* etc.
For our own debugging purposes, we have a registry key that can disable this. It *may* help relieve some issues in *very* large solutions. However, doing so is also likely to prevent the above features from working as designed, so this should be changed only as a last resort. To change it, create a registry key at `HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\Roslyn\Internal\OnOff\Components`, and within that, create a DWORD value named "`Solution Crawler`" and set its value to 0. This registry key works in VS 2015 RTM and later. (Note that some or all of the `Roslyn\Internal\Performance\Cache` keys may not exist and will need to be created)
5. **Disabling Reference Promotion** In Visual Studio 2015, we will sometimes automatically promote a "file reference" (`<Reference>` tag in the .csproj) to a "project to project reference" (`<ProjectReference>` tag in the .csproj) to give better experiences around IntelliSense and refactoring. However in some cases where there are very long chains of dependencies between projects, this can cause too much project information to be kept in memory. To disable this promotion, create a registry key at `HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\Roslyn\Internal\OnOff\Features\`, and within that, create a DWORD value named "`Project Reference Conversion`" and set its value to 0. This registry key works in VS 2015 Update 3 and later. (Note that some or all of the `Roslyn\Internal\Performance\Cache` keys may not exist and will need to be created)
6. **Specifying a main method explicitly** If you have a very large project that generates an executable, performance and memory usage may be improved by explicitly specifying the entry point in project properties. | While we do our best to design Roslyn to work well for a wide range of solutions from small to very large, sometimes the defaults we choose in the balance between performance, memory usage, and useful information don't work in some solutions. In those cases, there are a number of options and in some cases registry keys that can be used to adjust things that may improve the experience.
1. **Disabling Full Solution Diagnostics** Visual Studio can analyze your entire solution in the background in order to populate the error list. This can provide a rich experience where you learn about errors before invoking Build, however, it does require significant resources. You can disable this analysis at Tools\Options\Text Editor\C#\Advanced (or Basic instead of C#). This option is available in VS 2015 RTM and later, but if you are running VS2015 Update 3 RC, the option is in the toolbar of the error list window, instead of below.

2. **Disabling CodeLens** In order to populate the Code Lens information, the IDE basically performs a Find All References operation for each method as it scrolls onto the screen. This is done in a separate process (named Microsoft.Alm.Shared.Remoting.RemoteContainer.dll), so that it won't affect Visual Studio's address space. This process also runs at Below Normal priority so as not to interfere with VS responsiveness. However, on memory constrained systems, systems with slow disk access, or on single core machines, it can still have an impact. CodeLens can be disabled at Tools\Options\Text Editor\All Languages\CodeLens, starting with VS 2013 RTM.

3. **Adjusting File Caching Threshold** We cache the syntax trees for files that have been analyzed in memory. We have the ability to serialize these files to disk to avoid running out of memory, however, there is an optimization in place to reduce disk utilization by keeping the entire contents of small files (under 4KB) in memory. Unfortunately, we've found that in some solutions with a large number of small files this can cause Visual Studio to run out of memory, since it's a 32-bit process, and therefore is limited to 4GB of memory on a 64-bit OS. The file size at which this optimization takes effect can be controlled by changing the registry.
To change it, create a registry key at `HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\Roslyn\Internal\Performance\Cache` , and within that, create a DWORD value named "`RecoverableTreeLengthThreshold`" and set its value to the maximum file size (in bytes) for which syntax trees should be cached. The default value (used if the key doesn't exist) is `4096`. This registry key works in VS 2015 RTM and later. (Note that some or all of the `Roslyn\Internal\Performance\Cache` keys may not exist and will need to be created)
4. **Disabling Solution Crawler** Even with Full Solution Analysis disabled, there are various operations that will cause Visual Studio to process all of the files in your solution. This analysis powers features like:
* Populating the task list with TODO comments
* Populating a cache of information for Find All References and Navigate To
* Determining whether files should be opened in the designer or code view,
* etc.
For our own debugging purposes, we have a registry key that can disable this. It *may* help relieve some issues in *very* large solutions. However, doing so is also likely to prevent the above features from working as designed, so this should be changed only as a last resort. To change it, create a registry key at `HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\Roslyn\Internal\OnOff\Components`, and within that, create a DWORD value named "`Solution Crawler`" and set its value to 0. This registry key works in VS 2015 RTM and later. (Note that some or all of the `Roslyn\Internal\Performance\Cache` keys may not exist and will need to be created)
5. **Disabling Reference Promotion** In Visual Studio 2015, we will sometimes automatically promote a "file reference" (`<Reference>` tag in the .csproj) to a "project to project reference" (`<ProjectReference>` tag in the .csproj) to give better experiences around IntelliSense and refactoring. However in some cases where there are very long chains of dependencies between projects, this can cause too much project information to be kept in memory. To disable this promotion, create a registry key at `HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\Roslyn\Internal\OnOff\Features\`, and within that, create a DWORD value named "`Project Reference Conversion`" and set its value to 0. This registry key works in VS 2015 Update 3 and later. (Note that some or all of the `Roslyn\Internal\Performance\Cache` keys may not exist and will need to be created)
6. **Specifying a main method explicitly** If you have a very large project that generates an executable, performance and memory usage may be improved by explicitly specifying the entry point in project properties. | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./docs/features/nullable-metadata.md | Nullable Metadata
=========
The following describes the representation of nullable annotations in metadata.
## NullableAttribute
Type references are annotated in metadata with a `NullableAttribute`.
```C#
namespace System.Runtime.CompilerServices
{
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Event |
AttributeTargets.Field |
AttributeTargets.GenericParameter |
AttributeTargets.Parameter |
AttributeTargets.Property |
AttributeTargets.ReturnValue,
AllowMultiple = false,
Inherited = false)]
public sealed class NullableAttribute : Attribute
{
public readonly byte[] NullableFlags;
public NullableAttribute(byte flag)
{
NullableFlags = new byte[] { flag };
}
public NullableAttribute(byte[] flags)
{
NullableFlags = flags;
}
}
}
```
The `NullableAttribute` type is for compiler use only - it is not permitted in source.
The type declaration is synthesized by the compiler if not already included in the compilation.
Each type reference in metadata may have an associated `NullableAttribute` with a `byte[]` where each `byte`
represents nullability: 0 for oblivious, 1 for not annotated, and 2 for annotated.
The `byte[]` is constructed as follows:
- Reference type: the nullability (0, 1, or 2), followed by the representation of the type arguments in order including containing types
- Nullable value type: the representation of the type argument only
- Non-generic value type: skipped
- Generic value type: 0, followed by the representation of the type arguments in order including containing types
- Array: the nullability (0, 1, or 2), followed by the representation of the element type
- Tuple: the representation of the underlying constructed type
- Type parameter reference: the nullability (0, 1, or 2, with 0 for unconstrained type parameter)
Note that non-generic value types are represented by an empty `byte[]`.
However, generic value types and type parameters constrained to value types have an explicit 0 in the `byte[]` for nullability.
The reason generic types and type parameters are represented with an explicit `byte` is to simplify metadata import.
Specifically, this avoids the need to calculate whether a type parameter is constrained to a value type when
decoding nullability metadata, since the constraints may include a (valid) cyclic reference to the type parameter.
### Optimizations
If the `byte[]` is empty, the `NullableAttribute` is omitted.
If all values in the `byte[]` are the same, the `NullableAttribute` is constructed with that single `byte` value. (For instance, `NullableAttribute(1)` rather than `NullableAttribute(new byte[] { 1, 1 }))`.)
### Type parameters
Each type parameter definition may have an associated `NullableAttribute` with a single `byte`:
1. `notnull` constraint: `NullableAttribute(1)`
2. `class` constraint in `#nullable disable` context: `NullableAttribute(0)`
3. `class` constraint in `#nullable enable` context: `NullableAttribute(1)`
4. `class?` constraint: `NullableAttribute(2)`
5. No `notnull`, `class`, `struct`, `unmanaged`, or type constraints in `#nullable disable` context: `NullableAttribute(0)`
6. No `notnull`, `class`, `struct`, `unmanaged`, or type constraints in `#nullable enable` context
(equivalent to an `object?` constraint): `NullableAttribute(2)`
## NullableContextAttribute
`NullableContextAttribute` can be used to indicate the nullability of type references that have no `NullableAttribute` annotations.
```C#
namespace System.Runtime.CompilerServices
{
[System.AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Delegate |
AttributeTargets.Interface |
AttributeTargets.Method |
AttributeTargets.Struct,
AllowMultiple = false,
Inherited = false)]
public sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte flag)
{
Flag = flag;
}
}
}
```
The `NullableContextAttribute` type is for compiler use only - it is not permitted in source.
The type declaration is synthesized by the compiler if not already included in the compilation.
The `NullableContextAttribute` is optional - nullable annotations can be represented in metadata with full fidelity using `NullableAttribute` only.
`NullableContextAttribute` is valid in metadata on type and method declarations.
The `byte` value represents the implicit `NullableAttribute` value for type references within that scope
that do not have an explicit `NullableAttribute` and would not otherwise be represented by an empty `byte[]`.
The nearest `NullableContextAttribute` in the metadata hierarchy applies.
If there are no `NullableContextAttribute` attributes in the hierarchy,
missing `NullableAttribute` attributes are treated as `NullableAttribute(0)`.
The attribute is not inherited.
The C#8 compiler uses the following algorithm to determine which `NullableAttribute` and
`NullableContextAttribute` attributes to emit.
First, `NullableAttribute` attributes are generated at each type reference and type parameter definition by:
calculating the `byte[]`, skipping empty `byte[]`, and collapsing `byte[]` to single `byte` where possible.
Then at each level in metadata hierarchy starting at methods:
The compiler finds the most common single `byte` value across all the `NullableAttribute` attributes at that level
and any `NullableContextAttribute` attributes on immediate children.
If there are no single `byte` values, there are no changes.
Otherwise, a `NullableContext(value)` attribute is created at that level where `value` is most common
value (preferring `0` over `1` and preferring `1` over `2`), and all `NullableAttribute` and `NullableContextAttribute` attributes with that value are removed.
Note that an assembly compiled with C#8 where all reference types are oblivious will have no
`NullableContextAttribute` and no `NullableAttribute` attributes emitted.
That is equivalent to a legacy assembly.
### Examples
```C#
// C# representation of metadata
[NullableContext(2)]
class Program
{
string s; // string?
[Nullable({ 2, 1, 2 }] Dictionary<string, object> d; // Dictionary<string!, object?>?
[Nullable(1)] int[] a; // int[]!
int[] b; // int[]?
[Nullable({ 0, 2 })] object[] c; // object?[]~
}
```
## Private members
To reduce the size of metadata, the C#8 compiler can be configured to not emit attributes
for members that are inaccessible outside the assembly (`private` members, and also `internal` members
if the assembly does not contain `InternalsVisibleToAttribute` attributes).
The compiler behavior is configured from a command-line flag.
For now a feature flag is used: `-features:nullablePublicOnly`.
If private member attributes are dropped, the compiler will emit a `[module: NullablePublicOnly]` attribute.
The presence or absence of the `NullablePublicOnlyAttribute` can be used by tools to interpret
the nullability of private members that do not have an associated `NullableAttribute` attribute.
For members that do not have explicit accessibility in metadata
(specifically for parameters, type parameters, events, and properties),
the compiler uses the accessibility of the container to determine whether to emit nullable attributes.
```C#
namespace System.Runtime.CompilerServices
{
[System.AttributeUsage(AttributeTargets.Module, AllowMultiple = false)]
public sealed class NullablePublicOnlyAttribute : Attribute
{
public readonly bool IncludesInternals;
public NullablePublicOnlyAttribute(bool includesInternals)
{
IncludesInternals = includesInternals;
}
}
}
```
The `NullablePublicOnlyAttribute` type is for compiler use only - it is not permitted in source.
The type declaration is synthesized by the compiler if not already included in the compilation.
`IncludesInternal` is true if `internal` members are annotated in addition to `public` and `protected` members.
## Compatibility
The nullable metadata does not include an explicit version number.
Where possible, the compiler will silently ignore attribute forms that are unexpected.
The metadata format described here is incompatible with the format used by earlier C#8 previews:
1. Concrete non-generic value types are no longer included in the `byte[]`, and
2. `NullableContextAttribute` attributes are used in place of explicit `NullableAttribute` attributes.
Those differences mean that assemblies compiled with earlier previews may be read incorrectly by later previews,
and assemblies compiled with later previews may be read incorrectly by earlier previews.
| Nullable Metadata
=========
The following describes the representation of nullable annotations in metadata.
## NullableAttribute
Type references are annotated in metadata with a `NullableAttribute`.
```C#
namespace System.Runtime.CompilerServices
{
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Event |
AttributeTargets.Field |
AttributeTargets.GenericParameter |
AttributeTargets.Parameter |
AttributeTargets.Property |
AttributeTargets.ReturnValue,
AllowMultiple = false,
Inherited = false)]
public sealed class NullableAttribute : Attribute
{
public readonly byte[] NullableFlags;
public NullableAttribute(byte flag)
{
NullableFlags = new byte[] { flag };
}
public NullableAttribute(byte[] flags)
{
NullableFlags = flags;
}
}
}
```
The `NullableAttribute` type is for compiler use only - it is not permitted in source.
The type declaration is synthesized by the compiler if not already included in the compilation.
Each type reference in metadata may have an associated `NullableAttribute` with a `byte[]` where each `byte`
represents nullability: 0 for oblivious, 1 for not annotated, and 2 for annotated.
The `byte[]` is constructed as follows:
- Reference type: the nullability (0, 1, or 2), followed by the representation of the type arguments in order including containing types
- Nullable value type: the representation of the type argument only
- Non-generic value type: skipped
- Generic value type: 0, followed by the representation of the type arguments in order including containing types
- Array: the nullability (0, 1, or 2), followed by the representation of the element type
- Tuple: the representation of the underlying constructed type
- Type parameter reference: the nullability (0, 1, or 2, with 0 for unconstrained type parameter)
Note that non-generic value types are represented by an empty `byte[]`.
However, generic value types and type parameters constrained to value types have an explicit 0 in the `byte[]` for nullability.
The reason generic types and type parameters are represented with an explicit `byte` is to simplify metadata import.
Specifically, this avoids the need to calculate whether a type parameter is constrained to a value type when
decoding nullability metadata, since the constraints may include a (valid) cyclic reference to the type parameter.
### Optimizations
If the `byte[]` is empty, the `NullableAttribute` is omitted.
If all values in the `byte[]` are the same, the `NullableAttribute` is constructed with that single `byte` value. (For instance, `NullableAttribute(1)` rather than `NullableAttribute(new byte[] { 1, 1 }))`.)
### Type parameters
Each type parameter definition may have an associated `NullableAttribute` with a single `byte`:
1. `notnull` constraint: `NullableAttribute(1)`
2. `class` constraint in `#nullable disable` context: `NullableAttribute(0)`
3. `class` constraint in `#nullable enable` context: `NullableAttribute(1)`
4. `class?` constraint: `NullableAttribute(2)`
5. No `notnull`, `class`, `struct`, `unmanaged`, or type constraints in `#nullable disable` context: `NullableAttribute(0)`
6. No `notnull`, `class`, `struct`, `unmanaged`, or type constraints in `#nullable enable` context
(equivalent to an `object?` constraint): `NullableAttribute(2)`
## NullableContextAttribute
`NullableContextAttribute` can be used to indicate the nullability of type references that have no `NullableAttribute` annotations.
```C#
namespace System.Runtime.CompilerServices
{
[System.AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Delegate |
AttributeTargets.Interface |
AttributeTargets.Method |
AttributeTargets.Struct,
AllowMultiple = false,
Inherited = false)]
public sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte flag)
{
Flag = flag;
}
}
}
```
The `NullableContextAttribute` type is for compiler use only - it is not permitted in source.
The type declaration is synthesized by the compiler if not already included in the compilation.
The `NullableContextAttribute` is optional - nullable annotations can be represented in metadata with full fidelity using `NullableAttribute` only.
`NullableContextAttribute` is valid in metadata on type and method declarations.
The `byte` value represents the implicit `NullableAttribute` value for type references within that scope
that do not have an explicit `NullableAttribute` and would not otherwise be represented by an empty `byte[]`.
The nearest `NullableContextAttribute` in the metadata hierarchy applies.
If there are no `NullableContextAttribute` attributes in the hierarchy,
missing `NullableAttribute` attributes are treated as `NullableAttribute(0)`.
The attribute is not inherited.
The C#8 compiler uses the following algorithm to determine which `NullableAttribute` and
`NullableContextAttribute` attributes to emit.
First, `NullableAttribute` attributes are generated at each type reference and type parameter definition by:
calculating the `byte[]`, skipping empty `byte[]`, and collapsing `byte[]` to single `byte` where possible.
Then at each level in metadata hierarchy starting at methods:
The compiler finds the most common single `byte` value across all the `NullableAttribute` attributes at that level
and any `NullableContextAttribute` attributes on immediate children.
If there are no single `byte` values, there are no changes.
Otherwise, a `NullableContext(value)` attribute is created at that level where `value` is most common
value (preferring `0` over `1` and preferring `1` over `2`), and all `NullableAttribute` and `NullableContextAttribute` attributes with that value are removed.
Note that an assembly compiled with C#8 where all reference types are oblivious will have no
`NullableContextAttribute` and no `NullableAttribute` attributes emitted.
That is equivalent to a legacy assembly.
### Examples
```C#
// C# representation of metadata
[NullableContext(2)]
class Program
{
string s; // string?
[Nullable({ 2, 1, 2 }] Dictionary<string, object> d; // Dictionary<string!, object?>?
[Nullable(1)] int[] a; // int[]!
int[] b; // int[]?
[Nullable({ 0, 2 })] object[] c; // object?[]~
}
```
## Private members
To reduce the size of metadata, the C#8 compiler can be configured to not emit attributes
for members that are inaccessible outside the assembly (`private` members, and also `internal` members
if the assembly does not contain `InternalsVisibleToAttribute` attributes).
The compiler behavior is configured from a command-line flag.
For now a feature flag is used: `-features:nullablePublicOnly`.
If private member attributes are dropped, the compiler will emit a `[module: NullablePublicOnly]` attribute.
The presence or absence of the `NullablePublicOnlyAttribute` can be used by tools to interpret
the nullability of private members that do not have an associated `NullableAttribute` attribute.
For members that do not have explicit accessibility in metadata
(specifically for parameters, type parameters, events, and properties),
the compiler uses the accessibility of the container to determine whether to emit nullable attributes.
```C#
namespace System.Runtime.CompilerServices
{
[System.AttributeUsage(AttributeTargets.Module, AllowMultiple = false)]
public sealed class NullablePublicOnlyAttribute : Attribute
{
public readonly bool IncludesInternals;
public NullablePublicOnlyAttribute(bool includesInternals)
{
IncludesInternals = includesInternals;
}
}
}
```
The `NullablePublicOnlyAttribute` type is for compiler use only - it is not permitted in source.
The type declaration is synthesized by the compiler if not already included in the compilation.
`IncludesInternal` is true if `internal` members are annotated in addition to `public` and `protected` members.
## Compatibility
The nullable metadata does not include an explicit version number.
Where possible, the compiler will silently ignore attribute forms that are unexpected.
The metadata format described here is incompatible with the format used by earlier C#8 previews:
1. Concrete non-generic value types are no longer included in the `byte[]`, and
2. `NullableContextAttribute` attributes are used in place of explicit `NullableAttribute` attributes.
Those differences mean that assemblies compiled with earlier previews may be read incorrectly by later previews,
and assemblies compiled with later previews may be read incorrectly by earlier previews.
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicBuild.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.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicBuild : AbstractIntegrationTest
{
public BasicBuild(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.SolutionExplorer.CreateSolution(nameof(BasicBuild));
var testProj = new ProjectUtils.Project("TestProj");
VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ConsoleApplication, LanguageNames.VisualBasic);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Build)]
public void BuildProject()
{
var editorText = @"Module Program
Sub Main()
Console.WriteLine(""Hello, World!"")
End Sub
End Module";
VisualStudio.Editor.SetText(editorText);
// TODO: Validate build works as expected
}
}
}
| // 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.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicBuild : AbstractIntegrationTest
{
public BasicBuild(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.SolutionExplorer.CreateSolution(nameof(BasicBuild));
var testProj = new ProjectUtils.Project("TestProj");
VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ConsoleApplication, LanguageNames.VisualBasic);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Build)]
public void BuildProject()
{
var editorText = @"Module Program
Sub Main()
Console.WriteLine(""Hello, World!"")
End Sub
End Module";
VisualStudio.Editor.SetText(editorText);
// TODO: Validate build works as expected
}
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/EditorFeatures/CSharpTest/Diagnostics/FixReturnType/FixReturnTypeTests.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.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.FixReturnType;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.FixReturnType
{
[Trait(Traits.Feature, Traits.Features.CodeActionsFixReturnType)]
public partial class FixReturnTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public FixReturnTypeTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new CSharpFixReturnTypeCodeFixProvider());
[Fact]
public async Task Simple()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] 1;
}
}",
@"class C
{
int M()
{
return 1;
}
}");
}
[Fact]
public async Task Simple_WithTrivia()
{
await TestInRegularAndScript1Async(
@"class C
{
/*A*/ void /*B*/ M()
{
[|return|] 1;
}
}",
@"class C
{
/*A*/
int /*B*/ M()
{
return 1;
}
}");
// Note: the formatting change is introduced by Formatter.FormatAsync
}
[Fact]
public async Task ReturnString()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] """";
}
}",
@"class C
{
string M()
{
return """";
}
}");
}
[Fact]
public async Task ReturnNull()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] null;
}
}",
@"class C
{
object M()
{
return null;
}
}");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/33481")]
public async Task ReturnTypelessTuple()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] (null, string.Empty);
}
}",
@"class C
{
object M()
{
return (null, string.Empty);
}
}");
}
[Fact]
public async Task ReturnLambda()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] () => {};
}
}",
@"class C
{
object M()
{
return () => {};
}
}");
}
[Fact]
public async Task ReturnC()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] new C();
}
}",
@"class C
{
C M()
{
return new C();
}
}");
}
[Fact]
public async Task ReturnString_AsyncVoid()
{
await TestInRegularAndScript1Async(
@"class C
{
async void M()
{
[|return|] """";
}
}",
@"class C
{
async System.Threading.Tasks.Task<string> M()
{
return """";
}
}");
}
[Fact]
public async Task ReturnString_AsyncVoid_WithUsing()
{
await TestInRegularAndScript1Async(
@"
using System.Threading.Tasks;
class C
{
async void M()
{
[|return|] """";
}
}",
@"
using System.Threading.Tasks;
class C
{
async Task<string> M()
{
return """";
}
}");
}
[Fact]
public async Task ReturnString_AsyncTask()
{
await TestInRegularAndScript1Async(
@"class C
{
async System.Threading.Tasks.Task M()
{
[|return|] """";
}
}",
@"class C
{
async System.Threading.Tasks.Task<string> M()
{
return """";
}
}");
}
[Fact]
public async Task ReturnString_LocalFunction()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
void local()
{
[|return|] """";
}
}
}",
@"class C
{
void M()
{
string local()
{
return """";
}
}
}");
}
[Fact]
public async Task ReturnString_AsyncVoid_LocalFunction()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
async void local()
{
[|return|] """";
}
}
}",
@"class C
{
void M()
{
async System.Threading.Tasks.Task<string> local()
{
return """";
}
}
}");
}
[Fact]
public async Task ExpressionBodied()
{
await TestInRegularAndScript1Async(
@"class C
{
void M() => 1[||];
}",
@"class C
{
int M() => 1[||];
}");
}
[Fact]
[WorkItem(47089, "https://github.com/dotnet/roslyn/issues/47089")]
public async Task ExpressionAndReturnTypeAreVoid()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
return Console.WriteLine()[||];
}
}");
}
}
}
| // 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.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.FixReturnType;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.FixReturnType
{
[Trait(Traits.Feature, Traits.Features.CodeActionsFixReturnType)]
public partial class FixReturnTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public FixReturnTypeTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new CSharpFixReturnTypeCodeFixProvider());
[Fact]
public async Task Simple()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] 1;
}
}",
@"class C
{
int M()
{
return 1;
}
}");
}
[Fact]
public async Task Simple_WithTrivia()
{
await TestInRegularAndScript1Async(
@"class C
{
/*A*/ void /*B*/ M()
{
[|return|] 1;
}
}",
@"class C
{
/*A*/
int /*B*/ M()
{
return 1;
}
}");
// Note: the formatting change is introduced by Formatter.FormatAsync
}
[Fact]
public async Task ReturnString()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] """";
}
}",
@"class C
{
string M()
{
return """";
}
}");
}
[Fact]
public async Task ReturnNull()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] null;
}
}",
@"class C
{
object M()
{
return null;
}
}");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/33481")]
public async Task ReturnTypelessTuple()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] (null, string.Empty);
}
}",
@"class C
{
object M()
{
return (null, string.Empty);
}
}");
}
[Fact]
public async Task ReturnLambda()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] () => {};
}
}",
@"class C
{
object M()
{
return () => {};
}
}");
}
[Fact]
public async Task ReturnC()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|return|] new C();
}
}",
@"class C
{
C M()
{
return new C();
}
}");
}
[Fact]
public async Task ReturnString_AsyncVoid()
{
await TestInRegularAndScript1Async(
@"class C
{
async void M()
{
[|return|] """";
}
}",
@"class C
{
async System.Threading.Tasks.Task<string> M()
{
return """";
}
}");
}
[Fact]
public async Task ReturnString_AsyncVoid_WithUsing()
{
await TestInRegularAndScript1Async(
@"
using System.Threading.Tasks;
class C
{
async void M()
{
[|return|] """";
}
}",
@"
using System.Threading.Tasks;
class C
{
async Task<string> M()
{
return """";
}
}");
}
[Fact]
public async Task ReturnString_AsyncTask()
{
await TestInRegularAndScript1Async(
@"class C
{
async System.Threading.Tasks.Task M()
{
[|return|] """";
}
}",
@"class C
{
async System.Threading.Tasks.Task<string> M()
{
return """";
}
}");
}
[Fact]
public async Task ReturnString_LocalFunction()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
void local()
{
[|return|] """";
}
}
}",
@"class C
{
void M()
{
string local()
{
return """";
}
}
}");
}
[Fact]
public async Task ReturnString_AsyncVoid_LocalFunction()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
async void local()
{
[|return|] """";
}
}
}",
@"class C
{
void M()
{
async System.Threading.Tasks.Task<string> local()
{
return """";
}
}
}");
}
[Fact]
public async Task ExpressionBodied()
{
await TestInRegularAndScript1Async(
@"class C
{
void M() => 1[||];
}",
@"class C
{
int M() => 1[||];
}");
}
[Fact]
[WorkItem(47089, "https://github.com/dotnet/roslyn/issues/47089")]
public async Task ExpressionAndReturnTypeAreVoid()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
return Console.WriteLine()[||];
}
}");
}
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmExceptionCode.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
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\Concord\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
namespace Microsoft.VisualStudio.Debugger
{
//
// Summary:
// Defines the HRESULT codes used by this API.
public enum DkmExceptionCode
{
//
// Summary:
// Unspecified error.
E_FAIL = -2147467259,
//
// Summary:
// A debugger is already attached.
E_ATTACH_DEBUGGER_ALREADY_ATTACHED = -2147221503,
//
// Summary:
// The process does not have sufficient privileges to be debugged.
E_ATTACH_DEBUGGEE_PROCESS_SECURITY_VIOLATION = -2147221502,
//
// Summary:
// The desktop cannot be debugged.
E_ATTACH_CANNOT_ATTACH_TO_DESKTOP = -2147221501,
//
// Summary:
// Unmanaged debugging is not available.
E_LAUNCH_NO_INTEROP = -2147221499,
//
// Summary:
// Debugging isn't possible due to an incompatibility within the CLR implementation.
E_LAUNCH_DEBUGGING_NOT_POSSIBLE = -2147221498,
//
// Summary:
// Visual Studio cannot debug managed applications because a kernel debugger is
// enabled on the system. Please see Help for further information.
E_LAUNCH_KERNEL_DEBUGGER_ENABLED = -2147221497,
//
// Summary:
// Visual Studio cannot debug managed applications because a kernel debugger is
// present on the system. Please see Help for further information.
E_LAUNCH_KERNEL_DEBUGGER_PRESENT = -2147221496,
//
// Summary:
// The debugger does not support debugging managed and native code at the same time
// on the platform of the target computer/device. Configure the debugger to debug
// only native code or only managed code.
E_INTEROP_NOT_SUPPORTED = -2147221495,
//
// Summary:
// The maximum number of processes is already being debugged.
E_TOO_MANY_PROCESSES = -2147221494,
//
// Summary:
// Script debugging of your application is disabled in Internet Explorer. To enable
// script debugging in Internet Explorer, choose Internet Options from the Tools
// menu and navigate to the Advanced tab. Under the Browsing category, clear the
// 'Disable Script Debugging (Internet Explorer)' checkbox, then restart Internet
// Explorer.
E_MSHTML_SCRIPT_DEBUGGING_DISABLED = -2147221493,
//
// Summary:
// The correct version of pdm.dll is not registered. Repair your Visual Studio installation,
// or run 'regsvr32.exe "%CommonProgramFiles%\Microsoft Shared\VS7Debug\pdm.dll"'.
E_SCRIPT_PDM_NOT_REGISTERED = -2147221492,
//
// Summary:
// The .NET debugger has not been installed properly. The most probable cause is
// that mscordbi.dll is not properly registered. Click Help for more information
// on how to repair the .NET debugger.
E_DE_CLR_DBG_SERVICES_NOT_INSTALLED = -2147221491,
//
// Summary:
// There is no managed code running in the process. In order to attach to a process
// with the .NET debugger, managed code must be running in the process before attaching.
E_ATTACH_NO_CLR_PROGRAMS = -2147221490,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor has been closed on the remote
// machine.
E_REMOTE_SERVER_CLOSED = -2147221488,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer does
// not support debugging code running in the Common Language Runtime.
E_CLR_NOT_SUPPORTED = -2147221482,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer does
// not support debugging code running in the Common Language Runtime on a 64-bit
// computer.
E_64BIT_CLR_NOT_SUPPORTED = -2147221481,
//
// Summary:
// Cannot debug minidumps and processes at the same time.
E_CANNOT_MIX_MINDUMP_DEBUGGING = -2147221480,
E_DEBUG_ENGINE_NOT_REGISTERED = -2147221479,
//
// Summary:
// This application has failed to start because the application configuration is
// incorrect. Review the manifest file for possible errors. Reinstalling the application
// may fix this problem. For more details, please see the application event log.
E_LAUNCH_SXS_ERROR = -2147221478,
//
// Summary:
// Failed to initialize msdbg2.dll for script debugging. If this problem persists,
// use 'Add or Remove Programs' in Control Panel to repair your Visual Studio installation.
E_FAILED_TO_INITIALIZE_SCRIPT_PROXY = -2147221477,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor (MSVSMON.EXE) does not appear
// to be running on the remote computer. This may be because a firewall is preventing
// communication to the remote computer. Please see Help for assistance on configuring
// remote debugging.
E_REMOTE_SERVER_DOES_NOT_EXIST = -2147221472,
//
// Summary:
// Access is denied. Can not connect to Microsoft Visual Studio Remote Debugging
// Monitor on the remote computer.
E_REMOTE_SERVER_ACCESS_DENIED = -2147221471,
//
// Summary:
// The debugger cannot connect to the remote computer. The debugger was unable to
// resolve the specified computer name.
E_REMOTE_SERVER_MACHINE_DOES_NOT_EXIST = -2147221470,
//
// Summary:
// The debugger is not properly installed. Run setup to install or repair the debugger.
E_DEBUGGER_NOT_REGISTERED_PROPERLY = -2147221469,
//
// Summary:
// Access is denied. This seems to be because the 'Network access: Sharing and security
// model for local accounts' security policy does not allow users to authenticate
// as themselves. Please use the 'Local Security Settings' administration tool on
// the local computer to configure this option.
E_FORCE_GUEST_MODE_ENABLED = -2147221468,
E_GET_IWAM_USER_FAILURE = -2147221467,
//
// Summary:
// The specified remote server name is not valid.
E_REMOTE_SERVER_INVALID_NAME = -2147221466,
//
// Summary:
// Microsoft Visual Studio Debugging Monitor (MSVSMON.EXE) failed to start. If this
// problem persists, please repair your Visual Studio installation via 'Add or Remove
// Programs' in Control Panel.
E_AUTO_LAUNCH_EXEC_FAILURE = -2147221464,
//
// Summary:
// Microsoft Visual Studio Remote Debugging Monitor (MSVSMON.EXE) is not running
// under your user account and MSVSMON could not be automatically started. MSVSMON
// must be manually started, or the Visual Studio remote debugging components must
// be installed on the remote computer. Please see Help for assistance.
E_REMOTE_COMPONENTS_NOT_REGISTERED = -2147221461,
//
// Summary:
// A DCOM error occurred trying to contact the remote computer. Access is denied.
// It may be possible to avoid this error by changing your settings to debug only
// native code or only managed code.
E_DCOM_ACCESS_DENIED = -2147221460,
//
// Summary:
// Debugging using the Default transport is not possible because the remote machine
// has 'Share-level access control' enabled. To enable debugging on the remote machine,
// go to Control Panel -> Network -> Access control, and set Access control to be
// 'User-level access control'.
E_SHARE_LEVEL_ACCESS_CONTROL_ENABLED = -2147221459,
//
// Summary:
// Logon failure: unknown user name or bad password. See help for more information.
E_WORKGROUP_REMOTE_LOGON_FAILURE = -2147221458,
//
// Summary:
// Windows authentication is disabled in the Microsoft Visual Studio Remote Debugging
// Monitor (MSVSMON). To connect, choose one of the following options. 1. Enable
// Windows authentication in MSVSMON 2. Reconfigure your project to disable Windows
// authentication 3. Use the 'Remote (native with no authentication)' transport
// in the 'Attach to Process' dialog
E_WINAUTH_CONNECT_NOT_SUPPORTED = -2147221457,
//
// Summary:
// A previous expression evaluation is still in progress.
E_EVALUATE_BUSY_WITH_EVALUATION = -2147221456,
//
// Summary:
// The expression evaluation took too long.
E_EVALUATE_TIMEOUT = -2147221455,
//
// Summary:
// Mixed-mode debugging does not support Microsoft.NET Framework versions earlier
// than 2.0.
E_INTEROP_CLR_TOO_OLD = -2147221454,
//
// Summary:
// Check for one of the following. 1. The application you are trying to debug uses
// a version of the Microsoft .NET Framework that is not supported by the debugger.
// 2. The debugger has made an incorrect assumption about the Microsoft .NET Framework
// version your application is going to use. 3. The Microsoft .NET Framework version
// specified by you for debugging is incorrect. Please see the Visual Studio .NET
// debugger documentation for correctly specifying the Microsoft .NET Framework
// version your application is going to use for debugging.
E_CLR_INCOMPATIBLE_PROTOCOL = -2147221453,
//
// Summary:
// Unable to attach because process is running in fiber mode.
E_CLR_CANNOT_DEBUG_FIBER_PROCESS = -2147221452,
//
// Summary:
// Visual Studio has insufficient privileges to debug this process. To debug this
// process, Visual Studio must be run as an administrator.
E_PROCESS_OBJECT_ACCESS_DENIED = -2147221451,
//
// Summary:
// Visual Studio has insufficient privileges to inspect the process's identity.
E_PROCESS_TOKEN_ACCESS_DENIED = -2147221450,
//
// Summary:
// Visual Studio was unable to inspect the process's identity. This is most likely
// due to service configuration on the computer running the process.
E_PROCESS_TOKEN_ACCESS_DENIED_NO_TS = -2147221449,
E_OPERATION_REQUIRES_ELEVATION = -2147221448,
//
// Summary:
// Visual Studio has insufficient privileges to debug this process. To debug this
// process, Visual Studio must be run as an administrator.
E_ATTACH_REQUIRES_ELEVATION = -2147221447,
E_MEMORY_NOTSUPPORTED = -2147221440,
//
// Summary:
// The type of code you are currently debugging does not support disassembly.
E_DISASM_NOTSUPPORTED = -2147221439,
//
// Summary:
// The specified address does not exist in disassembly.
E_DISASM_BADADDRESS = -2147221438,
E_DISASM_NOTAVAILABLE = -2147221437,
//
// Summary:
// The breakpoint has been deleted.
E_BP_DELETED = -2147221408,
//
// Summary:
// The process has been terminated.
E_PROCESS_DESTROYED = -2147221392,
E_PROCESS_DEBUGGER_IS_DEBUGGEE = -2147221391,
//
// Summary:
// Terminating this process is not allowed.
E_TERMINATE_FORBIDDEN = -2147221390,
//
// Summary:
// The thread has terminated.
E_THREAD_DESTROYED = -2147221387,
//
// Summary:
// Cannot find port. Check the remote machine name.
E_PORTSUPPLIER_NO_PORT = -2147221376,
E_PORT_NO_REQUEST = -2147221360,
E_COMPARE_CANNOT_COMPARE = -2147221344,
E_JIT_INVALID_PID = -2147221327,
E_JIT_VSJITDEBUGGER_NOT_REGISTERED = -2147221325,
E_JIT_APPID_NOT_REGISTERED = -2147221324,
E_JIT_RUNTIME_VERSION_UNSUPPORTED = -2147221322,
E_SESSION_TERMINATE_DETACH_FAILED = -2147221310,
E_SESSION_TERMINATE_FAILED = -2147221309,
//
// Summary:
// Detach is not supported on Microsoft Windows 2000 for native code.
E_DETACH_NO_PROXY = -2147221296,
E_DETACH_TS_UNSUPPORTED = -2147221280,
E_DETACH_IMPERSONATE_FAILURE = -2147221264,
//
// Summary:
// This thread has called into a function that cannot be displayed.
E_CANNOT_SET_NEXT_STATEMENT_ON_NONLEAF_FRAME = -2147221248,
E_TARGET_FILE_MISMATCH = -2147221247,
E_IMAGE_NOT_LOADED = -2147221246,
E_FIBER_NOT_SUPPORTED = -2147221245,
//
// Summary:
// The next statement cannot be set to another function.
E_CANNOT_SETIP_TO_DIFFERENT_FUNCTION = -2147221244,
//
// Summary:
// In order to Set Next Statement, right-click on the active frame in the Call Stack
// window and select "Unwind To This Frame".
E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION = -2147221243,
//
// Summary:
// The next statement cannot be changed until the current statement has completed.
E_ENC_SETIP_REQUIRES_CONTINUE = -2147221241,
//
// Summary:
// The next statement cannot be set from outside a finally block to within it.
E_CANNOT_SET_NEXT_STATEMENT_INTO_FINALLY = -2147221240,
//
// Summary:
// The next statement cannot be set from within a finally block to a statement outside
// of it.
E_CANNOT_SET_NEXT_STATEMENT_OUT_OF_FINALLY = -2147221239,
//
// Summary:
// The next statement cannot be set from outside a catch block to within it.
E_CANNOT_SET_NEXT_STATEMENT_INTO_CATCH = -2147221238,
//
// Summary:
// The next statement cannot be changed at this time.
E_CANNOT_SET_NEXT_STATEMENT_GENERAL = -2147221237,
//
// Summary:
// The next statement cannot be set into or out of a catch filter.
E_CANNOT_SET_NEXT_STATEMENT_INTO_OR_OUT_OF_FILTER = -2147221236,
//
// Summary:
// This process is not currently executing the type of code that you selected to
// debug.
E_ASYNCBREAK_NO_PROGRAMS = -2147221232,
//
// Summary:
// The debugger is still attaching to the process or the process is not currently
// executing the type of code selected for debugging.
E_ASYNCBREAK_DEBUGGEE_NOT_INITIALIZED = -2147221231,
//
// Summary:
// The debugger is handling debug events or performing evaluations that do not allow
// nested break state. Try again.
E_ASYNCBREAK_UNABLE_TO_PROCESS = -2147221230,
//
// Summary:
// The web server has been locked down and is blocking the DEBUG verb, which is
// required to enable debugging. Please see Help for assistance.
E_WEBDBG_DEBUG_VERB_BLOCKED = -2147221215,
//
// Summary:
// ASP debugging is disabled because the ASP process is running as a user that does
// not have debug permissions. Please see Help for assistance.
E_ASP_USER_ACCESS_DENIED = -2147221211,
//
// Summary:
// The remote debugging components are not registered or running on the web server.
// Ensure the proper version of msvsmon is running on the remote computer.
E_AUTO_ATTACH_NOT_REGISTERED = -2147221210,
//
// Summary:
// An unexpected DCOM error occurred while trying to automatically attach to the
// remote web server. Try manually attaching to the remote web server using the
// 'Attach To Process' dialog.
E_AUTO_ATTACH_DCOM_ERROR = -2147221209,
//
// Summary:
// Expected failure from web server CoCreating debug verb CLSID
E_AUTO_ATTACH_COCREATE_FAILURE = -2147221208,
E_AUTO_ATTACH_CLASSNOTREG = -2147221207,
//
// Summary:
// The current thread cannot continue while an expression is being evaluated on
// another thread.
E_CANNOT_CONTINUE_DURING_PENDING_EXPR_EVAL = -2147221200,
E_REMOTE_REDIRECTION_UNSUPPORTED = -2147221195,
//
// Summary:
// The specified working directory does not exist or is not a full path.
E_INVALID_WORKING_DIRECTORY = -2147221194,
//
// Summary:
// The application manifest has the uiAccess attribute set to 'true'. Running an
// Accessibility application requires following the steps described in Help.
E_LAUNCH_FAILED_WITH_ELEVATION = -2147221193,
//
// Summary:
// This program requires additional permissions to start. To debug this program,
// restart Visual Studio as an administrator.
E_LAUNCH_ELEVATION_REQUIRED = -2147221192,
//
// Summary:
// Cannot locate Microsoft Internet Explorer.
E_CANNOT_FIND_INTERNET_EXPLORER = -2147221191,
//
// Summary:
// The Visual Studio Remote Debugger (MSVSMON.EXE) has insufficient privileges to
// debug this process. To debug this process, the remote debugger must be run as
// an administrator.
E_REMOTE_PROCESS_OBJECT_ACCESS_DENIED = -2147221190,
//
// Summary:
// The Visual Studio Remote Debugger (MSVSMON.EXE) has insufficient privileges to
// debug this process. To debug this process, launch the remote debugger using 'Run
// as administrator'. If the remote debugger has been configured to run as a service,
// ensure that it is running under an account that is a member of the Administrators
// group.
E_REMOTE_ATTACH_REQUIRES_ELEVATION = -2147221189,
//
// Summary:
// This program requires additional permissions to start. To debug this program,
// launch the Visual Studio Remote Debugger (MSVSMON.EXE) using 'Run as administrator'.
E_REMOTE_LAUNCH_ELEVATION_REQUIRED = -2147221188,
//
// Summary:
// The attempt to unwind the callstack failed. Unwinding is not possible in the
// following scenarios: 1. Debugging was started via Just-In-Time debugging. 2.
// An unwind is in progress. 3. A System.StackOverflowException or System.Threading.ThreadAbortException
// exception has been thrown.
E_EXCEPTION_CANNOT_BE_INTERCEPTED = -2147221184,
//
// Summary:
// You can only unwind to the function that caused the exception.
E_EXCEPTION_CANNOT_UNWIND_ABOVE_CALLBACK = -2147221183,
//
// Summary:
// Unwinding from the current exception is not supported.
E_INTERCEPT_CURRENT_EXCEPTION_NOT_SUPPORTED = -2147221182,
//
// Summary:
// You cannot unwind from an unhandled exception while doing managed and native
// code debugging at the same time.
E_INTERCEPT_CANNOT_UNWIND_LASTCHANCE_INTEROP = -2147221181,
E_JMC_CANNOT_SET_STATUS = -2147221179,
//
// Summary:
// The process has been terminated.
E_DESTROYED = -2147220991,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor is either not running on
// the remote machine or is running in Windows authentication mode.
E_REMOTE_NOMSVCMON = -2147220990,
//
// Summary:
// The IP address for the remote machine is not valid.
E_REMOTE_BADIPADDRESS = -2147220989,
//
// Summary:
// The remote machine is not responding.
E_REMOTE_MACHINEDOWN = -2147220988,
//
// Summary:
// The remote machine name is not specified.
E_REMOTE_MACHINEUNSPECIFIED = -2147220987,
//
// Summary:
// Other programs cannot be debugged during the current mixed dump debugging session.
E_CRASHDUMP_ACTIVE = -2147220986,
//
// Summary:
// All of the threads are frozen. Use the Threads window to unfreeze at least one
// thread before attempting to step or continue the process.
E_ALL_THREADS_SUSPENDED = -2147220985,
//
// Summary:
// The debugger transport DLL cannot be loaded.
E_LOAD_DLL_TL = -2147220984,
//
// Summary:
// mspdb110.dll cannot be loaded.
E_LOAD_DLL_SH = -2147220983,
//
// Summary:
// MSDIS170.dll cannot be loaded.
E_LOAD_DLL_EM = -2147220982,
//
// Summary:
// NatDbgEE.dll cannot be loaded.
E_LOAD_DLL_EE = -2147220981,
//
// Summary:
// NatDbgDM.dll cannot be loaded.
E_LOAD_DLL_DM = -2147220980,
//
// Summary:
// Old version of DBGHELP.DLL found, does not support minidumps.
E_LOAD_DLL_MD = -2147220979,
//
// Summary:
// Input or output cannot be redirected because the specified file is invalid.
E_IOREDIR_BADFILE = -2147220978,
//
// Summary:
// Input or output cannot be redirected because the syntax is incorrect.
E_IOREDIR_BADSYNTAX = -2147220977,
//
// Summary:
// The remote debugger is not an acceptable version.
E_REMOTE_BADVERSION = -2147220976,
//
// Summary:
// This operation is not supported when debugging dump files.
E_CRASHDUMP_UNSUPPORTED = -2147220975,
//
// Summary:
// The remote computer does not have a CLR version which is compatible with the
// remote debugging components. To install a compatible CLR version, see the instructions
// in the 'Remote Components Setup' page on the Visual Studio CD.
E_REMOTE_BAD_CLR_VERSION = -2147220974,
//
// Summary:
// The specified file is an unrecognized or unsupported binary format.
E_UNSUPPORTED_BINARY = -2147220971,
//
// Summary:
// The process has been soft broken.
E_DEBUGGEE_BLOCKED = -2147220970,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer is
// running as a different user.
E_REMOTE_NOUSERMSVCMON = -2147220969,
//
// Summary:
// Stepping to or from system code on a machine running Windows 95/Windows 98/Windows
// ME is not allowed.
E_STEP_WIN9xSYSCODE = -2147220968,
E_INTEROP_ORPC_INIT = -2147220967,
//
// Summary:
// The 64-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE)
// cannot be used to debug 32-bit processes or 32-bit dumps. Please use the 32-bit
// version instead.
E_CANNOT_DEBUG_WIN32 = -2147220965,
//
// Summary:
// The 32-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE)
// cannot be used to debug 64-bit processes or 64-bit dumps. Please use the 64-bit
// version instead.
E_CANNOT_DEBUG_WIN64 = -2147220964,
//
// Summary:
// Mini-Dumps cannot be read on this system. Please use a Windows NT based system
E_MINIDUMP_READ_WIN9X = -2147220963,
//
// Summary:
// Attaching to a process in a different terminal server session is not supported
// on this computer. Try remote debugging to the machine and running the Microsoft
// Visual Studio Remote Debugging Monitor in the process's session.
E_CROSS_TSSESSION_ATTACH = -2147220962,
//
// Summary:
// A stepping breakpoint could not be set
E_STEP_BP_SET_FAILED = -2147220961,
//
// Summary:
// The debugger transport DLL being loaded has an incorrect version.
E_LOAD_DLL_TL_INCORRECT_VERSION = -2147220960,
//
// Summary:
// NatDbgDM.dll being loaded has an incorrect version.
E_LOAD_DLL_DM_INCORRECT_VERSION = -2147220959,
E_REMOTE_NOMSVCMON_PIPE = -2147220958,
//
// Summary:
// msdia120.dll cannot be loaded.
E_LOAD_DLL_DIA = -2147220957,
//
// Summary:
// The dump file you opened is corrupted.
E_DUMP_CORRUPTED = -2147220956,
//
// Summary:
// Mixed-mode debugging of x64 processes is not supported when using Microsoft.NET
// Framework versions earlier than 4.0.
E_INTEROP_X64 = -2147220955,
//
// Summary:
// Debugging older format crashdumps is not supported.
E_CRASHDUMP_DEPRECATED = -2147220953,
//
// Summary:
// Debugging managed-only minidumps is not supported. Specify 'Mixed' for the 'Debugger
// Type' in project properties.
E_LAUNCH_MANAGEDONLYMINIDUMP_UNSUPPORTED = -2147220952,
//
// Summary:
// Debugging managed or mixed-mode minidumps is not supported on IA64 platforms.
// Specify 'Native' for the 'Debugger Type' in project properties.
E_LAUNCH_64BIT_MANAGEDMINIDUMP_UNSUPPORTED = -2147220951,
//
// Summary:
// The remote tools are not signed correctly.
E_DEVICEBITS_NOT_SIGNED = -2147220479,
//
// Summary:
// Attach is not enabled for this process with this debug type.
E_ATTACH_NOT_ENABLED = -2147220478,
//
// Summary:
// The connection has been broken.
E_REMOTE_DISCONNECT = -2147220477,
//
// Summary:
// The threads in the process cannot be suspended at this time. This may be a temporary
// condition.
E_BREAK_ALL_FAILED = -2147220476,
//
// Summary:
// Access denied. Try again, then check your device for a prompt.
E_DEVICE_ACCESS_DENIED_SELECT_YES = -2147220475,
//
// Summary:
// Unable to complete the operation. This could be because the device's security
// settings are too restrictive. Please use the Device Security Manager to change
// the settings and try again.
E_DEVICE_ACCESS_DENIED = -2147220474,
//
// Summary:
// The remote connection to the device has been lost. Verify the device connection
// and restart debugging.
E_DEVICE_CONNRESET = -2147220473,
//
// Summary:
// Unable to load the CLR. The target device does not have a compatible version
// of the CLR installed for the application you are attempting to debug. Verify
// that your device supports the appropriate CLR version and has that CLR installed.
// Some devices do not support automatic CLR upgrade.
E_BAD_NETCF_VERSION = -2147220472,
E_REFERENCE_NOT_VALID = -2147220223,
E_PROPERTY_NOT_VALID = -2147220207,
E_SETVALUE_VALUE_CANNOT_BE_SET = -2147220191,
E_SETVALUE_VALUE_IS_READONLY = -2147220190,
E_SETVALUEASREFERENCE_NOTSUPPORTED = -2147220189,
E_CANNOT_GET_UNMANAGED_MEMORY_CONTEXT = -2147220127,
E_GETREFERENCE_NO_REFERENCE = -2147220095,
E_CODE_CONTEXT_OUT_OF_SCOPE = -2147220063,
E_INVALID_SESSIONID = -2147220062,
//
// Summary:
// The Visual Studio Remote Debugger on the target computer cannot connect back
// to this computer. A firewall may be preventing communication via DCOM to the
// local computer. It may be possible to avoid this error by changing your settings
// to debug only native code or only managed code.
E_SERVER_UNAVAILABLE_ON_CALLBACK = -2147220061,
//
// Summary:
// The Visual Studio Remote Debugger on the target computer cannot connect back
// to this computer. Authentication failed. It may be possible to avoid this error
// by changing your settings to debug only native code or only managed code.
E_ACCESS_DENIED_ON_CALLBACK = -2147220060,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer could
// not connect to this computer because there was no available authentication service.
// It may be possible to avoid this error by changing your settings to debug only
// native code or only managed code.
E_UNKNOWN_AUTHN_SERVICE_ON_CALLBACK = -2147220059,
E_NO_SESSION_AVAILABLE = -2147220058,
E_CLIENT_NOT_LOGGED_ON = -2147220057,
E_OTHER_USERS_SESSION = -2147220056,
E_USER_LEVEL_ACCESS_CONTROL_REQUIRED = -2147220055,
//
// Summary:
// Can not evaluate script expressions while thread is stopped in the CLR.
E_SCRIPT_CLR_EE_DISABLED = -2147220048,
//
// Summary:
// Server side-error occurred on sending debug HTTP request.
E_HTTP_SERVERERROR = -2147219712,
//
// Summary:
// An authentication error occurred while communicating with the web server. Please
// see Help for assistance.
E_HTTP_UNAUTHORIZED = -2147219711,
//
// Summary:
// Could not start ASP.NET debugging. More information may be available by starting
// the project without debugging.
E_HTTP_SENDREQUEST_FAILED = -2147219710,
//
// Summary:
// The web server is not configured correctly. See help for common configuration
// errors. Running the web page outside of the debugger may provide further information.
E_HTTP_FORBIDDEN = -2147219709,
//
// Summary:
// The server does not support debugging of ASP.NET or ATL Server applications.
// Click Help for more information on how to enable debugging.
E_HTTP_NOT_SUPPORTED = -2147219708,
//
// Summary:
// Could not start ASP.NET or ATL Server debugging.
E_HTTP_NO_CONTENT = -2147219707,
//
// Summary:
// The web server could not find the requested resource.
E_HTTP_NOT_FOUND = -2147219706,
//
// Summary:
// The debug request could not be processed by the server due to invalid syntax.
E_HTTP_BAD_REQUEST = -2147219705,
//
// Summary:
// You do not have permissions to debug the web server process. You need to either
// be running as the same user account as the web server, or have administrator
// privilege.
E_HTTP_ACCESS_DENIED = -2147219704,
//
// Summary:
// Unable to connect to the web server. Verify that the web server is running and
// that incoming HTTP requests are not blocked by a firewall.
E_HTTP_CONNECT_FAILED = -2147219703,
E_HTTP_EXCEPTION = -2147219702,
//
// Summary:
// The web server did not respond in a timely manner. This may be because another
// debugger is already attached to the web server.
E_HTTP_TIMEOUT = -2147219701,
//
// Summary:
// IIS does not list a web site that matches the launched URL.
E_HTTP_SITE_NOT_FOUND = -2147219700,
//
// Summary:
// IIS does not list an application that matches the launched URL.
E_HTTP_APP_NOT_FOUND = -2147219699,
//
// Summary:
// Debugging requires the IIS Management Console. To install, go to Control Panel->Programs->Turn
// Windows features on or off. Check Internet Information Services->Web Management
// Tools->IIS Management Console.
E_HTTP_MANAGEMENT_API_MISSING = -2147219698,
//
// Summary:
// The IIS worker process for the launched URL is not currently running.
E_HTTP_NO_PROCESS = -2147219697,
E_64BIT_COMPONENTS_NOT_INSTALLED = -2147219632,
//
// Summary:
// The Visual Studio debugger cannot connect to the remote computer. Unable to initiate
// DCOM communication. Please see Help for assistance.
E_UNMARSHAL_SERVER_FAILED = -2147219631,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer cannot
// connect to the local computer. Unable to initiate DCOM communication. Please
// see Help for assistance.
E_UNMARSHAL_CALLBACK_FAILED = -2147219630,
//
// Summary:
// The Visual Studio debugger cannot connect to the remote computer. An RPC policy
// is enabled on the local computer which prevents remote debugging. Please see
// Help for assistance.
E_RPC_REQUIRES_AUTHENTICATION = -2147219627,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor cannot logon to the local
// computer: unknown user name or bad password. It may be possible to avoid this
// error by changing your settings to debug only native code or only managed code.
E_LOGON_FAILURE_ON_CALLBACK = -2147219626,
//
// Summary:
// The Visual Studio debugger cannot establish a DCOM connection to the remote computer.
// A firewall may be preventing communication via DCOM to the remote computer. It
// may be possible to avoid this error by changing your settings to debug only native
// code or only managed code.
E_REMOTE_SERVER_UNAVAILABLE = -2147219625,
E_REMOTE_CONNECT_USER_CANCELED = -2147219624,
//
// Summary:
// Windows file sharing has been configured so that you will connect to the remote
// computer using a different user name. This is incompatible with remote debugging.
// Please see Help for assistance.
E_REMOTE_CREDENTIALS_PROHIBITED = -2147219623,
//
// Summary:
// Windows Firewall does not currently allow exceptions. Use Control Panel to change
// the Windows Firewall settings so that exceptions are allowed.
E_FIREWALL_NO_EXCEPTIONS = -2147219622,
//
// Summary:
// Cannot add an application to the Windows Firewall exception list. Use the Control
// Panel to manually configure the Windows Firewall.
E_FIREWALL_CANNOT_OPEN_APPLICATION = -2147219621,
//
// Summary:
// Cannot add a port to the Windows Firewall exception list. Use the Control Panel
// to manually configure the Windows Firewall.
E_FIREWALL_CANNOT_OPEN_PORT = -2147219620,
//
// Summary:
// Cannot add 'File and Printer Sharing' to the Windows Firewall exception list.
// Use the Control Panel to manually configure the Windows Firewall.
E_FIREWALL_CANNOT_OPEN_FILE_SHARING = -2147219619,
//
// Summary:
// Remote debugging is not supported.
E_REMOTE_DEBUGGING_UNSUPPORTED = -2147219618,
E_REMOTE_BAD_MSDBG2 = -2147219617,
E_ATTACH_USER_CANCELED = -2147219616,
//
// Summary:
// Maximum packet length exceeded. If the problem continues, reduce the number of
// network host names or network addresses that are assigned to the computer running
// Visual Studio computer or to the target computer.
E_REMOTE_PACKET_TOO_BIG = -2147219615,
//
// Summary:
// The target process is running a version of the Microsoft .NET Framework newer
// than this version of Visual Studio. Visual Studio cannot debug this process.
E_UNSUPPORTED_FUTURE_CLR_VERSION = -2147219614,
//
// Summary:
// This version of Visual Studio does not support debugging code that uses Microsoft
// .NET Framework v1.0. Use Visual Studio 2008 or earlier to debug this process.
E_UNSUPPORTED_CLR_V1 = -2147219613,
//
// Summary:
// Mixed-mode debugging of IA64 processes is not supported.
E_INTEROP_IA64 = -2147219612,
//
// Summary:
// See help for common configuration errors. Running the web page outside of the
// debugger may provide further information.
E_HTTP_GENERAL = -2147219611,
//
// Summary:
// IDebugCoreServer* implementation does not have a connection to the remote computer.
// This can occur in T-SQL debugging when there is no remote debugging monitor.
E_REMOTE_NO_CONNECTION = -2147219610,
//
// Summary:
// The specified remote debugging proxy server name is invalid.
E_REMOTE_INVALID_PROXY_SERVER_NAME = -2147219609,
//
// Summary:
// Operation is not permitted on IDebugCoreServer* implementation which has a weak
// connection to the remote msvsmon instance. Weak connections are used when no
// process is being debugged.
E_REMOTE_WEAK_CONNECTION = -2147219608,
//
// Summary:
// Remote program providers are no longer supported before debugging begins (ex:
// process enumeration).
E_REMOTE_PROGRAM_PROVIDERS_UNSUPPORTED = -2147219607,
//
// Summary:
// Connection request was rejected by the remote debugger. Ensure that the remote
// debugger is running in 'No Authentication' mode.
E_REMOTE_REJECTED_NO_AUTH_REQUEST = -2147219606,
//
// Summary:
// Connection request was rejected by the remote debugger. Ensure that the remote
// debugger is running in 'Windows Authentication' mode.
E_REMOTE_REJECTED_WIN_AUTH_REQUEST = -2147219605,
//
// Summary:
// The debugger was unable to create a localhost TCP/IP connection, which is required
// for 64-bit debugging.
E_PSEUDOREMOTE_NO_LOCALHOST_TCPIP_CONNECTION = -2147219604,
//
// Summary:
// This operation requires the Windows Web Services API to be installed, and it
// is not currently installed on this computer.
E_REMOTE_WWS_NOT_INSTALLED = -2147219603,
//
// Summary:
// This operation requires the Windows Web Services API to be installed, and it
// is not currently installed on this computer. To install Windows Web Services,
// please restart Visual Studio as an administrator on this computer.
E_REMOTE_WWS_INSTALL_REQUIRES_ADMIN = -2147219602,
//
// Summary:
// The expression has not yet been translated to native machine code.
E_FUNCTION_NOT_JITTED = -2147219456,
E_NO_CODE_CONTEXT = -2147219455,
//
// Summary:
// A Microsoft .NET Framework component, diasymreader.dll, is not correctly installed.
// Please repair your Microsoft .NET Framework installation via 'Add or Remove Programs'
// in Control Panel.
E_BAD_CLR_DIASYMREADER = -2147219454,
//
// Summary:
// Unable to load the CLR. If a CLR version was specified for debugging, check that
// it was valid and installed on the machine. If the problem persists, please repair
// your Microsoft .NET Framework installation via 'Programs and Features' in Control
// Panel.
E_CLR_SHIM_ERROR = -2147219453,
//
// Summary:
// Unable to map the debug start page URL to a machine name.
E_AUTOATTACH_WEBSERVER_NOT_FOUND = -2147219199,
E_DBGEXTENSION_NOT_FOUND = -2147219184,
E_DBGEXTENSION_FUNCTION_NOT_FOUND = -2147219183,
E_DBGEXTENSION_FAULTED = -2147219182,
E_DBGEXTENSION_RESULT_INVALID = -2147219181,
E_PROGRAM_IN_RUNMODE = -2147219180,
//
// Summary:
// The remote procedure could not be debugged. This usually indicates that debugging
// has not been enabled on the server. See help for more information.
E_CAUSALITY_NO_SERVER_RESPONSE = -2147219168,
//
// Summary:
// Please install the Visual Studio Remote Debugger on the server to enable this
// functionality.
E_CAUSALITY_REMOTE_NOT_REGISTERED = -2147219167,
//
// Summary:
// The debugger failed to stop in the server process.
E_CAUSALITY_BREAKPOINT_NOT_HIT = -2147219166,
//
// Summary:
// Unable to determine a stopping location. Verify symbols are loaded.
E_CAUSALITY_BREAKPOINT_BIND_ERROR = -2147219165,
//
// Summary:
// Debugging this project is disabled. Debugging can be re-enabled from 'Start Options'
// under project properties.
E_CAUSALITY_PROJECT_DISABLED = -2147219164,
//
// Summary:
// Unable to attach the debugger to TSQL code.
E_NO_ATTACH_WHILE_DDD = -2147218944,
//
// Summary:
// Click Help for more information.
E_SQLLE_ACCESSDENIED = -2147218943,
//
// Summary:
// Click Help for more information.
E_SQL_SP_ENABLE_PERMISSION_DENIED = -2147218942,
//
// Summary:
// Click Help for more information.
E_SQL_DEBUGGING_NOT_ENABLED_ON_SERVER = -2147218941,
//
// Summary:
// Click Help for more information.
E_SQL_CANT_FIND_SSDEBUGPS_ON_CLIENT = -2147218940,
//
// Summary:
// Click Help for more information.
E_SQL_EXECUTED_BUT_NOT_DEBUGGED = -2147218939,
//
// Summary:
// Click Help for more information.
E_SQL_VDT_INIT_RETURNED_SQL_ERROR = -2147218938,
E_ATTACH_FAILED_ABORT_SILENTLY = -2147218937,
//
// Summary:
// Click Help for more information.
E_SQL_REGISTER_FAILED = -2147218936,
E_DE_NOT_SUPPORTED_PRE_8_0 = -2147218688,
E_PROGRAM_DESTROY_PENDING = -2147218687,
//
// Summary:
// The operation isn't supported for the Common Language Runtime version used by
// the process being debugged.
E_MANAGED_FEATURE_NOTSUPPORTED = -2147218515,
//
// Summary:
// The Visual Studio Remote Debugger does not support this edition of Windows.
E_OS_PERSONAL = -2147218432,
//
// Summary:
// Source server support is disabled because the assembly is partially trusted.
E_SOURCE_SERVER_DISABLE_PARTIAL_TRUST = -2147218431,
//
// Summary:
// Operation is not supported on the platform of the target computer/device.
E_REMOTE_UNSUPPORTED_OPERATION_ON_PLATFORM = -2147218430,
//
// Summary:
// Unable to load Visual Studio debugger component (vsdebugeng.dll). If this problem
// persists, repair your installation via 'Add or Remove Programs' in Control Panel.
E_LOAD_VSDEBUGENG_FAILED = -2147218416,
//
// Summary:
// Unable to initialize Visual Studio debugger component (vsdebugeng.dll). If this
// problem persists, repair your installation via 'Add or Remove Programs' in Control
// Panel.
E_LOAD_VSDEBUGENG_IMPORTS_FAILED = -2147218415,
//
// Summary:
// Unable to initialize Visual Studio debugger due to a configuration error. If
// this problem persists, repair your installation via 'Add or Remove Programs'
// in Control Panel.
E_LOAD_VSDEBUGENG_CONFIG_ERROR = -2147218414,
//
// Summary:
// Failed to launch minidump. The minidump file is corrupt.
E_CORRUPT_MINIDUMP = -2147218413,
//
// Summary:
// Unable to load a Visual Studio component (VSDebugScriptAgent110.dll). If the
// problem persists, repair your installation via 'Add or Remove Programs' in Control
// Panel.
E_LOAD_SCRIPT_AGENT_LOCAL_FAILURE = -2147218412,
//
// Summary:
// Remote script debugging requires that the remote debugger is registered on the
// target computer. Run the Visual Studio Remote Debugger setup (rdbgsetup_<processor>.exe)
// on the target computer.
E_LOAD_SCRIPT_AGENT_REMOTE_FAILURE = -2147218410,
//
// Summary:
// The debugger was unable to find the registration for the target application.
// If the problem persists, try uninstalling and then reinstalling this application.
E_APPX_REGISTRATION_NOT_FOUND = -2147218409,
//
// Summary:
// Unable to find a Visual Studio component (VsDebugLaunchNotify.exe). For remote
// debugging, this file must be present on the target computer. If the problem persists,
// repair your installation via 'Add or Remove Programs' in Control Panel.
E_VSDEBUGLAUNCHNOTIFY_NOT_INSTALLED = -2147218408,
//
// Summary:
// Windows 8 build# 8017 or higher is required to debug Windows Store apps.
E_WIN8_TOO_OLD = -2147218404,
E_THREAD_NOT_FOUND = -2147218175,
//
// Summary:
// Cannot auto-attach to the SQL Server, possibly because the firewall is configured
// incorrectly or auto-attach is forbidden by the operating system.
E_CANNOT_AUTOATTACH_TO_SQLSERVER = -2147218174,
E_OBJECT_OUT_OF_SYNC = -2147218173,
E_PROCESS_ALREADY_CONTINUED = -2147218172,
//
// Summary:
// Debugging multiple GPU processes is not supported.
E_CANNOT_DEBUG_MULTI_GPU_PROCS = -2147218171,
//
// Summary:
// No available devices supported by the selected debug engine. Please select a
// different engine.
E_GPU_ADAPTOR_NOT_FOUND = -2147218170,
//
// Summary:
// A Microsoft Windows component is not correctly registered. Please ensure that
// the Desktop Experience is enabled in Server Manager -> Manage -> Add Server Roles
// and Features.
E_WINDOWS_GRAPHICAL_SHELL_UNINSTALLED_ERROR = -2147218169,
//
// Summary:
// Windows 8 or higher was required for GPU debugging on the software emulator.
// For the most up-to-date information, please visit the link below. http://go.microsoft.com/fwlink/p/?LinkId=330081
E_GPU_DEBUG_NOT_SUPPORTED_PRE_DX_11_1 = -2147218168,
//
// Summary:
// There is a configuration issue with the selected Debugging Accelerator Type.
// For information on specific Accelerator providers, visit http://go.microsoft.com/fwlink/p/?LinkId=323500
E_GPU_DEBUG_CONFIG_ISSUE = -2147218167,
//
// Summary:
// Local debugging is not supported for the selected Debugging Accelerator Type.
// Use Remote Windows Debugger instead or change the Debugging Accelerator Type
E_GPU_LOCAL_DEBUGGING_ERROR = -2147218166,
//
// Summary:
// The debug driver for the selected Debugging Accelerator Type is not installed
// on the target machine. For more information, visit http://go.microsoft.com/fwlink/p/?LinkId=323500
E_GPU_LOAD_VSD3D_FAILURE = -2147218165,
//
// Summary:
// Timeout Detection and Recovery (TDR) must be disabled at the remote site. For
// more information search for 'TdrLevel' in MSDN or visit the link below. http://go.microsoft.com/fwlink/p/?LinkId=323500
E_GPU_TDR_ENABLED_FAILURE = -2147218164,
//
// Summary:
// Remote debugger does not support mixed (managed and native) debugger type.
E_CANNOT_REMOTE_DEBUG_MIXED = -2147218163,
//
// Summary:
// Background Task activation failed Please see Help for further information.
E_BG_TASK_ACTIVATION_FAILED = -2147218162,
//
// Summary:
// This version of the Visual Studio Remote Debugger does not support this operation.
// Please upgrade to the latest version. http://go.microsoft.com/fwlink/p/?LinkId=219549
E_REMOTE_VERSION = -2147218161,
//
// Summary:
// Unable to load a Visual Studio component (symbollocator.resources.dll). If the
// problem persists, repair your installation via 'Add or Remove Programs' in Control
// Panel.
E_SYMBOL_LOCATOR_INSTALL_ERROR = -2147218160,
//
// Summary:
// The format of the PE module is invalid.
E_INVALID_PE_FORMAT = -2147218159,
//
// Summary:
// This dump is already being debugged.
E_DUMP_ALREADY_LAUNCHED = -2147218158,
//
// Summary:
// The next statement cannot be set because the current assembly is optimized.
E_CANNOT_SET_NEXT_STATEMENT_IN_OPTIMIZED_CODE = -2147218157,
//
// Summary:
// Debugging of ARM minidumps requires Windows 8 or above.
E_ARMDUMP_NOT_SUPPORTED_PRE_WIN8 = -2147218156,
//
// Summary:
// Cannot detach while process termination is in progress.
E_CANNOT_DETACH_WHILE_TERMINATE_IN_PROGRESS = -2147218155,
//
// Summary:
// A required Microsoft Windows component, wldp.dll could not be found on the target
// device.
E_WLDP_NOT_FOUND = -2147218154,
//
// Summary:
// The target device does not allow debugging this process.
E_DEBUGGING_BLOCKED_ON_TARGET = -2147218153,
//
// Summary:
// Unable to debug .NET Native code. Install the Microsoft .NET Native Developer
// SDK. Alternatively debug with native code type.
E_DOTNETNATIVE_SDK_NOT_INSTALLED = -2147218152,
//
// Summary:
// The operation was canceled.
COR_E_OPERATIONCANCELED = -2146233029,
//
// Summary:
// A component dll failed to load. Try to restart this application. If failures
// continue, try disabling any installed add-ins or repair your installation.
E_XAPI_COMPONENT_LOAD_FAILURE = -1898053632,
//
// Summary:
// Xapi has not been initialized on this thread. Call ComponentManager.InitializeThread.
E_XAPI_NOT_INITIALIZED = -1898053631,
//
// Summary:
// Xapi has already been initialized on this thread.
E_XAPI_ALREADY_INITIALIZED = -1898053630,
//
// Summary:
// Xapi event thread aborted unexpectedly.
E_XAPI_THREAD_ABORTED = -1898053629,
//
// Summary:
// Component failed a call to QueryInterface. QueryInterface implementation or component
// configuration is incorrect.
E_XAPI_BAD_QUERY_INTERFACE = -1898053628,
//
// Summary:
// Object requested which is not available at the caller's component level.
E_XAPI_UNAVAILABLE_OBJECT = -1898053627,
//
// Summary:
// Failed to process configuration file. Try to restart this application. If failures
// continue, try to repair your installation.
E_XAPI_BAD_CONFIG = -1898053626,
//
// Summary:
// Failed to initialize managed/native marshalling system. Try to restart this application.
// If failures continue, try to repair your installation.
E_XAPI_MANAGED_DISPATCHER_CONNECT_FAILURE = -1898053625,
//
// Summary:
// This operation may only be preformed while processing the object's 'Create' event.
E_XAPI_DURING_CREATE_EVENT_REQUIRED = -1898053624,
//
// Summary:
// This operation may only be preformed by the component which created the object.
E_XAPI_CREATOR_REQUIRED = -1898053623,
//
// Summary:
// The work item cannot be appended to the work list because it is already complete.
E_XAPI_WORK_LIST_COMPLETE = -1898053622,
//
// Summary:
// 'Execute' may not be called on a work list which has already started.
E_XAPI_WORKLIST_ALREADY_STARTED = -1898053621,
//
// Summary:
// The interface implementation released the completion routine without calling
// it.
E_XAPI_COMPLETION_ROUTINE_RELEASED = -1898053620,
//
// Summary:
// Operation is not supported on this thread.
E_XAPI_WRONG_THREAD = -1898053619,
//
// Summary:
// No component with the given component id could be found in the configuration
// store.
E_XAPI_COMPONENTID_NOT_FOUND = -1898053618,
//
// Summary:
// Call was attempted to a remote connection from a server-side component (component
// level > 100000). This is not allowed.
E_XAPI_WRONG_CONNECTION_OBJECT = -1898053617,
//
// Summary:
// Destination of this call is on a remote connection and this method doesn't support
// remoting.
E_XAPI_METHOD_NOT_REMOTED = -1898053616,
//
// Summary:
// The network connection to the Visual Studio Remote Debugger was lost.
E_XAPI_REMOTE_DISCONNECTED = -1898053615,
//
// Summary:
// The network connection to the Visual Studio Remote Debugger has been closed.
E_XAPI_REMOTE_CLOSED = -1898053614,
//
// Summary:
// A protocol compatibility error occurred between Visual Studio and the Remote
// Debugger. Please ensure that the Visual Studio and Remote debugger versions match.
E_XAPI_INCOMPATIBLE_PROTOCOL = -1898053613,
//
// Summary:
// Maximum allocation size exceeded while processing a remoting message.
E_XAPI_MAX_PACKET_EXCEEDED = -1898053612,
//
// Summary:
// An object already exists with the same key value.
E_XAPI_OBJECT_ALREADY_EXISTS = -1898053611,
//
// Summary:
// An object cannot be found with the given key value.
E_XAPI_OBJECT_NOT_FOUND = -1898053610,
//
// Summary:
// A data item already exists with the same key value.
E_XAPI_DATA_ITEM_ALREADY_EXISTS = -1898053609,
//
// Summary:
// A data item cannot be for this component found with the given data item ID.
E_XAPI_DATA_ITEM_NOT_FOUND = -1898053608,
//
// Summary:
// Interface implementation failed to provide a required out param.
E_XAPI_NULL_OUT_PARAM = -1898053607,
//
// Summary:
// Strong name signature validation error while trying to load the managed dispatcher
E_XAPI_MANAGED_DISPATCHER_SIGNATURE_ERROR = -1898053600,
//
// Summary:
// Method may only be called by components which load in the IDE process (component
// level > 100000).
E_XAPI_CLIENT_ONLY_METHOD = -1898053599,
//
// Summary:
// Method may only be called by components which load in the remote debugger process
// (component level < 100000).
E_XAPI_SERVER_ONLY_METHOD = -1898053598,
//
// Summary:
// A component dll could not be found. If failures continue, try disabling any installed
// add-ins or repairing your installation.
E_XAPI_COMPONENT_DLL_NOT_FOUND = -1898053597,
//
// Summary:
// Operation requires the remote debugger be updated to a newer version.
E_XAPI_REMOTE_NEW_VER_REQUIRED = -1898053596,
//
// Summary:
// Symbols are not loaded for the target dll.
E_SYMBOLS_NOT_LOADED = -1842151424,
//
// Summary:
// Symbols for the target dll do not contain source information.
E_SYMBOLS_STRIPPED = -1842151423,
//
// Summary:
// Breakpoint could not be written at the specified instruction address.
E_BP_INVALID_ADDRESS = -1842151422,
//
// Summary:
// Breakpoints cannot be set in optimized code when the debugger option 'Just My
// Code' is enabled.
E_BP_IN_OPTIMIZED_CODE = -1842151420,
//
// Summary:
// The Common Language Runtime was unable to set the breakpoint.
E_BP_CLR_ERROR = -1842151418,
//
// Summary:
// Cannot set breakpoints in .NET Framework methods which are implemented in native
// code (ex: 'extern' function).
E_BP_CLR_EXTERN_FUNCTION = -1842151417,
//
// Summary:
// Cannot set breakpoint, target module is currently unloaded.
E_BP_MODULE_UNLOADED = -1842151416,
//
// Summary:
// Stopping events cannot be sent. See stopping event processing documentation for
// more information.
E_STOPPING_EVENT_REJECTED = -1842151415,
//
// Summary:
// This operation is not permitted because the target process is already stopped.
E_TARGET_ALREADY_STOPPED = -1842151414,
//
// Summary:
// This operation is not permitted because the target process is not stopped.
E_TARGET_NOT_STOPPED = -1842151413,
//
// Summary:
// This operation is not allowed on this thread.
E_WRONG_THREAD = -1842151412,
//
// Summary:
// This operation is not allowed at this time.
E_WRONG_TIME = -1842151411,
//
// Summary:
// The caller is not allowed to request this operation. This operation must be requested
// by a different component.
E_WRONG_COMPONENT = -1842151410,
//
// Summary:
// Operation is only permitted on the latest version of an edited method.
E_WRONG_METHOD_VERSION = -1842151409,
//
// Summary:
// A memory read or write operation failed because the specified memory address
// is not currently valid.
E_INVALID_MEMORY_ADDRESS = -1842151408,
//
// Summary:
// No source information is available for this instruction.
E_INSTRUCTION_NO_SOURCE = -1842151407,
//
// Summary:
// Failed to load localizable resource from vsdebugeng.impl.resources.dll. If this
// problem persists, please repair your Visual Studio installation via 'Add or Remove
// Programs' in Control Panel.
E_VSDEBUGENG_RESOURCE_LOAD_FAILURE = -1842151406,
//
// Summary:
// DkmVariant is of a form that marshalling is not supported. Marshalling is supported
// for primitives types, strings, and safe arrays of primitives.
E_UNMARSHALLABLE_VARIANT = -1842151405,
//
// Summary:
// An incorrect version of vsdebugeng.dll was loaded into Visual Studio. Please
// repair your Visual Studio installation.
E_VSDEBUGENG_DEPLOYMENT_ERROR = -1842151404,
//
// Summary:
// The remote debugger was unable to initialize Microsoft Windows Web Services (webservices.dll).
// If the problem continues, try reinstalling the Windows Web Services redistributable.
// This redistributable can be found under the 'Remote Debugger\Common Resources\Windows
// Updates' folder.
E_WEBSERVICES_LOAD_FAILURE = -1842151403,
//
// Summary:
// Visual Studio encountered an error while loading a Windows component (Global
// Interface Table). If the problem persists, this may be an indication of operating
// system corruption, and Windows may need to be reinstalled.
E_GLOBAL_INTERFACE_POINTER_FAILURE = -1842151402,
//
// Summary:
// Windows authentication was unable to establish a secure connection to the remote
// computer.
E_REMOTE_AUTHENTICATION_ERROR = -1842151401,
//
// Summary:
// The Remote Debugger was unable to locate a resource dll (vsdebugeng.impl.resources.dll).
// Please ensure that the complete remote debugger folder was copied or installed
// on the target computer.
E_CANNOT_FIND_REMOTE_RESOURCES = -1842151400,
//
// Summary:
// The hardware does not support monitoring the requested number of bytes.
E_INVALID_DATABP_SIZE = -1842151392,
//
// Summary:
// The maximum number of data breakpoints have already been set.
E_INVALID_DATABP_ALLREGSUSED = -1842151391,
//
// Summary:
// Breakpoints cannot be set while debugging a minidump.
E_DUMPS_DO_NOT_SUPPORT_BREAKPOINTS = -1842151390,
//
// Summary:
// The minidump is from an ARM-based computer and can only be debugged on an ARM
// computer.
E_DUMP_ARM_ARCHITECTURE = -1842151389,
//
// Summary:
// The minidump is from an unknown processor, and cannot be debugged with this version
// of Visual Studio.
E_DUMP_UNKNOWN_ARCHITECTURE = -1842151388,
//
// Summary:
// The shell failed to find a checksum for this file.
E_NO_CHECKSUM = -1842151387,
//
// Summary:
// On x64, context control must be included in a SetThreadContext
E_CONTEXT_CONTROL_REQUIRED = -1842151386,
//
// Summary:
// The size of the buffer does not match the size of the register.
E_INVALID_REGISTER_SIZE = -1842151385,
//
// Summary:
// The requested register was not found in the stack frame's unwound register collection.
E_REGISTER_NOT_FOUND = -1842151384,
//
// Summary:
// Cannot set a read-only register.
E_REGISTER_READONLY = -1842151383,
//
// Summary:
// Cannot set a register in a frame that is not the top of the stack.
E_REG_NOT_TOP_STACK = -1842151376,
//
// Summary:
// String could not be read within the specified maximum number of characters.
E_STRING_TOO_LONG = -1842151375,
//
// Summary:
// The memory region does not meet the requested protection flags.
E_INVALID_MEMORY_PROTECT = -1842151374,
//
// Summary:
// Instruction is invalid or unknown to the disassembler.
E_UNKNOWN_CPU_INSTRUCTION = -1842151373,
//
// Summary:
// An invalid runtime was specified for this operation.
E_INVALID_RUNTIME = -1842151372,
//
// Summary:
// Variable is optimized away.
E_VARIABLE_OPTIMIZED_AWAY = -1842151371,
//
// Summary:
// The text span is not currently loaded in the specified script document.
E_TEXT_SPAN_NOT_LOADED = -1842151370,
//
// Summary:
// This location could not be mapped to client side script.
E_SCRIPT_SPAN_MAPPING_FAILED = -1842151369,
//
// Summary:
// The file requested must be less than 100 megabytes in size
E_DEPLOY_FILE_TOO_LARGE = -1842151368,
//
// Summary:
// The file path requested could not be written to as it is invalid. Ensure the
// path does not contain a file where a directory is expected.
E_DEPLOY_FILE_PATH_INVALID = -1842151367,
//
// Summary:
// Script debugging is not enabled for WWAHost.exe.
E_SCRIPT_DEBUGGING_DISABLED_WWAHOST_ATTACH_FAILED = -1842151360,
//
// Summary:
// The file path requested for deletion does not exist.
E_DEPLOY_FILE_NOT_EXIST = -1842151359,
//
// Summary:
// A command is already executing, only one may execute at a time. Please wait for
// the executable to exit, or abort the command.
E_EXECUTE_COMMAND_IN_PROGRESS = -1842151358,
//
// Summary:
// The specified file path is a relative or unknown path format. File paths must
// be fully qualified.
E_INVALID_FULL_PATH = -1842151357,
//
// Summary:
// Windows Store app debugging is not possible when the remote debugger is running
// as a service. Run the Remote Debugger Configuration Wizard on the target computer,
// and uncheck the option to start the remote debugger service. Then start the Visual
// Studio Remote Debugging Monitor application.
E_CANNOT_DEBUG_APP_PACKAGE_IN_RDBSERVICE = -1842151356,
//
// Summary:
// Applications cannot be launched under the debugger when the remote debugger is
// running as a service. Run the Remote Debugger Configuration Wizard on the target
// computer, and uncheck the option to start the remote debugger service. Then start
// the Visual Studio Remote Debugging Monitor application.
E_CANNOT_LAUNCH_IN_RDBSERVICE = -1842151355,
//
// Summary:
// The AD7 AL Causality bridge has already been initialized.
E_CAUSALITY_BRIDGE_ALREADY_INITIALIZED = -1842151354,
//
// Summary:
// App Packages may only be shutdown as part of a Visual Studio build operation.
E_DEPLOY_APPX_SHUTDOWN_WRONG_TIME = -1842151353,
//
// Summary:
// A Microsoft Windows component is not correctly registered. If the problem persists,
// try repairing your Windows installation, or reinstalling Windows.
E_WINDOWS_REG_ERROR = -1842151352,
//
// Summary:
// The application never reached a suspended state.
E_APP_PACKAGE_NEVER_SUSPENDED = -1842151351,
//
// Summary:
// A different version of this script file has been loaded by the debugged process.
// The script file may need to be reloaded.
E_SCRIPT_FILE_DIFFERENT_CONTENT = -1842151350,
//
// Summary:
// No stack frame was found.
E_NO_FRAME = -1842151349,
//
// Summary:
// Operation is not supported while interop debugging.
E_NOT_SUPPORTED_INTEROP = -1842151348,
//
// Summary:
// The selected accelerator does not support the run current tile to cursor operation.
E_GPU_BARRIER_BREAKPOINT_NOT_SUPPORTED = -1842151347,
//
// Summary:
// Data breakpoints are not supported on this platform.
E_DATABPS_NOTSUPPORTED = -1842151346,
//
// Summary:
// The debugger failed to attach to the process requested in the DkmDebugProcessRequest.
E_DEBUG_PROCESS_REQUEST_FAILED = -1842151345,
//
// Summary:
// An invalid NativeOffset or CPUInstructionPart value was used with a DkmClrInstructionAddress
// or DkmClrInstructionSymbol
E_INVALID_CLR_INSTRUCTION_NATIVE_OFFSET = -1842151339,
//
// Summary:
// Managed heap is not in a state that can be enumerated
E_MANAGED_HEAP_NOT_ENUMERABLE = -1842151338,
//
// Summary:
// This operation is unavailable when mixed mode debugging with Script
E_OPERATION_UNAVAILABLE_SCRIPT_INTEROP = -1842151337,
//
// Summary:
// This operation is unavailable when debugging native-compiled .NET code.
E_OPERATION_UNAVAILABLE_CLR_NC = -1842151336,
//
// Summary:
// Symbol file contains data which is in an unexpected format.
E_BAD_SYMBOL_DATA = -1842151335,
//
// Summary:
// Dynamically enabling script debugging in the target process failed.
E_ENABLE_SCRIPT_DEBUGGING_FAILED = -1842151334,
//
// Summary:
// Expression evaluation is not available in async call stack frames.
E_SCRIPT_ASYNC_FRAME_EE_UNAVAILABLE = -1842151333,
//
// Summary:
// This dump does not contain any thread information or the thread information is
// corrupt. Visual Studio does not support debugging of dumps without valid thread
// information.
E_DUMP_NO_THREADS = -1842151332,
//
// Summary:
// DkmLoadCompleteEventDeferral.Add cannot be called after the load complete event
// has been sent.
E_LOAD_COMPLETE_ALREADY_SENT = -1842151331,
//
// Summary:
// DkmLoadCompleteEventDeferral was not present in the list during a call to DkmLoadCompleteEventDeferral.Remove.
E_LOAD_COMPLETE_DEFERRAL_NOT_FOUND = -1842151330,
//
// Summary:
// The buffer size specified was too large to marshal over the remote boundary.
E_MARSHALLING_SIZE_TOO_LARGE = -1842151329,
//
// Summary:
// Emulation of iterator for results view failed. This is typically caused when
// the iterator calls into native code.
E_CANNOT_EMULATE_RESULTS_VIEW = -1842151328,
//
// Summary:
// Managed heap enumeration is attempted on running target. This is typically caused
// by continuing the process while heap enumeration is in progress.
E_MANAGED_HEAP_ENUMERATION_TARGET_NOT_STOPPED = -1842151327
}
}
| // 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
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\Concord\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
namespace Microsoft.VisualStudio.Debugger
{
//
// Summary:
// Defines the HRESULT codes used by this API.
public enum DkmExceptionCode
{
//
// Summary:
// Unspecified error.
E_FAIL = -2147467259,
//
// Summary:
// A debugger is already attached.
E_ATTACH_DEBUGGER_ALREADY_ATTACHED = -2147221503,
//
// Summary:
// The process does not have sufficient privileges to be debugged.
E_ATTACH_DEBUGGEE_PROCESS_SECURITY_VIOLATION = -2147221502,
//
// Summary:
// The desktop cannot be debugged.
E_ATTACH_CANNOT_ATTACH_TO_DESKTOP = -2147221501,
//
// Summary:
// Unmanaged debugging is not available.
E_LAUNCH_NO_INTEROP = -2147221499,
//
// Summary:
// Debugging isn't possible due to an incompatibility within the CLR implementation.
E_LAUNCH_DEBUGGING_NOT_POSSIBLE = -2147221498,
//
// Summary:
// Visual Studio cannot debug managed applications because a kernel debugger is
// enabled on the system. Please see Help for further information.
E_LAUNCH_KERNEL_DEBUGGER_ENABLED = -2147221497,
//
// Summary:
// Visual Studio cannot debug managed applications because a kernel debugger is
// present on the system. Please see Help for further information.
E_LAUNCH_KERNEL_DEBUGGER_PRESENT = -2147221496,
//
// Summary:
// The debugger does not support debugging managed and native code at the same time
// on the platform of the target computer/device. Configure the debugger to debug
// only native code or only managed code.
E_INTEROP_NOT_SUPPORTED = -2147221495,
//
// Summary:
// The maximum number of processes is already being debugged.
E_TOO_MANY_PROCESSES = -2147221494,
//
// Summary:
// Script debugging of your application is disabled in Internet Explorer. To enable
// script debugging in Internet Explorer, choose Internet Options from the Tools
// menu and navigate to the Advanced tab. Under the Browsing category, clear the
// 'Disable Script Debugging (Internet Explorer)' checkbox, then restart Internet
// Explorer.
E_MSHTML_SCRIPT_DEBUGGING_DISABLED = -2147221493,
//
// Summary:
// The correct version of pdm.dll is not registered. Repair your Visual Studio installation,
// or run 'regsvr32.exe "%CommonProgramFiles%\Microsoft Shared\VS7Debug\pdm.dll"'.
E_SCRIPT_PDM_NOT_REGISTERED = -2147221492,
//
// Summary:
// The .NET debugger has not been installed properly. The most probable cause is
// that mscordbi.dll is not properly registered. Click Help for more information
// on how to repair the .NET debugger.
E_DE_CLR_DBG_SERVICES_NOT_INSTALLED = -2147221491,
//
// Summary:
// There is no managed code running in the process. In order to attach to a process
// with the .NET debugger, managed code must be running in the process before attaching.
E_ATTACH_NO_CLR_PROGRAMS = -2147221490,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor has been closed on the remote
// machine.
E_REMOTE_SERVER_CLOSED = -2147221488,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer does
// not support debugging code running in the Common Language Runtime.
E_CLR_NOT_SUPPORTED = -2147221482,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer does
// not support debugging code running in the Common Language Runtime on a 64-bit
// computer.
E_64BIT_CLR_NOT_SUPPORTED = -2147221481,
//
// Summary:
// Cannot debug minidumps and processes at the same time.
E_CANNOT_MIX_MINDUMP_DEBUGGING = -2147221480,
E_DEBUG_ENGINE_NOT_REGISTERED = -2147221479,
//
// Summary:
// This application has failed to start because the application configuration is
// incorrect. Review the manifest file for possible errors. Reinstalling the application
// may fix this problem. For more details, please see the application event log.
E_LAUNCH_SXS_ERROR = -2147221478,
//
// Summary:
// Failed to initialize msdbg2.dll for script debugging. If this problem persists,
// use 'Add or Remove Programs' in Control Panel to repair your Visual Studio installation.
E_FAILED_TO_INITIALIZE_SCRIPT_PROXY = -2147221477,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor (MSVSMON.EXE) does not appear
// to be running on the remote computer. This may be because a firewall is preventing
// communication to the remote computer. Please see Help for assistance on configuring
// remote debugging.
E_REMOTE_SERVER_DOES_NOT_EXIST = -2147221472,
//
// Summary:
// Access is denied. Can not connect to Microsoft Visual Studio Remote Debugging
// Monitor on the remote computer.
E_REMOTE_SERVER_ACCESS_DENIED = -2147221471,
//
// Summary:
// The debugger cannot connect to the remote computer. The debugger was unable to
// resolve the specified computer name.
E_REMOTE_SERVER_MACHINE_DOES_NOT_EXIST = -2147221470,
//
// Summary:
// The debugger is not properly installed. Run setup to install or repair the debugger.
E_DEBUGGER_NOT_REGISTERED_PROPERLY = -2147221469,
//
// Summary:
// Access is denied. This seems to be because the 'Network access: Sharing and security
// model for local accounts' security policy does not allow users to authenticate
// as themselves. Please use the 'Local Security Settings' administration tool on
// the local computer to configure this option.
E_FORCE_GUEST_MODE_ENABLED = -2147221468,
E_GET_IWAM_USER_FAILURE = -2147221467,
//
// Summary:
// The specified remote server name is not valid.
E_REMOTE_SERVER_INVALID_NAME = -2147221466,
//
// Summary:
// Microsoft Visual Studio Debugging Monitor (MSVSMON.EXE) failed to start. If this
// problem persists, please repair your Visual Studio installation via 'Add or Remove
// Programs' in Control Panel.
E_AUTO_LAUNCH_EXEC_FAILURE = -2147221464,
//
// Summary:
// Microsoft Visual Studio Remote Debugging Monitor (MSVSMON.EXE) is not running
// under your user account and MSVSMON could not be automatically started. MSVSMON
// must be manually started, or the Visual Studio remote debugging components must
// be installed on the remote computer. Please see Help for assistance.
E_REMOTE_COMPONENTS_NOT_REGISTERED = -2147221461,
//
// Summary:
// A DCOM error occurred trying to contact the remote computer. Access is denied.
// It may be possible to avoid this error by changing your settings to debug only
// native code or only managed code.
E_DCOM_ACCESS_DENIED = -2147221460,
//
// Summary:
// Debugging using the Default transport is not possible because the remote machine
// has 'Share-level access control' enabled. To enable debugging on the remote machine,
// go to Control Panel -> Network -> Access control, and set Access control to be
// 'User-level access control'.
E_SHARE_LEVEL_ACCESS_CONTROL_ENABLED = -2147221459,
//
// Summary:
// Logon failure: unknown user name or bad password. See help for more information.
E_WORKGROUP_REMOTE_LOGON_FAILURE = -2147221458,
//
// Summary:
// Windows authentication is disabled in the Microsoft Visual Studio Remote Debugging
// Monitor (MSVSMON). To connect, choose one of the following options. 1. Enable
// Windows authentication in MSVSMON 2. Reconfigure your project to disable Windows
// authentication 3. Use the 'Remote (native with no authentication)' transport
// in the 'Attach to Process' dialog
E_WINAUTH_CONNECT_NOT_SUPPORTED = -2147221457,
//
// Summary:
// A previous expression evaluation is still in progress.
E_EVALUATE_BUSY_WITH_EVALUATION = -2147221456,
//
// Summary:
// The expression evaluation took too long.
E_EVALUATE_TIMEOUT = -2147221455,
//
// Summary:
// Mixed-mode debugging does not support Microsoft.NET Framework versions earlier
// than 2.0.
E_INTEROP_CLR_TOO_OLD = -2147221454,
//
// Summary:
// Check for one of the following. 1. The application you are trying to debug uses
// a version of the Microsoft .NET Framework that is not supported by the debugger.
// 2. The debugger has made an incorrect assumption about the Microsoft .NET Framework
// version your application is going to use. 3. The Microsoft .NET Framework version
// specified by you for debugging is incorrect. Please see the Visual Studio .NET
// debugger documentation for correctly specifying the Microsoft .NET Framework
// version your application is going to use for debugging.
E_CLR_INCOMPATIBLE_PROTOCOL = -2147221453,
//
// Summary:
// Unable to attach because process is running in fiber mode.
E_CLR_CANNOT_DEBUG_FIBER_PROCESS = -2147221452,
//
// Summary:
// Visual Studio has insufficient privileges to debug this process. To debug this
// process, Visual Studio must be run as an administrator.
E_PROCESS_OBJECT_ACCESS_DENIED = -2147221451,
//
// Summary:
// Visual Studio has insufficient privileges to inspect the process's identity.
E_PROCESS_TOKEN_ACCESS_DENIED = -2147221450,
//
// Summary:
// Visual Studio was unable to inspect the process's identity. This is most likely
// due to service configuration on the computer running the process.
E_PROCESS_TOKEN_ACCESS_DENIED_NO_TS = -2147221449,
E_OPERATION_REQUIRES_ELEVATION = -2147221448,
//
// Summary:
// Visual Studio has insufficient privileges to debug this process. To debug this
// process, Visual Studio must be run as an administrator.
E_ATTACH_REQUIRES_ELEVATION = -2147221447,
E_MEMORY_NOTSUPPORTED = -2147221440,
//
// Summary:
// The type of code you are currently debugging does not support disassembly.
E_DISASM_NOTSUPPORTED = -2147221439,
//
// Summary:
// The specified address does not exist in disassembly.
E_DISASM_BADADDRESS = -2147221438,
E_DISASM_NOTAVAILABLE = -2147221437,
//
// Summary:
// The breakpoint has been deleted.
E_BP_DELETED = -2147221408,
//
// Summary:
// The process has been terminated.
E_PROCESS_DESTROYED = -2147221392,
E_PROCESS_DEBUGGER_IS_DEBUGGEE = -2147221391,
//
// Summary:
// Terminating this process is not allowed.
E_TERMINATE_FORBIDDEN = -2147221390,
//
// Summary:
// The thread has terminated.
E_THREAD_DESTROYED = -2147221387,
//
// Summary:
// Cannot find port. Check the remote machine name.
E_PORTSUPPLIER_NO_PORT = -2147221376,
E_PORT_NO_REQUEST = -2147221360,
E_COMPARE_CANNOT_COMPARE = -2147221344,
E_JIT_INVALID_PID = -2147221327,
E_JIT_VSJITDEBUGGER_NOT_REGISTERED = -2147221325,
E_JIT_APPID_NOT_REGISTERED = -2147221324,
E_JIT_RUNTIME_VERSION_UNSUPPORTED = -2147221322,
E_SESSION_TERMINATE_DETACH_FAILED = -2147221310,
E_SESSION_TERMINATE_FAILED = -2147221309,
//
// Summary:
// Detach is not supported on Microsoft Windows 2000 for native code.
E_DETACH_NO_PROXY = -2147221296,
E_DETACH_TS_UNSUPPORTED = -2147221280,
E_DETACH_IMPERSONATE_FAILURE = -2147221264,
//
// Summary:
// This thread has called into a function that cannot be displayed.
E_CANNOT_SET_NEXT_STATEMENT_ON_NONLEAF_FRAME = -2147221248,
E_TARGET_FILE_MISMATCH = -2147221247,
E_IMAGE_NOT_LOADED = -2147221246,
E_FIBER_NOT_SUPPORTED = -2147221245,
//
// Summary:
// The next statement cannot be set to another function.
E_CANNOT_SETIP_TO_DIFFERENT_FUNCTION = -2147221244,
//
// Summary:
// In order to Set Next Statement, right-click on the active frame in the Call Stack
// window and select "Unwind To This Frame".
E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION = -2147221243,
//
// Summary:
// The next statement cannot be changed until the current statement has completed.
E_ENC_SETIP_REQUIRES_CONTINUE = -2147221241,
//
// Summary:
// The next statement cannot be set from outside a finally block to within it.
E_CANNOT_SET_NEXT_STATEMENT_INTO_FINALLY = -2147221240,
//
// Summary:
// The next statement cannot be set from within a finally block to a statement outside
// of it.
E_CANNOT_SET_NEXT_STATEMENT_OUT_OF_FINALLY = -2147221239,
//
// Summary:
// The next statement cannot be set from outside a catch block to within it.
E_CANNOT_SET_NEXT_STATEMENT_INTO_CATCH = -2147221238,
//
// Summary:
// The next statement cannot be changed at this time.
E_CANNOT_SET_NEXT_STATEMENT_GENERAL = -2147221237,
//
// Summary:
// The next statement cannot be set into or out of a catch filter.
E_CANNOT_SET_NEXT_STATEMENT_INTO_OR_OUT_OF_FILTER = -2147221236,
//
// Summary:
// This process is not currently executing the type of code that you selected to
// debug.
E_ASYNCBREAK_NO_PROGRAMS = -2147221232,
//
// Summary:
// The debugger is still attaching to the process or the process is not currently
// executing the type of code selected for debugging.
E_ASYNCBREAK_DEBUGGEE_NOT_INITIALIZED = -2147221231,
//
// Summary:
// The debugger is handling debug events or performing evaluations that do not allow
// nested break state. Try again.
E_ASYNCBREAK_UNABLE_TO_PROCESS = -2147221230,
//
// Summary:
// The web server has been locked down and is blocking the DEBUG verb, which is
// required to enable debugging. Please see Help for assistance.
E_WEBDBG_DEBUG_VERB_BLOCKED = -2147221215,
//
// Summary:
// ASP debugging is disabled because the ASP process is running as a user that does
// not have debug permissions. Please see Help for assistance.
E_ASP_USER_ACCESS_DENIED = -2147221211,
//
// Summary:
// The remote debugging components are not registered or running on the web server.
// Ensure the proper version of msvsmon is running on the remote computer.
E_AUTO_ATTACH_NOT_REGISTERED = -2147221210,
//
// Summary:
// An unexpected DCOM error occurred while trying to automatically attach to the
// remote web server. Try manually attaching to the remote web server using the
// 'Attach To Process' dialog.
E_AUTO_ATTACH_DCOM_ERROR = -2147221209,
//
// Summary:
// Expected failure from web server CoCreating debug verb CLSID
E_AUTO_ATTACH_COCREATE_FAILURE = -2147221208,
E_AUTO_ATTACH_CLASSNOTREG = -2147221207,
//
// Summary:
// The current thread cannot continue while an expression is being evaluated on
// another thread.
E_CANNOT_CONTINUE_DURING_PENDING_EXPR_EVAL = -2147221200,
E_REMOTE_REDIRECTION_UNSUPPORTED = -2147221195,
//
// Summary:
// The specified working directory does not exist or is not a full path.
E_INVALID_WORKING_DIRECTORY = -2147221194,
//
// Summary:
// The application manifest has the uiAccess attribute set to 'true'. Running an
// Accessibility application requires following the steps described in Help.
E_LAUNCH_FAILED_WITH_ELEVATION = -2147221193,
//
// Summary:
// This program requires additional permissions to start. To debug this program,
// restart Visual Studio as an administrator.
E_LAUNCH_ELEVATION_REQUIRED = -2147221192,
//
// Summary:
// Cannot locate Microsoft Internet Explorer.
E_CANNOT_FIND_INTERNET_EXPLORER = -2147221191,
//
// Summary:
// The Visual Studio Remote Debugger (MSVSMON.EXE) has insufficient privileges to
// debug this process. To debug this process, the remote debugger must be run as
// an administrator.
E_REMOTE_PROCESS_OBJECT_ACCESS_DENIED = -2147221190,
//
// Summary:
// The Visual Studio Remote Debugger (MSVSMON.EXE) has insufficient privileges to
// debug this process. To debug this process, launch the remote debugger using 'Run
// as administrator'. If the remote debugger has been configured to run as a service,
// ensure that it is running under an account that is a member of the Administrators
// group.
E_REMOTE_ATTACH_REQUIRES_ELEVATION = -2147221189,
//
// Summary:
// This program requires additional permissions to start. To debug this program,
// launch the Visual Studio Remote Debugger (MSVSMON.EXE) using 'Run as administrator'.
E_REMOTE_LAUNCH_ELEVATION_REQUIRED = -2147221188,
//
// Summary:
// The attempt to unwind the callstack failed. Unwinding is not possible in the
// following scenarios: 1. Debugging was started via Just-In-Time debugging. 2.
// An unwind is in progress. 3. A System.StackOverflowException or System.Threading.ThreadAbortException
// exception has been thrown.
E_EXCEPTION_CANNOT_BE_INTERCEPTED = -2147221184,
//
// Summary:
// You can only unwind to the function that caused the exception.
E_EXCEPTION_CANNOT_UNWIND_ABOVE_CALLBACK = -2147221183,
//
// Summary:
// Unwinding from the current exception is not supported.
E_INTERCEPT_CURRENT_EXCEPTION_NOT_SUPPORTED = -2147221182,
//
// Summary:
// You cannot unwind from an unhandled exception while doing managed and native
// code debugging at the same time.
E_INTERCEPT_CANNOT_UNWIND_LASTCHANCE_INTEROP = -2147221181,
E_JMC_CANNOT_SET_STATUS = -2147221179,
//
// Summary:
// The process has been terminated.
E_DESTROYED = -2147220991,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor is either not running on
// the remote machine or is running in Windows authentication mode.
E_REMOTE_NOMSVCMON = -2147220990,
//
// Summary:
// The IP address for the remote machine is not valid.
E_REMOTE_BADIPADDRESS = -2147220989,
//
// Summary:
// The remote machine is not responding.
E_REMOTE_MACHINEDOWN = -2147220988,
//
// Summary:
// The remote machine name is not specified.
E_REMOTE_MACHINEUNSPECIFIED = -2147220987,
//
// Summary:
// Other programs cannot be debugged during the current mixed dump debugging session.
E_CRASHDUMP_ACTIVE = -2147220986,
//
// Summary:
// All of the threads are frozen. Use the Threads window to unfreeze at least one
// thread before attempting to step or continue the process.
E_ALL_THREADS_SUSPENDED = -2147220985,
//
// Summary:
// The debugger transport DLL cannot be loaded.
E_LOAD_DLL_TL = -2147220984,
//
// Summary:
// mspdb110.dll cannot be loaded.
E_LOAD_DLL_SH = -2147220983,
//
// Summary:
// MSDIS170.dll cannot be loaded.
E_LOAD_DLL_EM = -2147220982,
//
// Summary:
// NatDbgEE.dll cannot be loaded.
E_LOAD_DLL_EE = -2147220981,
//
// Summary:
// NatDbgDM.dll cannot be loaded.
E_LOAD_DLL_DM = -2147220980,
//
// Summary:
// Old version of DBGHELP.DLL found, does not support minidumps.
E_LOAD_DLL_MD = -2147220979,
//
// Summary:
// Input or output cannot be redirected because the specified file is invalid.
E_IOREDIR_BADFILE = -2147220978,
//
// Summary:
// Input or output cannot be redirected because the syntax is incorrect.
E_IOREDIR_BADSYNTAX = -2147220977,
//
// Summary:
// The remote debugger is not an acceptable version.
E_REMOTE_BADVERSION = -2147220976,
//
// Summary:
// This operation is not supported when debugging dump files.
E_CRASHDUMP_UNSUPPORTED = -2147220975,
//
// Summary:
// The remote computer does not have a CLR version which is compatible with the
// remote debugging components. To install a compatible CLR version, see the instructions
// in the 'Remote Components Setup' page on the Visual Studio CD.
E_REMOTE_BAD_CLR_VERSION = -2147220974,
//
// Summary:
// The specified file is an unrecognized or unsupported binary format.
E_UNSUPPORTED_BINARY = -2147220971,
//
// Summary:
// The process has been soft broken.
E_DEBUGGEE_BLOCKED = -2147220970,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer is
// running as a different user.
E_REMOTE_NOUSERMSVCMON = -2147220969,
//
// Summary:
// Stepping to or from system code on a machine running Windows 95/Windows 98/Windows
// ME is not allowed.
E_STEP_WIN9xSYSCODE = -2147220968,
E_INTEROP_ORPC_INIT = -2147220967,
//
// Summary:
// The 64-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE)
// cannot be used to debug 32-bit processes or 32-bit dumps. Please use the 32-bit
// version instead.
E_CANNOT_DEBUG_WIN32 = -2147220965,
//
// Summary:
// The 32-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE)
// cannot be used to debug 64-bit processes or 64-bit dumps. Please use the 64-bit
// version instead.
E_CANNOT_DEBUG_WIN64 = -2147220964,
//
// Summary:
// Mini-Dumps cannot be read on this system. Please use a Windows NT based system
E_MINIDUMP_READ_WIN9X = -2147220963,
//
// Summary:
// Attaching to a process in a different terminal server session is not supported
// on this computer. Try remote debugging to the machine and running the Microsoft
// Visual Studio Remote Debugging Monitor in the process's session.
E_CROSS_TSSESSION_ATTACH = -2147220962,
//
// Summary:
// A stepping breakpoint could not be set
E_STEP_BP_SET_FAILED = -2147220961,
//
// Summary:
// The debugger transport DLL being loaded has an incorrect version.
E_LOAD_DLL_TL_INCORRECT_VERSION = -2147220960,
//
// Summary:
// NatDbgDM.dll being loaded has an incorrect version.
E_LOAD_DLL_DM_INCORRECT_VERSION = -2147220959,
E_REMOTE_NOMSVCMON_PIPE = -2147220958,
//
// Summary:
// msdia120.dll cannot be loaded.
E_LOAD_DLL_DIA = -2147220957,
//
// Summary:
// The dump file you opened is corrupted.
E_DUMP_CORRUPTED = -2147220956,
//
// Summary:
// Mixed-mode debugging of x64 processes is not supported when using Microsoft.NET
// Framework versions earlier than 4.0.
E_INTEROP_X64 = -2147220955,
//
// Summary:
// Debugging older format crashdumps is not supported.
E_CRASHDUMP_DEPRECATED = -2147220953,
//
// Summary:
// Debugging managed-only minidumps is not supported. Specify 'Mixed' for the 'Debugger
// Type' in project properties.
E_LAUNCH_MANAGEDONLYMINIDUMP_UNSUPPORTED = -2147220952,
//
// Summary:
// Debugging managed or mixed-mode minidumps is not supported on IA64 platforms.
// Specify 'Native' for the 'Debugger Type' in project properties.
E_LAUNCH_64BIT_MANAGEDMINIDUMP_UNSUPPORTED = -2147220951,
//
// Summary:
// The remote tools are not signed correctly.
E_DEVICEBITS_NOT_SIGNED = -2147220479,
//
// Summary:
// Attach is not enabled for this process with this debug type.
E_ATTACH_NOT_ENABLED = -2147220478,
//
// Summary:
// The connection has been broken.
E_REMOTE_DISCONNECT = -2147220477,
//
// Summary:
// The threads in the process cannot be suspended at this time. This may be a temporary
// condition.
E_BREAK_ALL_FAILED = -2147220476,
//
// Summary:
// Access denied. Try again, then check your device for a prompt.
E_DEVICE_ACCESS_DENIED_SELECT_YES = -2147220475,
//
// Summary:
// Unable to complete the operation. This could be because the device's security
// settings are too restrictive. Please use the Device Security Manager to change
// the settings and try again.
E_DEVICE_ACCESS_DENIED = -2147220474,
//
// Summary:
// The remote connection to the device has been lost. Verify the device connection
// and restart debugging.
E_DEVICE_CONNRESET = -2147220473,
//
// Summary:
// Unable to load the CLR. The target device does not have a compatible version
// of the CLR installed for the application you are attempting to debug. Verify
// that your device supports the appropriate CLR version and has that CLR installed.
// Some devices do not support automatic CLR upgrade.
E_BAD_NETCF_VERSION = -2147220472,
E_REFERENCE_NOT_VALID = -2147220223,
E_PROPERTY_NOT_VALID = -2147220207,
E_SETVALUE_VALUE_CANNOT_BE_SET = -2147220191,
E_SETVALUE_VALUE_IS_READONLY = -2147220190,
E_SETVALUEASREFERENCE_NOTSUPPORTED = -2147220189,
E_CANNOT_GET_UNMANAGED_MEMORY_CONTEXT = -2147220127,
E_GETREFERENCE_NO_REFERENCE = -2147220095,
E_CODE_CONTEXT_OUT_OF_SCOPE = -2147220063,
E_INVALID_SESSIONID = -2147220062,
//
// Summary:
// The Visual Studio Remote Debugger on the target computer cannot connect back
// to this computer. A firewall may be preventing communication via DCOM to the
// local computer. It may be possible to avoid this error by changing your settings
// to debug only native code or only managed code.
E_SERVER_UNAVAILABLE_ON_CALLBACK = -2147220061,
//
// Summary:
// The Visual Studio Remote Debugger on the target computer cannot connect back
// to this computer. Authentication failed. It may be possible to avoid this error
// by changing your settings to debug only native code or only managed code.
E_ACCESS_DENIED_ON_CALLBACK = -2147220060,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer could
// not connect to this computer because there was no available authentication service.
// It may be possible to avoid this error by changing your settings to debug only
// native code or only managed code.
E_UNKNOWN_AUTHN_SERVICE_ON_CALLBACK = -2147220059,
E_NO_SESSION_AVAILABLE = -2147220058,
E_CLIENT_NOT_LOGGED_ON = -2147220057,
E_OTHER_USERS_SESSION = -2147220056,
E_USER_LEVEL_ACCESS_CONTROL_REQUIRED = -2147220055,
//
// Summary:
// Can not evaluate script expressions while thread is stopped in the CLR.
E_SCRIPT_CLR_EE_DISABLED = -2147220048,
//
// Summary:
// Server side-error occurred on sending debug HTTP request.
E_HTTP_SERVERERROR = -2147219712,
//
// Summary:
// An authentication error occurred while communicating with the web server. Please
// see Help for assistance.
E_HTTP_UNAUTHORIZED = -2147219711,
//
// Summary:
// Could not start ASP.NET debugging. More information may be available by starting
// the project without debugging.
E_HTTP_SENDREQUEST_FAILED = -2147219710,
//
// Summary:
// The web server is not configured correctly. See help for common configuration
// errors. Running the web page outside of the debugger may provide further information.
E_HTTP_FORBIDDEN = -2147219709,
//
// Summary:
// The server does not support debugging of ASP.NET or ATL Server applications.
// Click Help for more information on how to enable debugging.
E_HTTP_NOT_SUPPORTED = -2147219708,
//
// Summary:
// Could not start ASP.NET or ATL Server debugging.
E_HTTP_NO_CONTENT = -2147219707,
//
// Summary:
// The web server could not find the requested resource.
E_HTTP_NOT_FOUND = -2147219706,
//
// Summary:
// The debug request could not be processed by the server due to invalid syntax.
E_HTTP_BAD_REQUEST = -2147219705,
//
// Summary:
// You do not have permissions to debug the web server process. You need to either
// be running as the same user account as the web server, or have administrator
// privilege.
E_HTTP_ACCESS_DENIED = -2147219704,
//
// Summary:
// Unable to connect to the web server. Verify that the web server is running and
// that incoming HTTP requests are not blocked by a firewall.
E_HTTP_CONNECT_FAILED = -2147219703,
E_HTTP_EXCEPTION = -2147219702,
//
// Summary:
// The web server did not respond in a timely manner. This may be because another
// debugger is already attached to the web server.
E_HTTP_TIMEOUT = -2147219701,
//
// Summary:
// IIS does not list a web site that matches the launched URL.
E_HTTP_SITE_NOT_FOUND = -2147219700,
//
// Summary:
// IIS does not list an application that matches the launched URL.
E_HTTP_APP_NOT_FOUND = -2147219699,
//
// Summary:
// Debugging requires the IIS Management Console. To install, go to Control Panel->Programs->Turn
// Windows features on or off. Check Internet Information Services->Web Management
// Tools->IIS Management Console.
E_HTTP_MANAGEMENT_API_MISSING = -2147219698,
//
// Summary:
// The IIS worker process for the launched URL is not currently running.
E_HTTP_NO_PROCESS = -2147219697,
E_64BIT_COMPONENTS_NOT_INSTALLED = -2147219632,
//
// Summary:
// The Visual Studio debugger cannot connect to the remote computer. Unable to initiate
// DCOM communication. Please see Help for assistance.
E_UNMARSHAL_SERVER_FAILED = -2147219631,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor on the remote computer cannot
// connect to the local computer. Unable to initiate DCOM communication. Please
// see Help for assistance.
E_UNMARSHAL_CALLBACK_FAILED = -2147219630,
//
// Summary:
// The Visual Studio debugger cannot connect to the remote computer. An RPC policy
// is enabled on the local computer which prevents remote debugging. Please see
// Help for assistance.
E_RPC_REQUIRES_AUTHENTICATION = -2147219627,
//
// Summary:
// The Microsoft Visual Studio Remote Debugging Monitor cannot logon to the local
// computer: unknown user name or bad password. It may be possible to avoid this
// error by changing your settings to debug only native code or only managed code.
E_LOGON_FAILURE_ON_CALLBACK = -2147219626,
//
// Summary:
// The Visual Studio debugger cannot establish a DCOM connection to the remote computer.
// A firewall may be preventing communication via DCOM to the remote computer. It
// may be possible to avoid this error by changing your settings to debug only native
// code or only managed code.
E_REMOTE_SERVER_UNAVAILABLE = -2147219625,
E_REMOTE_CONNECT_USER_CANCELED = -2147219624,
//
// Summary:
// Windows file sharing has been configured so that you will connect to the remote
// computer using a different user name. This is incompatible with remote debugging.
// Please see Help for assistance.
E_REMOTE_CREDENTIALS_PROHIBITED = -2147219623,
//
// Summary:
// Windows Firewall does not currently allow exceptions. Use Control Panel to change
// the Windows Firewall settings so that exceptions are allowed.
E_FIREWALL_NO_EXCEPTIONS = -2147219622,
//
// Summary:
// Cannot add an application to the Windows Firewall exception list. Use the Control
// Panel to manually configure the Windows Firewall.
E_FIREWALL_CANNOT_OPEN_APPLICATION = -2147219621,
//
// Summary:
// Cannot add a port to the Windows Firewall exception list. Use the Control Panel
// to manually configure the Windows Firewall.
E_FIREWALL_CANNOT_OPEN_PORT = -2147219620,
//
// Summary:
// Cannot add 'File and Printer Sharing' to the Windows Firewall exception list.
// Use the Control Panel to manually configure the Windows Firewall.
E_FIREWALL_CANNOT_OPEN_FILE_SHARING = -2147219619,
//
// Summary:
// Remote debugging is not supported.
E_REMOTE_DEBUGGING_UNSUPPORTED = -2147219618,
E_REMOTE_BAD_MSDBG2 = -2147219617,
E_ATTACH_USER_CANCELED = -2147219616,
//
// Summary:
// Maximum packet length exceeded. If the problem continues, reduce the number of
// network host names or network addresses that are assigned to the computer running
// Visual Studio computer or to the target computer.
E_REMOTE_PACKET_TOO_BIG = -2147219615,
//
// Summary:
// The target process is running a version of the Microsoft .NET Framework newer
// than this version of Visual Studio. Visual Studio cannot debug this process.
E_UNSUPPORTED_FUTURE_CLR_VERSION = -2147219614,
//
// Summary:
// This version of Visual Studio does not support debugging code that uses Microsoft
// .NET Framework v1.0. Use Visual Studio 2008 or earlier to debug this process.
E_UNSUPPORTED_CLR_V1 = -2147219613,
//
// Summary:
// Mixed-mode debugging of IA64 processes is not supported.
E_INTEROP_IA64 = -2147219612,
//
// Summary:
// See help for common configuration errors. Running the web page outside of the
// debugger may provide further information.
E_HTTP_GENERAL = -2147219611,
//
// Summary:
// IDebugCoreServer* implementation does not have a connection to the remote computer.
// This can occur in T-SQL debugging when there is no remote debugging monitor.
E_REMOTE_NO_CONNECTION = -2147219610,
//
// Summary:
// The specified remote debugging proxy server name is invalid.
E_REMOTE_INVALID_PROXY_SERVER_NAME = -2147219609,
//
// Summary:
// Operation is not permitted on IDebugCoreServer* implementation which has a weak
// connection to the remote msvsmon instance. Weak connections are used when no
// process is being debugged.
E_REMOTE_WEAK_CONNECTION = -2147219608,
//
// Summary:
// Remote program providers are no longer supported before debugging begins (ex:
// process enumeration).
E_REMOTE_PROGRAM_PROVIDERS_UNSUPPORTED = -2147219607,
//
// Summary:
// Connection request was rejected by the remote debugger. Ensure that the remote
// debugger is running in 'No Authentication' mode.
E_REMOTE_REJECTED_NO_AUTH_REQUEST = -2147219606,
//
// Summary:
// Connection request was rejected by the remote debugger. Ensure that the remote
// debugger is running in 'Windows Authentication' mode.
E_REMOTE_REJECTED_WIN_AUTH_REQUEST = -2147219605,
//
// Summary:
// The debugger was unable to create a localhost TCP/IP connection, which is required
// for 64-bit debugging.
E_PSEUDOREMOTE_NO_LOCALHOST_TCPIP_CONNECTION = -2147219604,
//
// Summary:
// This operation requires the Windows Web Services API to be installed, and it
// is not currently installed on this computer.
E_REMOTE_WWS_NOT_INSTALLED = -2147219603,
//
// Summary:
// This operation requires the Windows Web Services API to be installed, and it
// is not currently installed on this computer. To install Windows Web Services,
// please restart Visual Studio as an administrator on this computer.
E_REMOTE_WWS_INSTALL_REQUIRES_ADMIN = -2147219602,
//
// Summary:
// The expression has not yet been translated to native machine code.
E_FUNCTION_NOT_JITTED = -2147219456,
E_NO_CODE_CONTEXT = -2147219455,
//
// Summary:
// A Microsoft .NET Framework component, diasymreader.dll, is not correctly installed.
// Please repair your Microsoft .NET Framework installation via 'Add or Remove Programs'
// in Control Panel.
E_BAD_CLR_DIASYMREADER = -2147219454,
//
// Summary:
// Unable to load the CLR. If a CLR version was specified for debugging, check that
// it was valid and installed on the machine. If the problem persists, please repair
// your Microsoft .NET Framework installation via 'Programs and Features' in Control
// Panel.
E_CLR_SHIM_ERROR = -2147219453,
//
// Summary:
// Unable to map the debug start page URL to a machine name.
E_AUTOATTACH_WEBSERVER_NOT_FOUND = -2147219199,
E_DBGEXTENSION_NOT_FOUND = -2147219184,
E_DBGEXTENSION_FUNCTION_NOT_FOUND = -2147219183,
E_DBGEXTENSION_FAULTED = -2147219182,
E_DBGEXTENSION_RESULT_INVALID = -2147219181,
E_PROGRAM_IN_RUNMODE = -2147219180,
//
// Summary:
// The remote procedure could not be debugged. This usually indicates that debugging
// has not been enabled on the server. See help for more information.
E_CAUSALITY_NO_SERVER_RESPONSE = -2147219168,
//
// Summary:
// Please install the Visual Studio Remote Debugger on the server to enable this
// functionality.
E_CAUSALITY_REMOTE_NOT_REGISTERED = -2147219167,
//
// Summary:
// The debugger failed to stop in the server process.
E_CAUSALITY_BREAKPOINT_NOT_HIT = -2147219166,
//
// Summary:
// Unable to determine a stopping location. Verify symbols are loaded.
E_CAUSALITY_BREAKPOINT_BIND_ERROR = -2147219165,
//
// Summary:
// Debugging this project is disabled. Debugging can be re-enabled from 'Start Options'
// under project properties.
E_CAUSALITY_PROJECT_DISABLED = -2147219164,
//
// Summary:
// Unable to attach the debugger to TSQL code.
E_NO_ATTACH_WHILE_DDD = -2147218944,
//
// Summary:
// Click Help for more information.
E_SQLLE_ACCESSDENIED = -2147218943,
//
// Summary:
// Click Help for more information.
E_SQL_SP_ENABLE_PERMISSION_DENIED = -2147218942,
//
// Summary:
// Click Help for more information.
E_SQL_DEBUGGING_NOT_ENABLED_ON_SERVER = -2147218941,
//
// Summary:
// Click Help for more information.
E_SQL_CANT_FIND_SSDEBUGPS_ON_CLIENT = -2147218940,
//
// Summary:
// Click Help for more information.
E_SQL_EXECUTED_BUT_NOT_DEBUGGED = -2147218939,
//
// Summary:
// Click Help for more information.
E_SQL_VDT_INIT_RETURNED_SQL_ERROR = -2147218938,
E_ATTACH_FAILED_ABORT_SILENTLY = -2147218937,
//
// Summary:
// Click Help for more information.
E_SQL_REGISTER_FAILED = -2147218936,
E_DE_NOT_SUPPORTED_PRE_8_0 = -2147218688,
E_PROGRAM_DESTROY_PENDING = -2147218687,
//
// Summary:
// The operation isn't supported for the Common Language Runtime version used by
// the process being debugged.
E_MANAGED_FEATURE_NOTSUPPORTED = -2147218515,
//
// Summary:
// The Visual Studio Remote Debugger does not support this edition of Windows.
E_OS_PERSONAL = -2147218432,
//
// Summary:
// Source server support is disabled because the assembly is partially trusted.
E_SOURCE_SERVER_DISABLE_PARTIAL_TRUST = -2147218431,
//
// Summary:
// Operation is not supported on the platform of the target computer/device.
E_REMOTE_UNSUPPORTED_OPERATION_ON_PLATFORM = -2147218430,
//
// Summary:
// Unable to load Visual Studio debugger component (vsdebugeng.dll). If this problem
// persists, repair your installation via 'Add or Remove Programs' in Control Panel.
E_LOAD_VSDEBUGENG_FAILED = -2147218416,
//
// Summary:
// Unable to initialize Visual Studio debugger component (vsdebugeng.dll). If this
// problem persists, repair your installation via 'Add or Remove Programs' in Control
// Panel.
E_LOAD_VSDEBUGENG_IMPORTS_FAILED = -2147218415,
//
// Summary:
// Unable to initialize Visual Studio debugger due to a configuration error. If
// this problem persists, repair your installation via 'Add or Remove Programs'
// in Control Panel.
E_LOAD_VSDEBUGENG_CONFIG_ERROR = -2147218414,
//
// Summary:
// Failed to launch minidump. The minidump file is corrupt.
E_CORRUPT_MINIDUMP = -2147218413,
//
// Summary:
// Unable to load a Visual Studio component (VSDebugScriptAgent110.dll). If the
// problem persists, repair your installation via 'Add or Remove Programs' in Control
// Panel.
E_LOAD_SCRIPT_AGENT_LOCAL_FAILURE = -2147218412,
//
// Summary:
// Remote script debugging requires that the remote debugger is registered on the
// target computer. Run the Visual Studio Remote Debugger setup (rdbgsetup_<processor>.exe)
// on the target computer.
E_LOAD_SCRIPT_AGENT_REMOTE_FAILURE = -2147218410,
//
// Summary:
// The debugger was unable to find the registration for the target application.
// If the problem persists, try uninstalling and then reinstalling this application.
E_APPX_REGISTRATION_NOT_FOUND = -2147218409,
//
// Summary:
// Unable to find a Visual Studio component (VsDebugLaunchNotify.exe). For remote
// debugging, this file must be present on the target computer. If the problem persists,
// repair your installation via 'Add or Remove Programs' in Control Panel.
E_VSDEBUGLAUNCHNOTIFY_NOT_INSTALLED = -2147218408,
//
// Summary:
// Windows 8 build# 8017 or higher is required to debug Windows Store apps.
E_WIN8_TOO_OLD = -2147218404,
E_THREAD_NOT_FOUND = -2147218175,
//
// Summary:
// Cannot auto-attach to the SQL Server, possibly because the firewall is configured
// incorrectly or auto-attach is forbidden by the operating system.
E_CANNOT_AUTOATTACH_TO_SQLSERVER = -2147218174,
E_OBJECT_OUT_OF_SYNC = -2147218173,
E_PROCESS_ALREADY_CONTINUED = -2147218172,
//
// Summary:
// Debugging multiple GPU processes is not supported.
E_CANNOT_DEBUG_MULTI_GPU_PROCS = -2147218171,
//
// Summary:
// No available devices supported by the selected debug engine. Please select a
// different engine.
E_GPU_ADAPTOR_NOT_FOUND = -2147218170,
//
// Summary:
// A Microsoft Windows component is not correctly registered. Please ensure that
// the Desktop Experience is enabled in Server Manager -> Manage -> Add Server Roles
// and Features.
E_WINDOWS_GRAPHICAL_SHELL_UNINSTALLED_ERROR = -2147218169,
//
// Summary:
// Windows 8 or higher was required for GPU debugging on the software emulator.
// For the most up-to-date information, please visit the link below. http://go.microsoft.com/fwlink/p/?LinkId=330081
E_GPU_DEBUG_NOT_SUPPORTED_PRE_DX_11_1 = -2147218168,
//
// Summary:
// There is a configuration issue with the selected Debugging Accelerator Type.
// For information on specific Accelerator providers, visit http://go.microsoft.com/fwlink/p/?LinkId=323500
E_GPU_DEBUG_CONFIG_ISSUE = -2147218167,
//
// Summary:
// Local debugging is not supported for the selected Debugging Accelerator Type.
// Use Remote Windows Debugger instead or change the Debugging Accelerator Type
E_GPU_LOCAL_DEBUGGING_ERROR = -2147218166,
//
// Summary:
// The debug driver for the selected Debugging Accelerator Type is not installed
// on the target machine. For more information, visit http://go.microsoft.com/fwlink/p/?LinkId=323500
E_GPU_LOAD_VSD3D_FAILURE = -2147218165,
//
// Summary:
// Timeout Detection and Recovery (TDR) must be disabled at the remote site. For
// more information search for 'TdrLevel' in MSDN or visit the link below. http://go.microsoft.com/fwlink/p/?LinkId=323500
E_GPU_TDR_ENABLED_FAILURE = -2147218164,
//
// Summary:
// Remote debugger does not support mixed (managed and native) debugger type.
E_CANNOT_REMOTE_DEBUG_MIXED = -2147218163,
//
// Summary:
// Background Task activation failed Please see Help for further information.
E_BG_TASK_ACTIVATION_FAILED = -2147218162,
//
// Summary:
// This version of the Visual Studio Remote Debugger does not support this operation.
// Please upgrade to the latest version. http://go.microsoft.com/fwlink/p/?LinkId=219549
E_REMOTE_VERSION = -2147218161,
//
// Summary:
// Unable to load a Visual Studio component (symbollocator.resources.dll). If the
// problem persists, repair your installation via 'Add or Remove Programs' in Control
// Panel.
E_SYMBOL_LOCATOR_INSTALL_ERROR = -2147218160,
//
// Summary:
// The format of the PE module is invalid.
E_INVALID_PE_FORMAT = -2147218159,
//
// Summary:
// This dump is already being debugged.
E_DUMP_ALREADY_LAUNCHED = -2147218158,
//
// Summary:
// The next statement cannot be set because the current assembly is optimized.
E_CANNOT_SET_NEXT_STATEMENT_IN_OPTIMIZED_CODE = -2147218157,
//
// Summary:
// Debugging of ARM minidumps requires Windows 8 or above.
E_ARMDUMP_NOT_SUPPORTED_PRE_WIN8 = -2147218156,
//
// Summary:
// Cannot detach while process termination is in progress.
E_CANNOT_DETACH_WHILE_TERMINATE_IN_PROGRESS = -2147218155,
//
// Summary:
// A required Microsoft Windows component, wldp.dll could not be found on the target
// device.
E_WLDP_NOT_FOUND = -2147218154,
//
// Summary:
// The target device does not allow debugging this process.
E_DEBUGGING_BLOCKED_ON_TARGET = -2147218153,
//
// Summary:
// Unable to debug .NET Native code. Install the Microsoft .NET Native Developer
// SDK. Alternatively debug with native code type.
E_DOTNETNATIVE_SDK_NOT_INSTALLED = -2147218152,
//
// Summary:
// The operation was canceled.
COR_E_OPERATIONCANCELED = -2146233029,
//
// Summary:
// A component dll failed to load. Try to restart this application. If failures
// continue, try disabling any installed add-ins or repair your installation.
E_XAPI_COMPONENT_LOAD_FAILURE = -1898053632,
//
// Summary:
// Xapi has not been initialized on this thread. Call ComponentManager.InitializeThread.
E_XAPI_NOT_INITIALIZED = -1898053631,
//
// Summary:
// Xapi has already been initialized on this thread.
E_XAPI_ALREADY_INITIALIZED = -1898053630,
//
// Summary:
// Xapi event thread aborted unexpectedly.
E_XAPI_THREAD_ABORTED = -1898053629,
//
// Summary:
// Component failed a call to QueryInterface. QueryInterface implementation or component
// configuration is incorrect.
E_XAPI_BAD_QUERY_INTERFACE = -1898053628,
//
// Summary:
// Object requested which is not available at the caller's component level.
E_XAPI_UNAVAILABLE_OBJECT = -1898053627,
//
// Summary:
// Failed to process configuration file. Try to restart this application. If failures
// continue, try to repair your installation.
E_XAPI_BAD_CONFIG = -1898053626,
//
// Summary:
// Failed to initialize managed/native marshalling system. Try to restart this application.
// If failures continue, try to repair your installation.
E_XAPI_MANAGED_DISPATCHER_CONNECT_FAILURE = -1898053625,
//
// Summary:
// This operation may only be preformed while processing the object's 'Create' event.
E_XAPI_DURING_CREATE_EVENT_REQUIRED = -1898053624,
//
// Summary:
// This operation may only be preformed by the component which created the object.
E_XAPI_CREATOR_REQUIRED = -1898053623,
//
// Summary:
// The work item cannot be appended to the work list because it is already complete.
E_XAPI_WORK_LIST_COMPLETE = -1898053622,
//
// Summary:
// 'Execute' may not be called on a work list which has already started.
E_XAPI_WORKLIST_ALREADY_STARTED = -1898053621,
//
// Summary:
// The interface implementation released the completion routine without calling
// it.
E_XAPI_COMPLETION_ROUTINE_RELEASED = -1898053620,
//
// Summary:
// Operation is not supported on this thread.
E_XAPI_WRONG_THREAD = -1898053619,
//
// Summary:
// No component with the given component id could be found in the configuration
// store.
E_XAPI_COMPONENTID_NOT_FOUND = -1898053618,
//
// Summary:
// Call was attempted to a remote connection from a server-side component (component
// level > 100000). This is not allowed.
E_XAPI_WRONG_CONNECTION_OBJECT = -1898053617,
//
// Summary:
// Destination of this call is on a remote connection and this method doesn't support
// remoting.
E_XAPI_METHOD_NOT_REMOTED = -1898053616,
//
// Summary:
// The network connection to the Visual Studio Remote Debugger was lost.
E_XAPI_REMOTE_DISCONNECTED = -1898053615,
//
// Summary:
// The network connection to the Visual Studio Remote Debugger has been closed.
E_XAPI_REMOTE_CLOSED = -1898053614,
//
// Summary:
// A protocol compatibility error occurred between Visual Studio and the Remote
// Debugger. Please ensure that the Visual Studio and Remote debugger versions match.
E_XAPI_INCOMPATIBLE_PROTOCOL = -1898053613,
//
// Summary:
// Maximum allocation size exceeded while processing a remoting message.
E_XAPI_MAX_PACKET_EXCEEDED = -1898053612,
//
// Summary:
// An object already exists with the same key value.
E_XAPI_OBJECT_ALREADY_EXISTS = -1898053611,
//
// Summary:
// An object cannot be found with the given key value.
E_XAPI_OBJECT_NOT_FOUND = -1898053610,
//
// Summary:
// A data item already exists with the same key value.
E_XAPI_DATA_ITEM_ALREADY_EXISTS = -1898053609,
//
// Summary:
// A data item cannot be for this component found with the given data item ID.
E_XAPI_DATA_ITEM_NOT_FOUND = -1898053608,
//
// Summary:
// Interface implementation failed to provide a required out param.
E_XAPI_NULL_OUT_PARAM = -1898053607,
//
// Summary:
// Strong name signature validation error while trying to load the managed dispatcher
E_XAPI_MANAGED_DISPATCHER_SIGNATURE_ERROR = -1898053600,
//
// Summary:
// Method may only be called by components which load in the IDE process (component
// level > 100000).
E_XAPI_CLIENT_ONLY_METHOD = -1898053599,
//
// Summary:
// Method may only be called by components which load in the remote debugger process
// (component level < 100000).
E_XAPI_SERVER_ONLY_METHOD = -1898053598,
//
// Summary:
// A component dll could not be found. If failures continue, try disabling any installed
// add-ins or repairing your installation.
E_XAPI_COMPONENT_DLL_NOT_FOUND = -1898053597,
//
// Summary:
// Operation requires the remote debugger be updated to a newer version.
E_XAPI_REMOTE_NEW_VER_REQUIRED = -1898053596,
//
// Summary:
// Symbols are not loaded for the target dll.
E_SYMBOLS_NOT_LOADED = -1842151424,
//
// Summary:
// Symbols for the target dll do not contain source information.
E_SYMBOLS_STRIPPED = -1842151423,
//
// Summary:
// Breakpoint could not be written at the specified instruction address.
E_BP_INVALID_ADDRESS = -1842151422,
//
// Summary:
// Breakpoints cannot be set in optimized code when the debugger option 'Just My
// Code' is enabled.
E_BP_IN_OPTIMIZED_CODE = -1842151420,
//
// Summary:
// The Common Language Runtime was unable to set the breakpoint.
E_BP_CLR_ERROR = -1842151418,
//
// Summary:
// Cannot set breakpoints in .NET Framework methods which are implemented in native
// code (ex: 'extern' function).
E_BP_CLR_EXTERN_FUNCTION = -1842151417,
//
// Summary:
// Cannot set breakpoint, target module is currently unloaded.
E_BP_MODULE_UNLOADED = -1842151416,
//
// Summary:
// Stopping events cannot be sent. See stopping event processing documentation for
// more information.
E_STOPPING_EVENT_REJECTED = -1842151415,
//
// Summary:
// This operation is not permitted because the target process is already stopped.
E_TARGET_ALREADY_STOPPED = -1842151414,
//
// Summary:
// This operation is not permitted because the target process is not stopped.
E_TARGET_NOT_STOPPED = -1842151413,
//
// Summary:
// This operation is not allowed on this thread.
E_WRONG_THREAD = -1842151412,
//
// Summary:
// This operation is not allowed at this time.
E_WRONG_TIME = -1842151411,
//
// Summary:
// The caller is not allowed to request this operation. This operation must be requested
// by a different component.
E_WRONG_COMPONENT = -1842151410,
//
// Summary:
// Operation is only permitted on the latest version of an edited method.
E_WRONG_METHOD_VERSION = -1842151409,
//
// Summary:
// A memory read or write operation failed because the specified memory address
// is not currently valid.
E_INVALID_MEMORY_ADDRESS = -1842151408,
//
// Summary:
// No source information is available for this instruction.
E_INSTRUCTION_NO_SOURCE = -1842151407,
//
// Summary:
// Failed to load localizable resource from vsdebugeng.impl.resources.dll. If this
// problem persists, please repair your Visual Studio installation via 'Add or Remove
// Programs' in Control Panel.
E_VSDEBUGENG_RESOURCE_LOAD_FAILURE = -1842151406,
//
// Summary:
// DkmVariant is of a form that marshalling is not supported. Marshalling is supported
// for primitives types, strings, and safe arrays of primitives.
E_UNMARSHALLABLE_VARIANT = -1842151405,
//
// Summary:
// An incorrect version of vsdebugeng.dll was loaded into Visual Studio. Please
// repair your Visual Studio installation.
E_VSDEBUGENG_DEPLOYMENT_ERROR = -1842151404,
//
// Summary:
// The remote debugger was unable to initialize Microsoft Windows Web Services (webservices.dll).
// If the problem continues, try reinstalling the Windows Web Services redistributable.
// This redistributable can be found under the 'Remote Debugger\Common Resources\Windows
// Updates' folder.
E_WEBSERVICES_LOAD_FAILURE = -1842151403,
//
// Summary:
// Visual Studio encountered an error while loading a Windows component (Global
// Interface Table). If the problem persists, this may be an indication of operating
// system corruption, and Windows may need to be reinstalled.
E_GLOBAL_INTERFACE_POINTER_FAILURE = -1842151402,
//
// Summary:
// Windows authentication was unable to establish a secure connection to the remote
// computer.
E_REMOTE_AUTHENTICATION_ERROR = -1842151401,
//
// Summary:
// The Remote Debugger was unable to locate a resource dll (vsdebugeng.impl.resources.dll).
// Please ensure that the complete remote debugger folder was copied or installed
// on the target computer.
E_CANNOT_FIND_REMOTE_RESOURCES = -1842151400,
//
// Summary:
// The hardware does not support monitoring the requested number of bytes.
E_INVALID_DATABP_SIZE = -1842151392,
//
// Summary:
// The maximum number of data breakpoints have already been set.
E_INVALID_DATABP_ALLREGSUSED = -1842151391,
//
// Summary:
// Breakpoints cannot be set while debugging a minidump.
E_DUMPS_DO_NOT_SUPPORT_BREAKPOINTS = -1842151390,
//
// Summary:
// The minidump is from an ARM-based computer and can only be debugged on an ARM
// computer.
E_DUMP_ARM_ARCHITECTURE = -1842151389,
//
// Summary:
// The minidump is from an unknown processor, and cannot be debugged with this version
// of Visual Studio.
E_DUMP_UNKNOWN_ARCHITECTURE = -1842151388,
//
// Summary:
// The shell failed to find a checksum for this file.
E_NO_CHECKSUM = -1842151387,
//
// Summary:
// On x64, context control must be included in a SetThreadContext
E_CONTEXT_CONTROL_REQUIRED = -1842151386,
//
// Summary:
// The size of the buffer does not match the size of the register.
E_INVALID_REGISTER_SIZE = -1842151385,
//
// Summary:
// The requested register was not found in the stack frame's unwound register collection.
E_REGISTER_NOT_FOUND = -1842151384,
//
// Summary:
// Cannot set a read-only register.
E_REGISTER_READONLY = -1842151383,
//
// Summary:
// Cannot set a register in a frame that is not the top of the stack.
E_REG_NOT_TOP_STACK = -1842151376,
//
// Summary:
// String could not be read within the specified maximum number of characters.
E_STRING_TOO_LONG = -1842151375,
//
// Summary:
// The memory region does not meet the requested protection flags.
E_INVALID_MEMORY_PROTECT = -1842151374,
//
// Summary:
// Instruction is invalid or unknown to the disassembler.
E_UNKNOWN_CPU_INSTRUCTION = -1842151373,
//
// Summary:
// An invalid runtime was specified for this operation.
E_INVALID_RUNTIME = -1842151372,
//
// Summary:
// Variable is optimized away.
E_VARIABLE_OPTIMIZED_AWAY = -1842151371,
//
// Summary:
// The text span is not currently loaded in the specified script document.
E_TEXT_SPAN_NOT_LOADED = -1842151370,
//
// Summary:
// This location could not be mapped to client side script.
E_SCRIPT_SPAN_MAPPING_FAILED = -1842151369,
//
// Summary:
// The file requested must be less than 100 megabytes in size
E_DEPLOY_FILE_TOO_LARGE = -1842151368,
//
// Summary:
// The file path requested could not be written to as it is invalid. Ensure the
// path does not contain a file where a directory is expected.
E_DEPLOY_FILE_PATH_INVALID = -1842151367,
//
// Summary:
// Script debugging is not enabled for WWAHost.exe.
E_SCRIPT_DEBUGGING_DISABLED_WWAHOST_ATTACH_FAILED = -1842151360,
//
// Summary:
// The file path requested for deletion does not exist.
E_DEPLOY_FILE_NOT_EXIST = -1842151359,
//
// Summary:
// A command is already executing, only one may execute at a time. Please wait for
// the executable to exit, or abort the command.
E_EXECUTE_COMMAND_IN_PROGRESS = -1842151358,
//
// Summary:
// The specified file path is a relative or unknown path format. File paths must
// be fully qualified.
E_INVALID_FULL_PATH = -1842151357,
//
// Summary:
// Windows Store app debugging is not possible when the remote debugger is running
// as a service. Run the Remote Debugger Configuration Wizard on the target computer,
// and uncheck the option to start the remote debugger service. Then start the Visual
// Studio Remote Debugging Monitor application.
E_CANNOT_DEBUG_APP_PACKAGE_IN_RDBSERVICE = -1842151356,
//
// Summary:
// Applications cannot be launched under the debugger when the remote debugger is
// running as a service. Run the Remote Debugger Configuration Wizard on the target
// computer, and uncheck the option to start the remote debugger service. Then start
// the Visual Studio Remote Debugging Monitor application.
E_CANNOT_LAUNCH_IN_RDBSERVICE = -1842151355,
//
// Summary:
// The AD7 AL Causality bridge has already been initialized.
E_CAUSALITY_BRIDGE_ALREADY_INITIALIZED = -1842151354,
//
// Summary:
// App Packages may only be shutdown as part of a Visual Studio build operation.
E_DEPLOY_APPX_SHUTDOWN_WRONG_TIME = -1842151353,
//
// Summary:
// A Microsoft Windows component is not correctly registered. If the problem persists,
// try repairing your Windows installation, or reinstalling Windows.
E_WINDOWS_REG_ERROR = -1842151352,
//
// Summary:
// The application never reached a suspended state.
E_APP_PACKAGE_NEVER_SUSPENDED = -1842151351,
//
// Summary:
// A different version of this script file has been loaded by the debugged process.
// The script file may need to be reloaded.
E_SCRIPT_FILE_DIFFERENT_CONTENT = -1842151350,
//
// Summary:
// No stack frame was found.
E_NO_FRAME = -1842151349,
//
// Summary:
// Operation is not supported while interop debugging.
E_NOT_SUPPORTED_INTEROP = -1842151348,
//
// Summary:
// The selected accelerator does not support the run current tile to cursor operation.
E_GPU_BARRIER_BREAKPOINT_NOT_SUPPORTED = -1842151347,
//
// Summary:
// Data breakpoints are not supported on this platform.
E_DATABPS_NOTSUPPORTED = -1842151346,
//
// Summary:
// The debugger failed to attach to the process requested in the DkmDebugProcessRequest.
E_DEBUG_PROCESS_REQUEST_FAILED = -1842151345,
//
// Summary:
// An invalid NativeOffset or CPUInstructionPart value was used with a DkmClrInstructionAddress
// or DkmClrInstructionSymbol
E_INVALID_CLR_INSTRUCTION_NATIVE_OFFSET = -1842151339,
//
// Summary:
// Managed heap is not in a state that can be enumerated
E_MANAGED_HEAP_NOT_ENUMERABLE = -1842151338,
//
// Summary:
// This operation is unavailable when mixed mode debugging with Script
E_OPERATION_UNAVAILABLE_SCRIPT_INTEROP = -1842151337,
//
// Summary:
// This operation is unavailable when debugging native-compiled .NET code.
E_OPERATION_UNAVAILABLE_CLR_NC = -1842151336,
//
// Summary:
// Symbol file contains data which is in an unexpected format.
E_BAD_SYMBOL_DATA = -1842151335,
//
// Summary:
// Dynamically enabling script debugging in the target process failed.
E_ENABLE_SCRIPT_DEBUGGING_FAILED = -1842151334,
//
// Summary:
// Expression evaluation is not available in async call stack frames.
E_SCRIPT_ASYNC_FRAME_EE_UNAVAILABLE = -1842151333,
//
// Summary:
// This dump does not contain any thread information or the thread information is
// corrupt. Visual Studio does not support debugging of dumps without valid thread
// information.
E_DUMP_NO_THREADS = -1842151332,
//
// Summary:
// DkmLoadCompleteEventDeferral.Add cannot be called after the load complete event
// has been sent.
E_LOAD_COMPLETE_ALREADY_SENT = -1842151331,
//
// Summary:
// DkmLoadCompleteEventDeferral was not present in the list during a call to DkmLoadCompleteEventDeferral.Remove.
E_LOAD_COMPLETE_DEFERRAL_NOT_FOUND = -1842151330,
//
// Summary:
// The buffer size specified was too large to marshal over the remote boundary.
E_MARSHALLING_SIZE_TOO_LARGE = -1842151329,
//
// Summary:
// Emulation of iterator for results view failed. This is typically caused when
// the iterator calls into native code.
E_CANNOT_EMULATE_RESULTS_VIEW = -1842151328,
//
// Summary:
// Managed heap enumeration is attempted on running target. This is typically caused
// by continuing the process while heap enumeration is in progress.
E_MANAGED_HEAP_ENUMERATION_TARGET_NOT_STOPPED = -1842151327
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/Core/Portable/CommandLine/CommandLineSourceFile.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;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Describes a source file specification stored on command line arguments.
/// </summary>
[DebuggerDisplay("{Path,nq}")]
public struct CommandLineSourceFile
{
public CommandLineSourceFile(string path, bool isScript) :
this(path, isScript, false)
{ }
public CommandLineSourceFile(string path, bool isScript, bool isInputRedirected)
{
Debug.Assert(!string.IsNullOrEmpty(path));
Path = path;
IsScript = isScript;
IsInputRedirected = isInputRedirected;
}
/// <summary>
/// Resolved absolute path of the source file (does not contain wildcards).
/// </summary>
/// <remarks>
/// Although this path is absolute it may not be normalized. That is, it may contain ".." and "." in the middle.
/// </remarks>
public string Path { get; }
/// <summary>
/// True if the input has been redirected from the standard input stream.
/// </summary>
public bool IsInputRedirected { get; }
/// <summary>
/// True if the file should be treated as a script file.
/// </summary>
public bool IsScript { 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.Diagnostics;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Describes a source file specification stored on command line arguments.
/// </summary>
[DebuggerDisplay("{Path,nq}")]
public struct CommandLineSourceFile
{
public CommandLineSourceFile(string path, bool isScript) :
this(path, isScript, false)
{ }
public CommandLineSourceFile(string path, bool isScript, bool isInputRedirected)
{
Debug.Assert(!string.IsNullOrEmpty(path));
Path = path;
IsScript = isScript;
IsInputRedirected = isInputRedirected;
}
/// <summary>
/// Resolved absolute path of the source file (does not contain wildcards).
/// </summary>
/// <remarks>
/// Although this path is absolute it may not be normalized. That is, it may contain ".." and "." in the middle.
/// </remarks>
public string Path { get; }
/// <summary>
/// True if the input has been redirected from the standard input stream.
/// </summary>
public bool IsInputRedirected { get; }
/// <summary>
/// True if the file should be treated as a script file.
/// </summary>
public bool IsScript { get; }
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionFixAllTests.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;
using Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertSwitchStatementToExpression
{
using VerifyCS = CSharpCodeFixVerifier<
ConvertSwitchStatementToExpressionDiagnosticAnalyzer,
ConvertSwitchStatementToExpressionCodeFixProvider>;
public class ConvertSwitchStatementToExpressionFixAllTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_01()
{
await VerifyCS.VerifyCodeFixAsync(
@"class Program
{
int M(int i, int j)
{
int r;
[|switch|] (i)
{
case 1:
r = 1;
break;
case 2:
r = 2;
break;
case 3:
r = 3;
break;
default:
r = 4;
break;
}
int x, y;
switch (i)
{
case 1:
x = 1;
y = 1;
break;
case 2:
x = 1;
y = 1;
break;
case 3:
x = 1;
y = 1;
break;
default:
x = 1;
y = 1;
break;
}
[|switch|] (i)
{
default:
throw null;
case 1:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
}
return 0;
case 2:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
case var _:
return 0;
}
case 3:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
case var v:
return 0;
}
}
}
}",
@"class Program
{
int M(int i, int j)
{
var r = i switch
{
1 => 1,
2 => 2,
3 => 3,
_ => 4,
};
int x, y;
switch (i)
{
case 1:
x = 1;
y = 1;
break;
case 2:
x = 1;
y = 1;
break;
case 3:
x = 1;
y = 1;
break;
default:
x = 1;
y = 1;
break;
}
return i switch
{
1 => j switch
{
10 => 10,
20 => 20,
30 => 30,
_ => 0,
},
2 => j switch
{
10 => 10,
20 => 20,
30 => 30,
var _ => 0,
},
3 => j switch
{
10 => 10,
20 => 20,
30 => 30,
var v => 0,
},
_ => throw null,
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_02()
{
var input = @"class Program
{
System.Func<int> M(int i, int j)
{
[|switch|] (i)
{
// 1
default: // 2
return () =>
{
[|switch|] (j)
{
default:
return 3;
}
};
}
}
}";
var expected = @"class Program
{
System.Func<int> M(int i, int j)
{
return i switch
{
// 1
// 2
_ => () =>
{
return j switch
{
_ => 3,
};
}
,
};
}
}";
await new VerifyCS.Test
{
TestCode = input,
FixedCode = expected,
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[WorkItem(37907, "https://github.com/dotnet/roslyn/issues/37907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_03()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
class Program
{
public static void Main() { }
public DayOfWeek StatusValue() => DayOfWeek.Monday;
public short Value => 0;
public bool ValueBoolean()
{
bool value;
[|switch|] (StatusValue())
{
case DayOfWeek.Monday:
[|switch|] (Value)
{
case 0:
value = false;
break;
case 1:
value = true;
break;
default:
throw new Exception();
}
break;
default:
throw new Exception();
}
return value;
}
}",
@"using System;
class Program
{
public static void Main() { }
public DayOfWeek StatusValue() => DayOfWeek.Monday;
public short Value => 0;
public bool ValueBoolean()
{
var value = StatusValue() switch
{
DayOfWeek.Monday => Value switch
{
0 => false,
1 => true,
_ => throw new Exception(),
},
_ => throw new Exception(),
};
return value;
}
}");
}
[WorkItem(44572, "https://github.com/dotnet/roslyn/issues/44572")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestImplicitConversion()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
class C
{
public C(String s) => _s = s;
private readonly String _s;
public static implicit operator String(C value) => value._s;
public static implicit operator C(String value) => new C(value);
public bool method(C c)
{
[|switch|] (c)
{
case ""A"": return true;
default: return false;
}
}
}",
@"using System;
class C
{
public C(String s) => _s = s;
private readonly String _s;
public static implicit operator String(C value) => value._s;
public static implicit operator C(String value) => new C(value);
public bool method(C c)
{
return (string)c switch
{
""A"" => true,
_ => 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertSwitchStatementToExpression
{
using VerifyCS = CSharpCodeFixVerifier<
ConvertSwitchStatementToExpressionDiagnosticAnalyzer,
ConvertSwitchStatementToExpressionCodeFixProvider>;
public class ConvertSwitchStatementToExpressionFixAllTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_01()
{
await VerifyCS.VerifyCodeFixAsync(
@"class Program
{
int M(int i, int j)
{
int r;
[|switch|] (i)
{
case 1:
r = 1;
break;
case 2:
r = 2;
break;
case 3:
r = 3;
break;
default:
r = 4;
break;
}
int x, y;
switch (i)
{
case 1:
x = 1;
y = 1;
break;
case 2:
x = 1;
y = 1;
break;
case 3:
x = 1;
y = 1;
break;
default:
x = 1;
y = 1;
break;
}
[|switch|] (i)
{
default:
throw null;
case 1:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
}
return 0;
case 2:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
case var _:
return 0;
}
case 3:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
case var v:
return 0;
}
}
}
}",
@"class Program
{
int M(int i, int j)
{
var r = i switch
{
1 => 1,
2 => 2,
3 => 3,
_ => 4,
};
int x, y;
switch (i)
{
case 1:
x = 1;
y = 1;
break;
case 2:
x = 1;
y = 1;
break;
case 3:
x = 1;
y = 1;
break;
default:
x = 1;
y = 1;
break;
}
return i switch
{
1 => j switch
{
10 => 10,
20 => 20,
30 => 30,
_ => 0,
},
2 => j switch
{
10 => 10,
20 => 20,
30 => 30,
var _ => 0,
},
3 => j switch
{
10 => 10,
20 => 20,
30 => 30,
var v => 0,
},
_ => throw null,
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_02()
{
var input = @"class Program
{
System.Func<int> M(int i, int j)
{
[|switch|] (i)
{
// 1
default: // 2
return () =>
{
[|switch|] (j)
{
default:
return 3;
}
};
}
}
}";
var expected = @"class Program
{
System.Func<int> M(int i, int j)
{
return i switch
{
// 1
// 2
_ => () =>
{
return j switch
{
_ => 3,
};
}
,
};
}
}";
await new VerifyCS.Test
{
TestCode = input,
FixedCode = expected,
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[WorkItem(37907, "https://github.com/dotnet/roslyn/issues/37907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_03()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
class Program
{
public static void Main() { }
public DayOfWeek StatusValue() => DayOfWeek.Monday;
public short Value => 0;
public bool ValueBoolean()
{
bool value;
[|switch|] (StatusValue())
{
case DayOfWeek.Monday:
[|switch|] (Value)
{
case 0:
value = false;
break;
case 1:
value = true;
break;
default:
throw new Exception();
}
break;
default:
throw new Exception();
}
return value;
}
}",
@"using System;
class Program
{
public static void Main() { }
public DayOfWeek StatusValue() => DayOfWeek.Monday;
public short Value => 0;
public bool ValueBoolean()
{
var value = StatusValue() switch
{
DayOfWeek.Monday => Value switch
{
0 => false,
1 => true,
_ => throw new Exception(),
},
_ => throw new Exception(),
};
return value;
}
}");
}
[WorkItem(44572, "https://github.com/dotnet/roslyn/issues/44572")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestImplicitConversion()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
class C
{
public C(String s) => _s = s;
private readonly String _s;
public static implicit operator String(C value) => value._s;
public static implicit operator C(String value) => new C(value);
public bool method(C c)
{
[|switch|] (c)
{
case ""A"": return true;
default: return false;
}
}
}",
@"using System;
class C
{
public C(String s) => _s = s;
private readonly String _s;
public static implicit operator String(C value) => value._s;
public static implicit operator C(String value) => new C(value);
public bool method(C c)
{
return (string)c switch
{
""A"" => true,
_ => false,
};
}
}");
}
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.Structure;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Tagging
{
[UseExportProvider]
public class AsynchronousTaggerTests : TestBase
{
/// <summary>
/// This hits a special codepath in the product that is optimized for more than 100 spans.
/// I'm leaving this test here because it covers that code path (as shown by code coverage)
/// </summary>
[WpfFact]
[WorkItem(530368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530368")]
public async Task LargeNumberOfSpans()
{
using var workspace = TestWorkspace.CreateCSharp(@"class Program
{
void M()
{
int z = 0;
z = z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z;
}
}");
static List<ITagSpan<TestTag>> tagProducer(SnapshotSpan span, CancellationToken cancellationToken)
{
return new List<ITagSpan<TestTag>>() { new TagSpan<TestTag>(span, new TestTag()) };
}
var asyncListener = new AsynchronousOperationListener();
WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(LargeNumberOfSpans)} creates asynchronous taggers");
var eventSource = CreateEventSource();
var taggerProvider = new TestTaggerProvider(
workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
tagProducer,
eventSource,
asyncListener);
var document = workspace.Documents.First();
var textBuffer = document.GetTextBuffer();
var snapshot = textBuffer.CurrentSnapshot;
var tagger = taggerProvider.CreateTagger<TestTag>(textBuffer);
using var disposable = (IDisposable)tagger;
var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1));
var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans);
eventSource.SendUpdateEvent();
await asyncListener.ExpeditedWaitAsync();
var tags = tagger.GetTags(snapshotSpans);
Assert.Equal(1, tags.Count());
}
[WpfFact]
public void TestNotSynchronousOutlining()
{
using var workspace = TestWorkspace.CreateCSharp("class Program {\r\n\r\n}", composition: EditorTestCompositions.EditorFeaturesWpf);
WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestNotSynchronousOutlining)} creates asynchronous taggers");
var tagProvider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>();
var document = workspace.Documents.First();
var textBuffer = document.GetTextBuffer();
var tagger = tagProvider.CreateTagger<IStructureTag>(textBuffer);
using var disposable = (IDisposable)tagger;
// The very first all to get tags will not be synchronous as this contains no #region tag
var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan()));
Assert.Equal(0, tags.Count());
}
[WpfFact]
public void TestSynchronousOutlining()
{
using var workspace = TestWorkspace.CreateCSharp(@"
#region x
class Program
{
}
#endregion", composition: EditorTestCompositions.EditorFeaturesWpf);
WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestSynchronousOutlining)} creates asynchronous taggers");
var tagProvider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>();
var document = workspace.Documents.First();
var textBuffer = document.GetTextBuffer();
var tagger = tagProvider.CreateTagger<IStructureTag>(textBuffer);
using var disposable = (IDisposable)tagger;
// The very first all to get tags will be synchronous because of the #region
var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan()));
Assert.Equal(2, tags.Count());
}
private static TestTaggerEventSource CreateEventSource()
=> new TestTaggerEventSource();
private sealed class TestTag : TextMarkerTag
{
public TestTag()
: base("Test")
{
}
}
private delegate List<ITagSpan<TestTag>> Callback(SnapshotSpan span, CancellationToken cancellationToken);
private sealed class TestTaggerProvider : AsynchronousTaggerProvider<TestTag>
{
private readonly Callback _callback;
private readonly ITaggerEventSource _eventSource;
public TestTaggerProvider(
IThreadingContext threadingContext,
Callback callback,
ITaggerEventSource eventSource,
IAsynchronousOperationListener asyncListener)
: base(threadingContext, asyncListener)
{
_callback = callback;
_eventSource = eventSource;
}
protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate;
protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
=> _eventSource;
protected override Task ProduceTagsAsync(TaggerContext<TestTag> context, DocumentSnapshotSpan snapshotSpan, int? caretPosition)
{
var tags = _callback(snapshotSpan.SnapshotSpan, context.CancellationToken);
if (tags != null)
{
foreach (var tag in tags)
{
context.AddTag(tag);
}
}
return Task.CompletedTask;
}
}
private sealed class TestTaggerEventSource : AbstractTaggerEventSource
{
public TestTaggerEventSource()
{
}
public void SendUpdateEvent()
=> this.RaiseChanged();
public override void Connect()
{
}
public override void Disconnect()
{
}
}
}
}
| // 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.Structure;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Tagging
{
[UseExportProvider]
public class AsynchronousTaggerTests : TestBase
{
/// <summary>
/// This hits a special codepath in the product that is optimized for more than 100 spans.
/// I'm leaving this test here because it covers that code path (as shown by code coverage)
/// </summary>
[WpfFact]
[WorkItem(530368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530368")]
public async Task LargeNumberOfSpans()
{
using var workspace = TestWorkspace.CreateCSharp(@"class Program
{
void M()
{
int z = 0;
z = z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z;
}
}");
static List<ITagSpan<TestTag>> tagProducer(SnapshotSpan span, CancellationToken cancellationToken)
{
return new List<ITagSpan<TestTag>>() { new TagSpan<TestTag>(span, new TestTag()) };
}
var asyncListener = new AsynchronousOperationListener();
WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(LargeNumberOfSpans)} creates asynchronous taggers");
var eventSource = CreateEventSource();
var taggerProvider = new TestTaggerProvider(
workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
tagProducer,
eventSource,
asyncListener);
var document = workspace.Documents.First();
var textBuffer = document.GetTextBuffer();
var snapshot = textBuffer.CurrentSnapshot;
var tagger = taggerProvider.CreateTagger<TestTag>(textBuffer);
using var disposable = (IDisposable)tagger;
var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1));
var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans);
eventSource.SendUpdateEvent();
await asyncListener.ExpeditedWaitAsync();
var tags = tagger.GetTags(snapshotSpans);
Assert.Equal(1, tags.Count());
}
[WpfFact]
public void TestNotSynchronousOutlining()
{
using var workspace = TestWorkspace.CreateCSharp("class Program {\r\n\r\n}", composition: EditorTestCompositions.EditorFeaturesWpf);
WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestNotSynchronousOutlining)} creates asynchronous taggers");
var tagProvider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>();
var document = workspace.Documents.First();
var textBuffer = document.GetTextBuffer();
var tagger = tagProvider.CreateTagger<IStructureTag>(textBuffer);
using var disposable = (IDisposable)tagger;
// The very first all to get tags will not be synchronous as this contains no #region tag
var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan()));
Assert.Equal(0, tags.Count());
}
[WpfFact]
public void TestSynchronousOutlining()
{
using var workspace = TestWorkspace.CreateCSharp(@"
#region x
class Program
{
}
#endregion", composition: EditorTestCompositions.EditorFeaturesWpf);
WpfTestRunner.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestSynchronousOutlining)} creates asynchronous taggers");
var tagProvider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>();
var document = workspace.Documents.First();
var textBuffer = document.GetTextBuffer();
var tagger = tagProvider.CreateTagger<IStructureTag>(textBuffer);
using var disposable = (IDisposable)tagger;
// The very first all to get tags will be synchronous because of the #region
var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan()));
Assert.Equal(2, tags.Count());
}
private static TestTaggerEventSource CreateEventSource()
=> new TestTaggerEventSource();
private sealed class TestTag : TextMarkerTag
{
public TestTag()
: base("Test")
{
}
}
private delegate List<ITagSpan<TestTag>> Callback(SnapshotSpan span, CancellationToken cancellationToken);
private sealed class TestTaggerProvider : AsynchronousTaggerProvider<TestTag>
{
private readonly Callback _callback;
private readonly ITaggerEventSource _eventSource;
public TestTaggerProvider(
IThreadingContext threadingContext,
Callback callback,
ITaggerEventSource eventSource,
IAsynchronousOperationListener asyncListener)
: base(threadingContext, asyncListener)
{
_callback = callback;
_eventSource = eventSource;
}
protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate;
protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
=> _eventSource;
protected override Task ProduceTagsAsync(TaggerContext<TestTag> context, DocumentSnapshotSpan snapshotSpan, int? caretPosition)
{
var tags = _callback(snapshotSpan.SnapshotSpan, context.CancellationToken);
if (tags != null)
{
foreach (var tag in tags)
{
context.AddTag(tag);
}
}
return Task.CompletedTask;
}
}
private sealed class TestTaggerEventSource : AbstractTaggerEventSource
{
public TestTaggerEventSource()
{
}
public void SendUpdateEvent()
=> this.RaiseChanged();
public override void Connect()
{
}
public override void Disconnect()
{
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/VisualBasic/Test/Syntax/Parser/ParseDeclarationTests.vb | ' 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.
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
<CLSCompliant(False)>
Public Class ParseDeclarations
Inherits BasicTestBase
<WorkItem(865836, "DevDiv/Personal")>
<WorkItem(927366, "DevDiv/Personal")>
<Fact>
Public Sub ParseModuleDeclaration()
ParseAndVerify(<![CDATA[
Module Module1
End Module
]]>).
VerifyOccurrenceCount(SyntaxKind.EndOfFileToken, 1)
ParseAndVerify(<![CDATA[
Module Module1 : End Module
]]>).
VerifyOccurrenceCount(SyntaxKind.EndOfFileToken, 1)
ParseAndVerify(<![CDATA[Module Module1
End Module]]>).
VerifyOccurrenceCount(SyntaxKind.EndOfFileToken, 1)
End Sub
<Fact>
Public Sub ParseNamespaceDeclaration()
ParseAndVerify(<![CDATA[
Namespace N1
End Namespace
]]>)
ParseAndVerify(<![CDATA[
Namespace N1 : End Namespace
]]>)
End Sub
<Fact>
Public Sub ParseNamespaceDeclarationWithGlobal()
ParseAndVerify(<![CDATA[
Namespace Global.N1
End Namespace
]]>)
End Sub
<Fact>
Public Sub ParseClassDeclaration()
ParseAndVerify(<![CDATA[
Class C1
End Class
]]>)
ParseAndVerify(<![CDATA[
Class C1 : End Class
]]>)
End Sub
<Fact>
Public Sub ParseStructureDeclaration()
ParseAndVerify(<![CDATA[
Structure S1
End Structure
]]>)
ParseAndVerify(<![CDATA[
Structure S1 : End Structure
]]>)
End Sub
<Fact>
Public Sub ParseInterfaceDeclaration()
ParseAndVerify(<![CDATA[
Interface I1
End Interface
]]>)
ParseAndVerify(<![CDATA[
Interface I1 : End Interface
]]>)
End Sub
<Fact>
Public Sub ParseClassInheritsDeclaration()
ParseAndVerify(<![CDATA[
Class C1
End Class
Class C2
Inherits C1
End Class
]]>)
End Sub
<WorkItem(927384, "DevDiv/Personal")>
<Fact>
Public Sub ParseClassInheritsStatementWithSeparator()
ParseAndVerify(<![CDATA[
Class C1
End Class
Class C2 : Inherits C1
End Class
Class C3 :
Inherits C1
End Class
Class C4
: Inherits C1
End Class
Class C4 :::
:::: Inherits C1
:::: Implements QQQ
End Class
Interface I1 : End Interface
Interface I2:
Inherits I1
End Interface
Interface I3
:Inherits I1
End Interface
Interface I3::
:Inherits I1 ::
:: Inherits I2 ::
End Interface
Structure S1
:Implements I1
End Structure
Structure S2:
Implements I1
End Structure
]]>)
End Sub
<Fact>
Public Sub ParseClassImplementsDeclaration()
ParseAndVerify(<![CDATA[
Interface I1
End Interface
Class C2
Implements I1
End Class
]]>)
End Sub
<Fact>
Public Sub ParseGenericClassDeclaration()
ParseAndVerify(<![CDATA[
Class C1(of T1, T2)
End Class
]]>)
ParseAndVerify(<![CDATA[
Class C1(
of
T1,
T2
)
End Class
]]>)
End Sub
<Fact>
Public Sub ParseGenericClassAsNewDeclaration()
ParseAndVerify(<![CDATA[
Class Base
End Class
Class C1(of T1 as new)
End Class
]]>)
End Sub
<Fact>
Public Sub ParseGenericClassAsTypeDeclaration()
ParseAndVerify(<![CDATA[
Class Base
End Class
Class C1(of T1 as Base)
End Class
]]>)
End Sub
<Fact>
Public Sub ParseGenericClassAsMultipleDeclaration()
ParseAndVerify(<![CDATA[
Class Base
End Class
Class C1(of T1 as {new, Base})
End Class
]]>)
ParseAndVerify(<![CDATA[
Class Base
End Class
Class C1(of
T1 as {
new,
Base
})
End Class
]]>)
End Sub
<Fact>
Public Sub ParseEnum()
ParseAndVerify(<![CDATA[
Module Module1
enum e1
member1
member2
member3 = 100
member4
end enum
End Module
]]>)
End Sub
<Fact>
Public Sub Bug8037()
ParseAndVerify(<![CDATA[
Enum Y
::A ::B
End Enum
]]>)
ParseAndVerify(<![CDATA[
Enum Y::
::A::B:::
End Enum
]]>)
ParseAndVerify(<![CDATA[
Enum Y
A::B::: ' A: is parsed as a label
End Enum
]]>,
Diagnostic(ERRID.ERR_InvInsideEnum, "A:"))
ParseAndVerify(<![CDATA[
Enum Y:::::
A::B ' A: is parsed as a label
End Enum
]]>,
Diagnostic(ERRID.ERR_InvInsideEnum, "A:"))
End Sub
<Fact>
Public Sub Bug862490()
ParseAndVerify(<![CDATA[
Interface I1
End Interface
Interface I2
Inherits I1
End Interface
]]>)
End Sub
<Fact>
Public Sub Bug863541()
ParseAndVerify(<![CDATA[
Class Class1(Of Type)
End Class
]]>)
End Sub
<Fact>
Public Sub Bug866559()
ParseAndVerify(<![CDATA[
Interface IVariance1(Of Out)
End Interface
]]>)
End Sub
<Fact>
Public Sub Bug866616()
ParseAndVerify(<![CDATA[
Module Module1
Dim x = from i in ""
End Module
]]>).
VerifyOccurrenceCount(SyntaxKind.EmptyStatement, 0)
End Sub
<Fact>
Public Sub Bug867063()
ParseAndVerify(<![CDATA[
Interface IVariance(Of In T, Out R) : : End Interface
]]>)
End Sub
<Fact>
Public Sub Bug868402()
'Tree does not round-trip for generic type parameter list with newlines
ParseAndVerify(<![CDATA[
Interface IVariance1(Of Out
)
End Interface
]]>)
End Sub
<WorkItem(873467, "DevDiv/Personal")>
<Fact>
Public Sub ParseInterfaceBasesDeclaration()
ParseAndVerify(<![CDATA[
Interface I1 : End Interface
Interface I2 : End Interface
Interface I3
Inherits I1, I2
End Interface
]]>)
ParseAndVerify(<![CDATA[
Interface I1 : End Interface
Interface I2 : End Interface
Class C1
Implements I1, I2
End Class
]]>)
ParseAndVerify(<![CDATA[
Interface I1 : End Interface
Interface I2 : End Interface
Structure S1
Implements I1, I2
End Structure
]]>)
End Sub
<WorkItem(882976, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaInFieldInitializer()
ParseAndVerify(<![CDATA[
Class Class1
Dim x = Sub() Console.WriteLine()
Dim y As Integer = 3
End Class
]]>)
End Sub
<WorkItem(869140, "DevDiv/Personal")>
<Fact>
Public Sub ParseInterfaceSingleLine()
ParseAndVerify(<![CDATA[
Interface IVariance(Of Out T) : Function Goo() As T : End Interface
]]>)
End Sub
<WorkItem(889005, "DevDiv/Personal")>
<Fact>
Public Sub ParseErrorsInvalidEndFunctionAndExecutableAsDeclaration()
ParseAndVerify(<![CDATA[
Class Class1
Dim x32 As Object = Sub() Call Function()
Return New Exception
Return New Exception
End Function
Dim x43 As Object = CType(Function()
Return Nothing
End Function, Action(Of Long))
End Class
]]>)
End Sub
<WorkItem(917197, "DevDiv/Personal")>
<Fact>
Public Sub TraverseEmptyBlocks()
ParseAndVerify(
"Module M1" & vbCrLf &
"Sub Goo" & vbCrLf &
"Try" & vbCrLf &
"Catch" & vbCrLf &
"Finally" & vbCrLf &
"End Try" & vbCrLf &
"End Sub" & vbCrLf &
"End Module"
).
TraverseAllNodes()
End Sub
<WorkItem(527076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527076")>
<Fact>
Public Sub ParseMustOverrideInsideModule()
ParseAndVerify(<![CDATA[
Module M1
Mustoverride Sub Goo()
End Sub
End Module
]]>, <errors>
<error id="30429" message="'End Sub' must be preceded by a matching 'Sub'." start="34" end="41"/>
</errors>)
End Sub
<Fact>
Public Sub ParseVariousOrderingOfDeclModifiers()
ParseAndVerify(<![CDATA[
Public MustInherit Class A
MustInherit Private Class B
Public MustOverride Function Func() As Integer
MustOverride Protected Property Prop As String
End Class
End Class
]]>)
End Sub
<Fact>
Public Sub ParseIncompleteMemberBecauseOfAttributeAndOrModifiers()
ParseAndVerify(<![CDATA[
Public Class C1
<Obsolete1()>
goo
<Obsolete2()>
if true then :
Public ' 1
<Obsolete3()>
Public ' 2
<Obsolete4()>
Public Shared with
Public Shared with if SyncLock
Public Shared Sub Main()
End Sub
End Class
]]>, <errors>
<error id="32035"/>
<error id="32035"/>
<error id="30203"/>
<error id="30203"/>
<error id="32035"/>
<error id="30183"/>
<error id="30183"/>
</errors>)
End Sub
<WorkItem(543607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543607")>
<Fact()>
Public Sub ParseInheritsAtInvalidLocation()
ParseAndVerify(<![CDATA[
Class Scen24
Dim i = Sub(a as Integer, b as Long)
Inherits Scen23
End Sub
End Class
]]>, <errors>
<error id="30024"/>
</errors>)
End Sub
#Region "Parser Error Tests"
<WorkItem(866455, "DevDiv/Personal")>
<Fact>
Public Sub BC30001ERR_NoParseError()
ParseAndVerify(<![CDATA[
Property Goo As Integer
Namespace Namespace1
End Namespace
]]>)
End Sub
<WorkItem(863086, "DevDiv/Personal")>
<Fact>
Public Sub BC30025ERR_EndProp()
ParseAndVerify(<![CDATA[
Structure Struct1
Default Public Property Goo(ByVal x) As Integer
End Function
End Structure
]]>,
<errors>
<error id="30430"/>
<error id="30634"/>
<error id="30025"/>
</errors>)
End Sub
<WorkItem(527022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527022")>
<Fact()>
Public Sub BC30037ERR_IllegalChar_TypeParamMissingAsCommaOrRParen()
ParseAndVerify(<![CDATA[
Class Class1(of ])
End Class
]]>,
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_TypeParamMissingAsCommaOrRParen, ""),
Diagnostic(ERRID.ERR_IllegalChar, "]"))
End Sub
<WorkItem(888046, "DevDiv/Personal")>
<Fact>
Public Sub BC30184ERR_InvalidEndEnum()
ParseAndVerify(<![CDATA[
Enum myenum
x
Shared Narrowing Operator CType(ByVal x As Integer) As c2
Return New c2
End Operator
End Enum
]]>,
Diagnostic(ERRID.ERR_MissingEndEnum, "Enum myenum"),
Diagnostic(ERRID.ERR_InvInsideEndsEnum, "Shared Narrowing Operator CType(ByVal x As Integer) As c2"),
Diagnostic(ERRID.ERR_InvalidEndEnum, "End Enum"))
End Sub
<WorkItem(869144, "DevDiv/Personal")>
<Fact>
Public Sub BC30185ERR_MissingEndEnum()
' Tree loses text when access modifier used on Enum member
ParseAndVerify(<![CDATA[
Enum Access1
Orange
Public Red = 2
End Enum
]]>,
<errors>
<error id="30185"/>
<error id="30619"/>
<error id="30184"/>
</errors>)
End Sub
<WorkItem(863528, "DevDiv/Personal")>
<Fact>
Public Sub BC30188ERR_ExpectedDeclaration()
ParseAndVerify(<![CDATA[
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
Persistable = 0 'NotPersistable
DataBindingBehavior = 0 'vbNone
DataSourceBehavior = 0 'vbNone
MTSTransactionMode = 0 'NotAnMTSObject
END
Attribute VB_Name = "Class1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Public v As Variant
]]>,
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "VERSION 1.0 CLASS"),
Diagnostic(ERRID.ERR_ObsoleteArgumentsNeedParens, "1.0 CLASS"),
Diagnostic(ERRID.ERR_ArgumentSyntax, "CLASS"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "BEGIN"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "MultiUse = -1"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Persistable = 0"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "DataBindingBehavior = 0"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "DataSourceBehavior = 0"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "MTSTransactionMode = 0"),
Diagnostic(ERRID.ERR_UnrecognizedEnd, "END"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_Name = ""Class1"""),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_GlobalNameSpace = False"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_Creatable = True"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_PredeclaredId = False"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_Exposed = True"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ObsoleteObjectNotVariant, "Variant"))
End Sub
<Fact>
Public Sub BC30193ERR_SpecifiersInvalidOnInheritsImplOpt()
ParseAndVerify(<![CDATA[
Class C
<A> Inherits B
End Class
]]>,
<errors>
<error id="30193"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
<A> Implements I
End Class
]]>,
<errors>
<error id="30193"/>
</errors>)
End Sub
<WorkItem(863112, "DevDiv/Personal")>
<Fact>
Public Sub BC30193ERR_SpecifiersInvalidOnInheritsImplOpt_2()
ParseAndVerify(<![CDATA[
<System.Runtime.CompilerServices.Extension()> Namespace ExtensionAttributeNamespace01
End Namespace
]]>,
<errors>
<error id="30193"/>
</errors>)
End Sub
<WorkItem(887502, "DevDiv/Personal")>
<Fact>
Public Sub BC30193_MismatchEndNoNamespace()
ParseAndVerify(<![CDATA[
<System.Runtime.CompilerServices.CompilationRelaxations(Runtime.CompilerServices.CompilationRelaxations.NoStringInterning)> _
Namespace CompilerRelaxations02
End Namespace
]]>,
<errors>
<error id="30193"/>
</errors>)
End Sub
<Fact>
Public Sub BC30193_ParseInterfaceInherits()
ParseAndVerify(<![CDATA[
interface i
public inherits i2
end interface
]]>,
<errors>
<error id="30193"/>
</errors>)
End Sub
<WorkItem(889075, "DevDiv/Personal")>
<Fact>
Public Sub BC30201ERR_ExpectedExpression_InvInsideEndsEnumAndMissingEndEnum()
ParseAndVerify(<![CDATA[
Module Module1
Enum byteenum As Byte
a = 200
b =
End Enum
Enum sbyteenum As SByte
c
d
End Enum
End Module
]]>,
<errors>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(889301, "DevDiv/Personal")>
<Fact>
Public Sub BC30203ERR_ExpectedIdentifier_ParasExtraError30213()
' Expected error 30203: Identifier expected.
' Was also reporting 30213.
ParseAndVerify(<![CDATA[
Friend Class cTest
Sub Sub1 (0 To 10)
End Sub
End Class
]]>,
<errors>
<error id="30203"/>
</errors>)
End Sub
<Fact>
Public Sub BC30205ERR_ExpectedEOS_NamespaceDeclarationWithGeneric()
ParseAndVerify(<![CDATA[
Namespace N1.N2(of T)
End Namespace
]]>,
<errors>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(894067, "DevDiv/Personal")>
<Fact>
Public Sub BC30213ERR_InvalidParameterSyntax_DollarAutoProp()
ParseAndVerify(<![CDATA[
Property Scen4(
p1 as vb$anonymous1
) a
]]>,
Diagnostic(ERRID.ERR_InvalidParameterSyntax, "anonymous1"),
Diagnostic(ERRID.ERR_AutoPropertyCantHaveParams, <![CDATA[(
p1 as vb$anonymous1
)]]>))
End Sub
<Fact>
Public Sub BC30363ERR_NewInInterface_InterfaceWithSubNew()
ParseAndVerify(<![CDATA[
Interface i
Sub new ()
End Interface
]]>,
<errors>
<error id="30363"/>
</errors>)
End Sub
<WorkItem(887748, "DevDiv/Personal")>
<WorkItem(889062, "DevDiv/Personal")>
<WorkItem(538919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538919")>
<Fact>
Public Sub BC30602ERR_InterfaceMemberSyntax_TypeStatement()
ParseAndVerify(<![CDATA[
interface i1
dim i as integer
End interface
Interface Scen1
type dd
End Interface
Interface il
_loc as object
End Interface
]]>,
<errors>
<error id="30188"/>
<error id="30602"/>
<error id="30802"/>
</errors>)
End Sub
<WorkItem(887508, "DevDiv/Personal")>
<Fact>
Public Sub BC30603ERR_InvInsideInterface_ParseInterfaceWithSubWithEndSub()
ParseAndVerify(<![CDATA[
Interface i1
Sub goo()
end sub
End Interface
]]>,
<errors>
<error id="30603"/>
</errors>)
End Sub
<Fact>
Public Sub BC30618ERR_NamespaceNotAtNamespace_ModuleNamespaceClassDeclaration()
ParseAndVerify(<![CDATA[
Namespace N1
Module M1
Class A
End Class
End Module
End Namespace
]]>)
ParseAndVerify(<![CDATA[
Module Module1
Namespace N1
Class A
End Class
End Namespace
End Module
]]>,
<errors>
<error id=<%= CInt(ERRID.ERR_ExpectedEndModule) %>/>
<error id=<%= CInt(ERRID.ERR_NamespaceNotAtNamespace) %>/>
<error id=<%= CInt(ERRID.ERR_EndModuleNoModule) %>/>
</errors>)
End Sub
<WorkItem(862508, "DevDiv/Personal")>
<Fact>
Public Sub BC30624ERR_ExpectedEndStructure()
ParseAndVerify(<![CDATA[
Structure Struct1
]]>,
<errors>
<error id="30624"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30625ERR_ExpectedEndModule()
ParseAndVerify(<![CDATA[
Module M1
]]>,
<errors>
<error id="30625"/>
</errors>)
End Sub
<Fact>
Public Sub BC30626ERR_ExpectedEndNamespace_ModuleNamespaceClassMissingEnd1()
ParseAndVerify(<![CDATA[
Module Module1
Namespace N1
Class A
End Module
]]>,
<errors>
<error id=<%= CInt(ERRID.ERR_ExpectedEndModule) %>/>
<error id=<%= CInt(ERRID.ERR_NamespaceNotAtNamespace) %>/>
<error id=<%= CInt(ERRID.ERR_ExpectedEndNamespace) %>/>
<error id=<%= CInt(ERRID.ERR_ExpectedEndClass) %>/>
<error id=<%= CInt(ERRID.ERR_EndModuleNoModule) %>/>
</errors>)
End Sub
<Fact>
Public Sub NamespaceOutOfPlace()
ParseAndVerify(<![CDATA[
Module Module1
Class C1
Namespace N1
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'." start="17" end="31"/>
<error id="30481" message="'Class' statement must end with a matching 'End Class'." start="52" end="60"/>
<error id="30618" message="'Namespace' statements can occur only at file or namespace level." start="85" end="97"/>
<error id="30626" message="'Namespace' statement must end with a matching 'End Namespace'." start="85" end="97"/>
</errors>)
ParseAndVerify(<![CDATA[
Module Module1
Sub S1()
Namespace N1
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'." start="17" end="31"/>
<error id="30026" message="'End Sub' expected." start="52" end="60"/>
<error id="30289" message="Statement cannot appear within a method body. End of method assumed." start="85" end="97"/>
<error id="30626" message="'Namespace' statement must end with a matching 'End Namespace'." start="85" end="97"/>
</errors>)
End Sub
<WorkItem(888556, "DevDiv/Personal")>
<Fact>
Public Sub BC30984ERR_ExpectedAssignmentOperatorInInit_AndExpectedRbrace()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
Dim scen2b = New With {.prop = 10, .321prop = 9, .567abc = -10}
Dim scen3 = New With {.$123prop=1}
End Sub
End Module
]]>,
<errors>
<error id="36576"/>
<error id="36576"/>
<error id="30203"/>
<error id="30984"/>
<error id="30201"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(888560, "DevDiv/Personal")>
<Fact>
Public Sub BC30987ERR_ExpectedLbrace_EndNoModuleAndModuleNotAtNamespaceAndExpectedEndClass()
ParseAndVerify(<![CDATA[
Namespace scen8
Class customer
End Class
Class c1
public x as new customer with
End Class
Module m
Sub test()
End Sub
End Module
End Namespace
]]>,
<errors>
<error id="30987"/>
</errors>)
End Sub
<WorkItem(889038, "DevDiv/Personal")>
<Fact>
Public Sub BC31111ERR_ExitEventMemberNotInvalid_ExpectedExitKindAndSubOfFuncAndExpectedExitKind()
ParseAndVerify(<![CDATA[
Friend Class cTest
Friend Delegate Sub fir()
Friend Custom Event e As fir
AddHandler(ByVal value As fir)
exit addhandler
End AddHandler
RemoveHandler(ByVal value As fir)
exit removehandler
End RemoveHandler
RaiseEvent()
exit raiseevent
End RaiseEvent
End Event
End Class
]]>,
<errors>
<error id="31111"/>
<error id="31111"/>
<error id="31111"/>
</errors>)
End Sub
<WorkItem(536278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536278")>
<Fact>
Public Sub BC31140ERR_InvalidUseOfCustomModifier_ExpectedSpecifierAndInvalidEndSub()
ParseAndVerify(<![CDATA[
Module Module1
Custom sub goo()
End Sub
End Module
]]>,
<errors>
<error id="30195"/>
<error id="31140"/>
<error id="30429"/>
</errors>)
End Sub
<Fact>
Public Sub BC32100ERR_TypeParamMissingAsCommaOrRParen_GenericClassMissingComma()
ParseAndVerify(<![CDATA[
class B(of a b)
end class
]]>,
<errors>
<error id="32100"/>
</errors>)
End Sub
<Fact>
Public Sub Bug863497()
ParseAndVerify(<![CDATA[
Namespace $safeitemname$
Public Module $safeitemname$
End Module
End Namespace
]]>,
<errors>
<error id="30203"/>
<error id="30037"/>
<error id="30203"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(538990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538990")>
<Fact>
Public Sub Bug4770()
ParseAndVerify(<![CDATA[
interface i1
dim i as integer
End interface
]]>, <errors>
<error id="30602"/>
</errors>)
End Sub
<WorkItem(539509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539509")>
<Fact>
Public Sub EnumsWithGenericParameter()
' Enums should recover the same was as other declarations that do not allow generics.
Dim t = ParseAndVerify(<![CDATA[
enum e(Of T1, T2)
red
end enum
Module Program(Of T1, T2)
End Module
Class C
Sub New(Of T)()
End Sub
Property P(Of T)
Event e(Of T)
Shared Operator +(Of T)(x As C1, y As C1) As C1
End Operator
End Class
]]>,
<errors>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="14" end="25"/>
<error id="32073" message="Modules cannot be generic." start="81" end="92"/>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="148" end="154"/>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="199" end="205"/>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="225" end="231"/>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="261" end="267"/>
</errors>)
Dim root = t.GetCompilationUnitRoot()
Assert.Equal("(Of T1, T2)" + vbLf, DirectCast(root.Members(0), EnumBlockSyntax).EnumStatement.Identifier.TrailingTrivia.Node.ToFullString)
Assert.Equal("(Of T1, T2)" + vbLf, DirectCast(root.Members(1), TypeBlockSyntax).BlockStatement.Identifier.TrailingTrivia.Node.ToFullString)
Dim c = DirectCast(root.Members(2), TypeBlockSyntax)
Assert.Equal("(Of T)", DirectCast(c.Members(0), ConstructorBlockSyntax).SubNewStatement.NewKeyword.TrailingTrivia.Node.ToFullString)
Assert.Equal("(Of T)" + vbLf, DirectCast(c.Members(1), PropertyStatementSyntax).Identifier.TrailingTrivia.Node.ToFullString)
Assert.Equal("(Of T)" + vbLf, DirectCast(c.Members(2), EventStatementSyntax).Identifier.TrailingTrivia.Node.ToFullString)
Assert.Equal("(Of T)", DirectCast(c.Members(3), OperatorBlockSyntax).OperatorStatement.OperatorToken.TrailingTrivia.Node.ToFullString)
End Sub
<Fact>
Public Sub ERR_NamespaceNotAllowedInScript()
Const source = "
Namespace N
End Namespace
"
Parse(source, TestOptions.Script).AssertTheseDiagnostics(<errors><![CDATA[
BC36965: You cannot declare Namespace in script code
Namespace N
~~~~~~~~~
]]></errors>)
End Sub
#End Region
End Class
| ' 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.
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
<CLSCompliant(False)>
Public Class ParseDeclarations
Inherits BasicTestBase
<WorkItem(865836, "DevDiv/Personal")>
<WorkItem(927366, "DevDiv/Personal")>
<Fact>
Public Sub ParseModuleDeclaration()
ParseAndVerify(<![CDATA[
Module Module1
End Module
]]>).
VerifyOccurrenceCount(SyntaxKind.EndOfFileToken, 1)
ParseAndVerify(<![CDATA[
Module Module1 : End Module
]]>).
VerifyOccurrenceCount(SyntaxKind.EndOfFileToken, 1)
ParseAndVerify(<![CDATA[Module Module1
End Module]]>).
VerifyOccurrenceCount(SyntaxKind.EndOfFileToken, 1)
End Sub
<Fact>
Public Sub ParseNamespaceDeclaration()
ParseAndVerify(<![CDATA[
Namespace N1
End Namespace
]]>)
ParseAndVerify(<![CDATA[
Namespace N1 : End Namespace
]]>)
End Sub
<Fact>
Public Sub ParseNamespaceDeclarationWithGlobal()
ParseAndVerify(<![CDATA[
Namespace Global.N1
End Namespace
]]>)
End Sub
<Fact>
Public Sub ParseClassDeclaration()
ParseAndVerify(<![CDATA[
Class C1
End Class
]]>)
ParseAndVerify(<![CDATA[
Class C1 : End Class
]]>)
End Sub
<Fact>
Public Sub ParseStructureDeclaration()
ParseAndVerify(<![CDATA[
Structure S1
End Structure
]]>)
ParseAndVerify(<![CDATA[
Structure S1 : End Structure
]]>)
End Sub
<Fact>
Public Sub ParseInterfaceDeclaration()
ParseAndVerify(<![CDATA[
Interface I1
End Interface
]]>)
ParseAndVerify(<![CDATA[
Interface I1 : End Interface
]]>)
End Sub
<Fact>
Public Sub ParseClassInheritsDeclaration()
ParseAndVerify(<![CDATA[
Class C1
End Class
Class C2
Inherits C1
End Class
]]>)
End Sub
<WorkItem(927384, "DevDiv/Personal")>
<Fact>
Public Sub ParseClassInheritsStatementWithSeparator()
ParseAndVerify(<![CDATA[
Class C1
End Class
Class C2 : Inherits C1
End Class
Class C3 :
Inherits C1
End Class
Class C4
: Inherits C1
End Class
Class C4 :::
:::: Inherits C1
:::: Implements QQQ
End Class
Interface I1 : End Interface
Interface I2:
Inherits I1
End Interface
Interface I3
:Inherits I1
End Interface
Interface I3::
:Inherits I1 ::
:: Inherits I2 ::
End Interface
Structure S1
:Implements I1
End Structure
Structure S2:
Implements I1
End Structure
]]>)
End Sub
<Fact>
Public Sub ParseClassImplementsDeclaration()
ParseAndVerify(<![CDATA[
Interface I1
End Interface
Class C2
Implements I1
End Class
]]>)
End Sub
<Fact>
Public Sub ParseGenericClassDeclaration()
ParseAndVerify(<![CDATA[
Class C1(of T1, T2)
End Class
]]>)
ParseAndVerify(<![CDATA[
Class C1(
of
T1,
T2
)
End Class
]]>)
End Sub
<Fact>
Public Sub ParseGenericClassAsNewDeclaration()
ParseAndVerify(<![CDATA[
Class Base
End Class
Class C1(of T1 as new)
End Class
]]>)
End Sub
<Fact>
Public Sub ParseGenericClassAsTypeDeclaration()
ParseAndVerify(<![CDATA[
Class Base
End Class
Class C1(of T1 as Base)
End Class
]]>)
End Sub
<Fact>
Public Sub ParseGenericClassAsMultipleDeclaration()
ParseAndVerify(<![CDATA[
Class Base
End Class
Class C1(of T1 as {new, Base})
End Class
]]>)
ParseAndVerify(<![CDATA[
Class Base
End Class
Class C1(of
T1 as {
new,
Base
})
End Class
]]>)
End Sub
<Fact>
Public Sub ParseEnum()
ParseAndVerify(<![CDATA[
Module Module1
enum e1
member1
member2
member3 = 100
member4
end enum
End Module
]]>)
End Sub
<Fact>
Public Sub Bug8037()
ParseAndVerify(<![CDATA[
Enum Y
::A ::B
End Enum
]]>)
ParseAndVerify(<![CDATA[
Enum Y::
::A::B:::
End Enum
]]>)
ParseAndVerify(<![CDATA[
Enum Y
A::B::: ' A: is parsed as a label
End Enum
]]>,
Diagnostic(ERRID.ERR_InvInsideEnum, "A:"))
ParseAndVerify(<![CDATA[
Enum Y:::::
A::B ' A: is parsed as a label
End Enum
]]>,
Diagnostic(ERRID.ERR_InvInsideEnum, "A:"))
End Sub
<Fact>
Public Sub Bug862490()
ParseAndVerify(<![CDATA[
Interface I1
End Interface
Interface I2
Inherits I1
End Interface
]]>)
End Sub
<Fact>
Public Sub Bug863541()
ParseAndVerify(<![CDATA[
Class Class1(Of Type)
End Class
]]>)
End Sub
<Fact>
Public Sub Bug866559()
ParseAndVerify(<![CDATA[
Interface IVariance1(Of Out)
End Interface
]]>)
End Sub
<Fact>
Public Sub Bug866616()
ParseAndVerify(<![CDATA[
Module Module1
Dim x = from i in ""
End Module
]]>).
VerifyOccurrenceCount(SyntaxKind.EmptyStatement, 0)
End Sub
<Fact>
Public Sub Bug867063()
ParseAndVerify(<![CDATA[
Interface IVariance(Of In T, Out R) : : End Interface
]]>)
End Sub
<Fact>
Public Sub Bug868402()
'Tree does not round-trip for generic type parameter list with newlines
ParseAndVerify(<![CDATA[
Interface IVariance1(Of Out
)
End Interface
]]>)
End Sub
<WorkItem(873467, "DevDiv/Personal")>
<Fact>
Public Sub ParseInterfaceBasesDeclaration()
ParseAndVerify(<![CDATA[
Interface I1 : End Interface
Interface I2 : End Interface
Interface I3
Inherits I1, I2
End Interface
]]>)
ParseAndVerify(<![CDATA[
Interface I1 : End Interface
Interface I2 : End Interface
Class C1
Implements I1, I2
End Class
]]>)
ParseAndVerify(<![CDATA[
Interface I1 : End Interface
Interface I2 : End Interface
Structure S1
Implements I1, I2
End Structure
]]>)
End Sub
<WorkItem(882976, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaInFieldInitializer()
ParseAndVerify(<![CDATA[
Class Class1
Dim x = Sub() Console.WriteLine()
Dim y As Integer = 3
End Class
]]>)
End Sub
<WorkItem(869140, "DevDiv/Personal")>
<Fact>
Public Sub ParseInterfaceSingleLine()
ParseAndVerify(<![CDATA[
Interface IVariance(Of Out T) : Function Goo() As T : End Interface
]]>)
End Sub
<WorkItem(889005, "DevDiv/Personal")>
<Fact>
Public Sub ParseErrorsInvalidEndFunctionAndExecutableAsDeclaration()
ParseAndVerify(<![CDATA[
Class Class1
Dim x32 As Object = Sub() Call Function()
Return New Exception
Return New Exception
End Function
Dim x43 As Object = CType(Function()
Return Nothing
End Function, Action(Of Long))
End Class
]]>)
End Sub
<WorkItem(917197, "DevDiv/Personal")>
<Fact>
Public Sub TraverseEmptyBlocks()
ParseAndVerify(
"Module M1" & vbCrLf &
"Sub Goo" & vbCrLf &
"Try" & vbCrLf &
"Catch" & vbCrLf &
"Finally" & vbCrLf &
"End Try" & vbCrLf &
"End Sub" & vbCrLf &
"End Module"
).
TraverseAllNodes()
End Sub
<WorkItem(527076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527076")>
<Fact>
Public Sub ParseMustOverrideInsideModule()
ParseAndVerify(<![CDATA[
Module M1
Mustoverride Sub Goo()
End Sub
End Module
]]>, <errors>
<error id="30429" message="'End Sub' must be preceded by a matching 'Sub'." start="34" end="41"/>
</errors>)
End Sub
<Fact>
Public Sub ParseVariousOrderingOfDeclModifiers()
ParseAndVerify(<![CDATA[
Public MustInherit Class A
MustInherit Private Class B
Public MustOverride Function Func() As Integer
MustOverride Protected Property Prop As String
End Class
End Class
]]>)
End Sub
<Fact>
Public Sub ParseIncompleteMemberBecauseOfAttributeAndOrModifiers()
ParseAndVerify(<![CDATA[
Public Class C1
<Obsolete1()>
goo
<Obsolete2()>
if true then :
Public ' 1
<Obsolete3()>
Public ' 2
<Obsolete4()>
Public Shared with
Public Shared with if SyncLock
Public Shared Sub Main()
End Sub
End Class
]]>, <errors>
<error id="32035"/>
<error id="32035"/>
<error id="30203"/>
<error id="30203"/>
<error id="32035"/>
<error id="30183"/>
<error id="30183"/>
</errors>)
End Sub
<WorkItem(543607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543607")>
<Fact()>
Public Sub ParseInheritsAtInvalidLocation()
ParseAndVerify(<![CDATA[
Class Scen24
Dim i = Sub(a as Integer, b as Long)
Inherits Scen23
End Sub
End Class
]]>, <errors>
<error id="30024"/>
</errors>)
End Sub
#Region "Parser Error Tests"
<WorkItem(866455, "DevDiv/Personal")>
<Fact>
Public Sub BC30001ERR_NoParseError()
ParseAndVerify(<![CDATA[
Property Goo As Integer
Namespace Namespace1
End Namespace
]]>)
End Sub
<WorkItem(863086, "DevDiv/Personal")>
<Fact>
Public Sub BC30025ERR_EndProp()
ParseAndVerify(<![CDATA[
Structure Struct1
Default Public Property Goo(ByVal x) As Integer
End Function
End Structure
]]>,
<errors>
<error id="30430"/>
<error id="30634"/>
<error id="30025"/>
</errors>)
End Sub
<WorkItem(527022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527022")>
<Fact()>
Public Sub BC30037ERR_IllegalChar_TypeParamMissingAsCommaOrRParen()
ParseAndVerify(<![CDATA[
Class Class1(of ])
End Class
]]>,
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_TypeParamMissingAsCommaOrRParen, ""),
Diagnostic(ERRID.ERR_IllegalChar, "]"))
End Sub
<WorkItem(888046, "DevDiv/Personal")>
<Fact>
Public Sub BC30184ERR_InvalidEndEnum()
ParseAndVerify(<![CDATA[
Enum myenum
x
Shared Narrowing Operator CType(ByVal x As Integer) As c2
Return New c2
End Operator
End Enum
]]>,
Diagnostic(ERRID.ERR_MissingEndEnum, "Enum myenum"),
Diagnostic(ERRID.ERR_InvInsideEndsEnum, "Shared Narrowing Operator CType(ByVal x As Integer) As c2"),
Diagnostic(ERRID.ERR_InvalidEndEnum, "End Enum"))
End Sub
<WorkItem(869144, "DevDiv/Personal")>
<Fact>
Public Sub BC30185ERR_MissingEndEnum()
' Tree loses text when access modifier used on Enum member
ParseAndVerify(<![CDATA[
Enum Access1
Orange
Public Red = 2
End Enum
]]>,
<errors>
<error id="30185"/>
<error id="30619"/>
<error id="30184"/>
</errors>)
End Sub
<WorkItem(863528, "DevDiv/Personal")>
<Fact>
Public Sub BC30188ERR_ExpectedDeclaration()
ParseAndVerify(<![CDATA[
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
Persistable = 0 'NotPersistable
DataBindingBehavior = 0 'vbNone
DataSourceBehavior = 0 'vbNone
MTSTransactionMode = 0 'NotAnMTSObject
END
Attribute VB_Name = "Class1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Public v As Variant
]]>,
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "VERSION 1.0 CLASS"),
Diagnostic(ERRID.ERR_ObsoleteArgumentsNeedParens, "1.0 CLASS"),
Diagnostic(ERRID.ERR_ArgumentSyntax, "CLASS"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "BEGIN"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "MultiUse = -1"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Persistable = 0"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "DataBindingBehavior = 0"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "DataSourceBehavior = 0"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "MTSTransactionMode = 0"),
Diagnostic(ERRID.ERR_UnrecognizedEnd, "END"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_Name = ""Class1"""),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_GlobalNameSpace = False"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_Creatable = True"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_PredeclaredId = False"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ExpectedSpecifier, "VB_Exposed = True"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Attribute"),
Diagnostic(ERRID.ERR_ObsoleteObjectNotVariant, "Variant"))
End Sub
<Fact>
Public Sub BC30193ERR_SpecifiersInvalidOnInheritsImplOpt()
ParseAndVerify(<![CDATA[
Class C
<A> Inherits B
End Class
]]>,
<errors>
<error id="30193"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
<A> Implements I
End Class
]]>,
<errors>
<error id="30193"/>
</errors>)
End Sub
<WorkItem(863112, "DevDiv/Personal")>
<Fact>
Public Sub BC30193ERR_SpecifiersInvalidOnInheritsImplOpt_2()
ParseAndVerify(<![CDATA[
<System.Runtime.CompilerServices.Extension()> Namespace ExtensionAttributeNamespace01
End Namespace
]]>,
<errors>
<error id="30193"/>
</errors>)
End Sub
<WorkItem(887502, "DevDiv/Personal")>
<Fact>
Public Sub BC30193_MismatchEndNoNamespace()
ParseAndVerify(<![CDATA[
<System.Runtime.CompilerServices.CompilationRelaxations(Runtime.CompilerServices.CompilationRelaxations.NoStringInterning)> _
Namespace CompilerRelaxations02
End Namespace
]]>,
<errors>
<error id="30193"/>
</errors>)
End Sub
<Fact>
Public Sub BC30193_ParseInterfaceInherits()
ParseAndVerify(<![CDATA[
interface i
public inherits i2
end interface
]]>,
<errors>
<error id="30193"/>
</errors>)
End Sub
<WorkItem(889075, "DevDiv/Personal")>
<Fact>
Public Sub BC30201ERR_ExpectedExpression_InvInsideEndsEnumAndMissingEndEnum()
ParseAndVerify(<![CDATA[
Module Module1
Enum byteenum As Byte
a = 200
b =
End Enum
Enum sbyteenum As SByte
c
d
End Enum
End Module
]]>,
<errors>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(889301, "DevDiv/Personal")>
<Fact>
Public Sub BC30203ERR_ExpectedIdentifier_ParasExtraError30213()
' Expected error 30203: Identifier expected.
' Was also reporting 30213.
ParseAndVerify(<![CDATA[
Friend Class cTest
Sub Sub1 (0 To 10)
End Sub
End Class
]]>,
<errors>
<error id="30203"/>
</errors>)
End Sub
<Fact>
Public Sub BC30205ERR_ExpectedEOS_NamespaceDeclarationWithGeneric()
ParseAndVerify(<![CDATA[
Namespace N1.N2(of T)
End Namespace
]]>,
<errors>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(894067, "DevDiv/Personal")>
<Fact>
Public Sub BC30213ERR_InvalidParameterSyntax_DollarAutoProp()
ParseAndVerify(<![CDATA[
Property Scen4(
p1 as vb$anonymous1
) a
]]>,
Diagnostic(ERRID.ERR_InvalidParameterSyntax, "anonymous1"),
Diagnostic(ERRID.ERR_AutoPropertyCantHaveParams, <![CDATA[(
p1 as vb$anonymous1
)]]>))
End Sub
<Fact>
Public Sub BC30363ERR_NewInInterface_InterfaceWithSubNew()
ParseAndVerify(<![CDATA[
Interface i
Sub new ()
End Interface
]]>,
<errors>
<error id="30363"/>
</errors>)
End Sub
<WorkItem(887748, "DevDiv/Personal")>
<WorkItem(889062, "DevDiv/Personal")>
<WorkItem(538919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538919")>
<Fact>
Public Sub BC30602ERR_InterfaceMemberSyntax_TypeStatement()
ParseAndVerify(<![CDATA[
interface i1
dim i as integer
End interface
Interface Scen1
type dd
End Interface
Interface il
_loc as object
End Interface
]]>,
<errors>
<error id="30188"/>
<error id="30602"/>
<error id="30802"/>
</errors>)
End Sub
<WorkItem(887508, "DevDiv/Personal")>
<Fact>
Public Sub BC30603ERR_InvInsideInterface_ParseInterfaceWithSubWithEndSub()
ParseAndVerify(<![CDATA[
Interface i1
Sub goo()
end sub
End Interface
]]>,
<errors>
<error id="30603"/>
</errors>)
End Sub
<Fact>
Public Sub BC30618ERR_NamespaceNotAtNamespace_ModuleNamespaceClassDeclaration()
ParseAndVerify(<![CDATA[
Namespace N1
Module M1
Class A
End Class
End Module
End Namespace
]]>)
ParseAndVerify(<![CDATA[
Module Module1
Namespace N1
Class A
End Class
End Namespace
End Module
]]>,
<errors>
<error id=<%= CInt(ERRID.ERR_ExpectedEndModule) %>/>
<error id=<%= CInt(ERRID.ERR_NamespaceNotAtNamespace) %>/>
<error id=<%= CInt(ERRID.ERR_EndModuleNoModule) %>/>
</errors>)
End Sub
<WorkItem(862508, "DevDiv/Personal")>
<Fact>
Public Sub BC30624ERR_ExpectedEndStructure()
ParseAndVerify(<![CDATA[
Structure Struct1
]]>,
<errors>
<error id="30624"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30625ERR_ExpectedEndModule()
ParseAndVerify(<![CDATA[
Module M1
]]>,
<errors>
<error id="30625"/>
</errors>)
End Sub
<Fact>
Public Sub BC30626ERR_ExpectedEndNamespace_ModuleNamespaceClassMissingEnd1()
ParseAndVerify(<![CDATA[
Module Module1
Namespace N1
Class A
End Module
]]>,
<errors>
<error id=<%= CInt(ERRID.ERR_ExpectedEndModule) %>/>
<error id=<%= CInt(ERRID.ERR_NamespaceNotAtNamespace) %>/>
<error id=<%= CInt(ERRID.ERR_ExpectedEndNamespace) %>/>
<error id=<%= CInt(ERRID.ERR_ExpectedEndClass) %>/>
<error id=<%= CInt(ERRID.ERR_EndModuleNoModule) %>/>
</errors>)
End Sub
<Fact>
Public Sub NamespaceOutOfPlace()
ParseAndVerify(<![CDATA[
Module Module1
Class C1
Namespace N1
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'." start="17" end="31"/>
<error id="30481" message="'Class' statement must end with a matching 'End Class'." start="52" end="60"/>
<error id="30618" message="'Namespace' statements can occur only at file or namespace level." start="85" end="97"/>
<error id="30626" message="'Namespace' statement must end with a matching 'End Namespace'." start="85" end="97"/>
</errors>)
ParseAndVerify(<![CDATA[
Module Module1
Sub S1()
Namespace N1
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'." start="17" end="31"/>
<error id="30026" message="'End Sub' expected." start="52" end="60"/>
<error id="30289" message="Statement cannot appear within a method body. End of method assumed." start="85" end="97"/>
<error id="30626" message="'Namespace' statement must end with a matching 'End Namespace'." start="85" end="97"/>
</errors>)
End Sub
<WorkItem(888556, "DevDiv/Personal")>
<Fact>
Public Sub BC30984ERR_ExpectedAssignmentOperatorInInit_AndExpectedRbrace()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
Dim scen2b = New With {.prop = 10, .321prop = 9, .567abc = -10}
Dim scen3 = New With {.$123prop=1}
End Sub
End Module
]]>,
<errors>
<error id="36576"/>
<error id="36576"/>
<error id="30203"/>
<error id="30984"/>
<error id="30201"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(888560, "DevDiv/Personal")>
<Fact>
Public Sub BC30987ERR_ExpectedLbrace_EndNoModuleAndModuleNotAtNamespaceAndExpectedEndClass()
ParseAndVerify(<![CDATA[
Namespace scen8
Class customer
End Class
Class c1
public x as new customer with
End Class
Module m
Sub test()
End Sub
End Module
End Namespace
]]>,
<errors>
<error id="30987"/>
</errors>)
End Sub
<WorkItem(889038, "DevDiv/Personal")>
<Fact>
Public Sub BC31111ERR_ExitEventMemberNotInvalid_ExpectedExitKindAndSubOfFuncAndExpectedExitKind()
ParseAndVerify(<![CDATA[
Friend Class cTest
Friend Delegate Sub fir()
Friend Custom Event e As fir
AddHandler(ByVal value As fir)
exit addhandler
End AddHandler
RemoveHandler(ByVal value As fir)
exit removehandler
End RemoveHandler
RaiseEvent()
exit raiseevent
End RaiseEvent
End Event
End Class
]]>,
<errors>
<error id="31111"/>
<error id="31111"/>
<error id="31111"/>
</errors>)
End Sub
<WorkItem(536278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536278")>
<Fact>
Public Sub BC31140ERR_InvalidUseOfCustomModifier_ExpectedSpecifierAndInvalidEndSub()
ParseAndVerify(<![CDATA[
Module Module1
Custom sub goo()
End Sub
End Module
]]>,
<errors>
<error id="30195"/>
<error id="31140"/>
<error id="30429"/>
</errors>)
End Sub
<Fact>
Public Sub BC32100ERR_TypeParamMissingAsCommaOrRParen_GenericClassMissingComma()
ParseAndVerify(<![CDATA[
class B(of a b)
end class
]]>,
<errors>
<error id="32100"/>
</errors>)
End Sub
<Fact>
Public Sub Bug863497()
ParseAndVerify(<![CDATA[
Namespace $safeitemname$
Public Module $safeitemname$
End Module
End Namespace
]]>,
<errors>
<error id="30203"/>
<error id="30037"/>
<error id="30203"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(538990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538990")>
<Fact>
Public Sub Bug4770()
ParseAndVerify(<![CDATA[
interface i1
dim i as integer
End interface
]]>, <errors>
<error id="30602"/>
</errors>)
End Sub
<WorkItem(539509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539509")>
<Fact>
Public Sub EnumsWithGenericParameter()
' Enums should recover the same was as other declarations that do not allow generics.
Dim t = ParseAndVerify(<![CDATA[
enum e(Of T1, T2)
red
end enum
Module Program(Of T1, T2)
End Module
Class C
Sub New(Of T)()
End Sub
Property P(Of T)
Event e(Of T)
Shared Operator +(Of T)(x As C1, y As C1) As C1
End Operator
End Class
]]>,
<errors>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="14" end="25"/>
<error id="32073" message="Modules cannot be generic." start="81" end="92"/>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="148" end="154"/>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="199" end="205"/>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="225" end="231"/>
<error id="32065" message="Type parameters cannot be specified on this declaration." start="261" end="267"/>
</errors>)
Dim root = t.GetCompilationUnitRoot()
Assert.Equal("(Of T1, T2)" + vbLf, DirectCast(root.Members(0), EnumBlockSyntax).EnumStatement.Identifier.TrailingTrivia.Node.ToFullString)
Assert.Equal("(Of T1, T2)" + vbLf, DirectCast(root.Members(1), TypeBlockSyntax).BlockStatement.Identifier.TrailingTrivia.Node.ToFullString)
Dim c = DirectCast(root.Members(2), TypeBlockSyntax)
Assert.Equal("(Of T)", DirectCast(c.Members(0), ConstructorBlockSyntax).SubNewStatement.NewKeyword.TrailingTrivia.Node.ToFullString)
Assert.Equal("(Of T)" + vbLf, DirectCast(c.Members(1), PropertyStatementSyntax).Identifier.TrailingTrivia.Node.ToFullString)
Assert.Equal("(Of T)" + vbLf, DirectCast(c.Members(2), EventStatementSyntax).Identifier.TrailingTrivia.Node.ToFullString)
Assert.Equal("(Of T)", DirectCast(c.Members(3), OperatorBlockSyntax).OperatorStatement.OperatorToken.TrailingTrivia.Node.ToFullString)
End Sub
<Fact>
Public Sub ERR_NamespaceNotAllowedInScript()
Const source = "
Namespace N
End Namespace
"
Parse(source, TestOptions.Script).AssertTheseDiagnostics(<errors><![CDATA[
BC36965: You cannot declare Namespace in script code
Namespace N
~~~~~~~~~
]]></errors>)
End Sub
#End Region
End Class
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/ExpressionEvaluator/CSharp/Test/ResultProvider/Properties/launchSettings.json | {
"profiles": {
"xUnit.net Console (32-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
},
"xUnit.net Console (64-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
}
}
} | {
"profiles": {
"xUnit.net Console (32-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
},
"xUnit.net Console (64-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
}
}
} | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/Resources/WindowsProxy.winmd | MZ @ !L!This program cannot be run in DOS mode.
$ PE L f$
T " 0 # @ @ `# O @ ` H .text `.rsrc @ @ @.reloc `
@ B # H P BSJB $ WindowsRuntime 1.3;CLR v4.0.30319 #~ L #Strings #US ( #GUID 8 #Blob 3 D d 0
. . . !
" <Module> mscorlib Windows.winmd System.Runtime DebuggableAttribute CompilationRelaxationsAttribute RuntimeCompatibilityAttribute .ctor System.Diagnostics System.Runtime.CompilerServices DebuggingModes Windows 'hB-b ?_
:z\V4G8|-,u"fe.,1_TOteX3oi oGk( 4R)γ?R[z
q:XqHe[{X3I*g TWrapNonExceptionThrows # # # _CorDllMain mscoree.dll % 0 H X@ D D4 V S _ V E R S I O N _ I N F O ? D V a r F i l e I n f o $ T r a n s l a t i o n S t r i n g F i l e I n f o 0 0 0 0 0 4 b 0 , F i l e D e s c r i p t i o n 0 F i l e V e r s i o n 0 . 0 . 0 . 0 8 I n t e r n a l N a m e W i n d o w s . o b j ( L e g a l C o p y r i g h t @ O r i g i n a l F i l e n a m e W i n d o w s . o b j 4 P r o d u c t V e r s i o n 0 . 0 . 0 . 0 8 A s s e m b l y V e r s i o n 0 . 0 . 0 . 0 3 | MZ @ !L!This program cannot be run in DOS mode.
$ PE L f$
T " 0 # @ @ `# O @ ` H .text `.rsrc @ @ @.reloc `
@ B # H P BSJB $ WindowsRuntime 1.3;CLR v4.0.30319 #~ L #Strings #US ( #GUID 8 #Blob 3 D d 0
. . . !
" <Module> mscorlib Windows.winmd System.Runtime DebuggableAttribute CompilationRelaxationsAttribute RuntimeCompatibilityAttribute .ctor System.Diagnostics System.Runtime.CompilerServices DebuggingModes Windows 'hB-b ?_
:z\V4G8|-,u"fe.,1_TOteX3oi oGk( 4R)γ?R[z
q:XqHe[{X3I*g TWrapNonExceptionThrows # # # _CorDllMain mscoree.dll % 0 H X@ D D4 V S _ V E R S I O N _ I N F O ? D V a r F i l e I n f o $ T r a n s l a t i o n S t r i n g F i l e I n f o 0 0 0 0 0 4 b 0 , F i l e D e s c r i p t i o n 0 F i l e V e r s i o n 0 . 0 . 0 . 0 8 I n t e r n a l N a m e W i n d o w s . o b j ( L e g a l C o p y r i g h t @ O r i g i n a l F i l e n a m e W i n d o w s . o b j 4 P r o d u c t V e r s i o n 0 . 0 . 0 . 0 8 A s s e m b l y V e r s i o n 0 . 0 . 0 . 0 3 | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/Test/Resources/Core/SymbolsTests/netModule/netModule1.vb | ' 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.
'vbc /t:module /vbruntime- netModule1.vb
Public Class Class1
Public Class Class3
Private Class Class5
End Class
End Class
End Class
Namespace NS1
Public Class Class4
Private Class Class6
End Class
Public Class Class7
End Class
End Class
Friend Class Class8
End Class
End Namespace
| ' 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.
'vbc /t:module /vbruntime- netModule1.vb
Public Class Class1
Public Class Class3
Private Class Class5
End Class
End Class
End Class
Namespace NS1
Public Class Class4
Private Class Class6
End Class
Public Class Class7
End Class
End Class
Friend Class Class8
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicExtractMethodService.vb | ' 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.
Imports System.Composition
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
<Export(GetType(IExtractMethodService)), ExportLanguageService(GetType(IExtractMethodService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicExtractMethodService
Inherits AbstractExtractMethodService(Of VisualBasicSelectionValidator, VisualBasicMethodExtractor, VisualBasicSelectionResult)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function CreateSelectionValidator(document As SemanticDocument,
textSpan As TextSpan,
options As OptionSet) As VisualBasicSelectionValidator
Return New VisualBasicSelectionValidator(document, textSpan, options)
End Function
Protected Overrides Function CreateMethodExtractor(selectionResult As VisualBasicSelectionResult, localFunction As Boolean) As VisualBasicMethodExtractor
Return New VisualBasicMethodExtractor(selectionResult)
End Function
End Class
End Namespace
| ' 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.
Imports System.Composition
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
<Export(GetType(IExtractMethodService)), ExportLanguageService(GetType(IExtractMethodService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicExtractMethodService
Inherits AbstractExtractMethodService(Of VisualBasicSelectionValidator, VisualBasicMethodExtractor, VisualBasicSelectionResult)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function CreateSelectionValidator(document As SemanticDocument,
textSpan As TextSpan,
options As OptionSet) As VisualBasicSelectionValidator
Return New VisualBasicSelectionValidator(document, textSpan, options)
End Function
Protected Overrides Function CreateMethodExtractor(selectionResult As VisualBasicSelectionResult, localFunction As Boolean) As VisualBasicMethodExtractor
Return New VisualBasicMethodExtractor(selectionResult)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/EditorFeatures/Core.Wpf/Interactive/InteractiveWindowResetCommand.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
extern alias InteractiveHost;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Editor.Interactive;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
/// <summary>
/// Represents a reset command which can be run from a REPL window.
/// </summary>
[Export(typeof(IInteractiveWindowCommand))]
[ContentType(InteractiveWindowContentTypes.CommandContentTypeName)]
internal sealed class InteractiveWindowResetCommand : IInteractiveWindowCommand
{
private const string CommandName = "reset";
private const string NoConfigParameterName = "noconfig";
private const string PlatformCore = "core";
private const string PlatformDesktop32 = "32";
private const string PlatformDesktop64 = "64";
private const string PlatformNames = PlatformCore + "|" + PlatformDesktop32 + "|" + PlatformDesktop64;
private static readonly int s_noConfigParameterNameLength = NoConfigParameterName.Length;
private readonly IStandardClassificationService _registry;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InteractiveWindowResetCommand(IStandardClassificationService registry)
=> _registry = registry;
public string Description
=> EditorFeaturesWpfResources.Reset_the_execution_environment_to_the_initial_state_keep_history;
public IEnumerable<string> DetailedDescription
=> null;
public IEnumerable<string> Names
=> SpecializedCollections.SingletonEnumerable(CommandName);
public string CommandLine
=> "[" + NoConfigParameterName + "] [" + PlatformNames + "]";
public IEnumerable<KeyValuePair<string, string>> ParametersDescription
{
get
{
yield return new KeyValuePair<string, string>(NoConfigParameterName, EditorFeaturesWpfResources.Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script);
yield return new KeyValuePair<string, string>(PlatformNames, EditorFeaturesWpfResources.Interactive_host_process_platform);
}
}
public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments)
{
if (!TryParseArguments(arguments, out var initialize, out var platform))
{
ReportInvalidArguments(window);
return ExecutionResult.Failed;
}
var evaluator = (CSharpInteractiveEvaluator)window.Evaluator;
evaluator.ResetOptions = new InteractiveEvaluatorResetOptions(platform);
return window.Operations.ResetAsync(initialize);
}
public IEnumerable<ClassificationSpan> ClassifyArguments(ITextSnapshot snapshot, Span argumentsSpan, Span spanToClassify)
{
var arguments = snapshot.GetText(argumentsSpan);
var argumentsStart = argumentsSpan.Start;
foreach (var pos in GetNoConfigPositions(arguments))
{
var snapshotSpan = new SnapshotSpan(snapshot, new Span(argumentsStart + pos, s_noConfigParameterNameLength));
yield return new ClassificationSpan(snapshotSpan, _registry.Keyword);
}
}
/// <remarks>
/// Internal for testing.
/// </remarks>
internal static IEnumerable<int> GetNoConfigPositions(string arguments)
{
var startIndex = 0;
while (true)
{
var index = arguments.IndexOf(NoConfigParameterName, startIndex, StringComparison.Ordinal);
if (index < 0)
yield break;
if ((index == 0 || char.IsWhiteSpace(arguments[index - 1])) &&
(index + s_noConfigParameterNameLength == arguments.Length || char.IsWhiteSpace(arguments[index + s_noConfigParameterNameLength])))
{
yield return index;
}
startIndex = index + s_noConfigParameterNameLength;
}
}
/// <remarks>
/// Accessibility is internal for testing.
/// </remarks>
internal static bool TryParseArguments(string arguments, out bool initialize, out InteractiveHostPlatform? platform)
{
platform = null;
initialize = true;
var noConfigSpecified = false;
foreach (var argument in arguments.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
{
switch (argument.ToLowerInvariant())
{
case PlatformDesktop32:
if (platform != null)
{
return false;
}
platform = InteractiveHostPlatform.Desktop32;
break;
case PlatformDesktop64:
if (platform != null)
{
return false;
}
platform = InteractiveHostPlatform.Desktop64;
break;
case PlatformCore:
if (platform != null)
{
return false;
}
platform = InteractiveHostPlatform.Core;
break;
case NoConfigParameterName:
if (noConfigSpecified)
{
return false;
}
noConfigSpecified = true;
initialize = false;
break;
default:
return false;
}
}
return true;
}
internal static string GetCommandLine(bool initialize, InteractiveHostPlatform? platform)
=> CommandName + (initialize ? "" : " " + NoConfigParameterName) + platform switch
{
null => "",
InteractiveHostPlatform.Core => " " + PlatformCore,
InteractiveHostPlatform.Desktop64 => " " + PlatformDesktop64,
InteractiveHostPlatform.Desktop32 => " " + PlatformDesktop32,
_ => throw ExceptionUtilities.Unreachable
};
private void ReportInvalidArguments(IInteractiveWindow window)
{
var commands = (IInteractiveWindowCommands)window.Properties[typeof(IInteractiveWindowCommands)];
commands.DisplayCommandUsage(this, window.ErrorOutputWriter, displayDetails: 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
extern alias InteractiveHost;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Editor.Interactive;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
/// <summary>
/// Represents a reset command which can be run from a REPL window.
/// </summary>
[Export(typeof(IInteractiveWindowCommand))]
[ContentType(InteractiveWindowContentTypes.CommandContentTypeName)]
internal sealed class InteractiveWindowResetCommand : IInteractiveWindowCommand
{
private const string CommandName = "reset";
private const string NoConfigParameterName = "noconfig";
private const string PlatformCore = "core";
private const string PlatformDesktop32 = "32";
private const string PlatformDesktop64 = "64";
private const string PlatformNames = PlatformCore + "|" + PlatformDesktop32 + "|" + PlatformDesktop64;
private static readonly int s_noConfigParameterNameLength = NoConfigParameterName.Length;
private readonly IStandardClassificationService _registry;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InteractiveWindowResetCommand(IStandardClassificationService registry)
=> _registry = registry;
public string Description
=> EditorFeaturesWpfResources.Reset_the_execution_environment_to_the_initial_state_keep_history;
public IEnumerable<string> DetailedDescription
=> null;
public IEnumerable<string> Names
=> SpecializedCollections.SingletonEnumerable(CommandName);
public string CommandLine
=> "[" + NoConfigParameterName + "] [" + PlatformNames + "]";
public IEnumerable<KeyValuePair<string, string>> ParametersDescription
{
get
{
yield return new KeyValuePair<string, string>(NoConfigParameterName, EditorFeaturesWpfResources.Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script);
yield return new KeyValuePair<string, string>(PlatformNames, EditorFeaturesWpfResources.Interactive_host_process_platform);
}
}
public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments)
{
if (!TryParseArguments(arguments, out var initialize, out var platform))
{
ReportInvalidArguments(window);
return ExecutionResult.Failed;
}
var evaluator = (CSharpInteractiveEvaluator)window.Evaluator;
evaluator.ResetOptions = new InteractiveEvaluatorResetOptions(platform);
return window.Operations.ResetAsync(initialize);
}
public IEnumerable<ClassificationSpan> ClassifyArguments(ITextSnapshot snapshot, Span argumentsSpan, Span spanToClassify)
{
var arguments = snapshot.GetText(argumentsSpan);
var argumentsStart = argumentsSpan.Start;
foreach (var pos in GetNoConfigPositions(arguments))
{
var snapshotSpan = new SnapshotSpan(snapshot, new Span(argumentsStart + pos, s_noConfigParameterNameLength));
yield return new ClassificationSpan(snapshotSpan, _registry.Keyword);
}
}
/// <remarks>
/// Internal for testing.
/// </remarks>
internal static IEnumerable<int> GetNoConfigPositions(string arguments)
{
var startIndex = 0;
while (true)
{
var index = arguments.IndexOf(NoConfigParameterName, startIndex, StringComparison.Ordinal);
if (index < 0)
yield break;
if ((index == 0 || char.IsWhiteSpace(arguments[index - 1])) &&
(index + s_noConfigParameterNameLength == arguments.Length || char.IsWhiteSpace(arguments[index + s_noConfigParameterNameLength])))
{
yield return index;
}
startIndex = index + s_noConfigParameterNameLength;
}
}
/// <remarks>
/// Accessibility is internal for testing.
/// </remarks>
internal static bool TryParseArguments(string arguments, out bool initialize, out InteractiveHostPlatform? platform)
{
platform = null;
initialize = true;
var noConfigSpecified = false;
foreach (var argument in arguments.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
{
switch (argument.ToLowerInvariant())
{
case PlatformDesktop32:
if (platform != null)
{
return false;
}
platform = InteractiveHostPlatform.Desktop32;
break;
case PlatformDesktop64:
if (platform != null)
{
return false;
}
platform = InteractiveHostPlatform.Desktop64;
break;
case PlatformCore:
if (platform != null)
{
return false;
}
platform = InteractiveHostPlatform.Core;
break;
case NoConfigParameterName:
if (noConfigSpecified)
{
return false;
}
noConfigSpecified = true;
initialize = false;
break;
default:
return false;
}
}
return true;
}
internal static string GetCommandLine(bool initialize, InteractiveHostPlatform? platform)
=> CommandName + (initialize ? "" : " " + NoConfigParameterName) + platform switch
{
null => "",
InteractiveHostPlatform.Core => " " + PlatformCore,
InteractiveHostPlatform.Desktop64 => " " + PlatformDesktop64,
InteractiveHostPlatform.Desktop32 => " " + PlatformDesktop32,
_ => throw ExceptionUtilities.Unreachable
};
private void ReportInvalidArguments(IInteractiveWindow window)
{
var commands = (IInteractiveWindowCommands)window.Properties[typeof(IInteractiveWindowCommands)];
commands.DisplayCommandUsage(this, window.ErrorOutputWriter, displayDetails: false);
}
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/Test/Resources/Core/SymbolsTests/With Spaces.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L CN ! >% @ @ ` @ $ O @ H .text D `.reloc @ @ B % H X (
*BSJB v4.0.30319 l | #~ #Strings #US #GUID #Blob G %3
0 G d
, iI I P ! ) 1 9 A I
Q Y a i . . . . # . . + 4 . 3 . ; C . C . . K . . S d . [ . c . k <Module> System Object .ctor System.Reflection AssemblyTitleAttribute AssemblyDescriptionAttribute AssemblyConfigurationAttribute AssemblyCompanyAttribute AssemblyProductAttribute AssemblyCopyrightAttribute AssemblyTrademarkAttribute System.Runtime.InteropServices ComVisibleAttribute GuidAttribute AssemblyFileVersionAttribute System.Runtime.CompilerServices CompilationRelaxationsAttribute RuntimeCompatibilityAttribute With Spaces.dll mscorlib C With Spaces =a'oH+ z\V4 With Spaces Microsoft Copyright © Microsoft 2011 ) $caf2f15b-96b4-4f58-8386-2bc2437487d3 1.0.0.0 TWrapNonExceptionThrows % .% % _CorDllMain mscoree.dll % @ @5 | MZ @ !L!This program cannot be run in DOS mode.
$ PE L CN ! >% @ @ ` @ $ O @ H .text D `.reloc @ @ B % H X (
*BSJB v4.0.30319 l | #~ #Strings #US #GUID #Blob G %3
0 G d
, iI I P ! ) 1 9 A I
Q Y a i . . . . # . . + 4 . 3 . ; C . C . . K . . S d . [ . c . k <Module> System Object .ctor System.Reflection AssemblyTitleAttribute AssemblyDescriptionAttribute AssemblyConfigurationAttribute AssemblyCompanyAttribute AssemblyProductAttribute AssemblyCopyrightAttribute AssemblyTrademarkAttribute System.Runtime.InteropServices ComVisibleAttribute GuidAttribute AssemblyFileVersionAttribute System.Runtime.CompilerServices CompilationRelaxationsAttribute RuntimeCompatibilityAttribute With Spaces.dll mscorlib C With Spaces =a'oH+ z\V4 With Spaces Microsoft Copyright © Microsoft 2011 ) $caf2f15b-96b4-4f58-8386-2bc2437487d3 1.0.0.0 TWrapNonExceptionThrows % .% % _CorDllMain mscoree.dll % @ @5 | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/CSharp/Portable/Symbols/SymbolVisitor.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;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract class CSharpSymbolVisitor
{
public virtual void Visit(Symbol symbol)
{
if ((object)symbol != null)
{
symbol.Accept(this);
}
}
public virtual void DefaultVisit(Symbol symbol)
{
}
public virtual void VisitAlias(AliasSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitArrayType(ArrayTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitAssembly(AssemblySymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitDynamicType(DynamicTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitDiscard(DiscardSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitEvent(EventSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitField(FieldSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitLabel(LabelSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitLocal(LocalSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitMethod(MethodSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitModule(ModuleSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitNamedType(NamedTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitNamespace(NamespaceSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitParameter(ParameterSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitPointerType(PointerTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitFunctionPointerType(FunctionPointerTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitProperty(PropertySymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitRangeVariable(RangeVariableSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitTypeParameter(TypeParameterSymbol symbol)
{
DefaultVisit(symbol);
}
}
}
| // 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;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract class CSharpSymbolVisitor
{
public virtual void Visit(Symbol symbol)
{
if ((object)symbol != null)
{
symbol.Accept(this);
}
}
public virtual void DefaultVisit(Symbol symbol)
{
}
public virtual void VisitAlias(AliasSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitArrayType(ArrayTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitAssembly(AssemblySymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitDynamicType(DynamicTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitDiscard(DiscardSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitEvent(EventSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitField(FieldSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitLabel(LabelSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitLocal(LocalSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitMethod(MethodSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitModule(ModuleSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitNamedType(NamedTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitNamespace(NamespaceSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitParameter(ParameterSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitPointerType(PointerTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitFunctionPointerType(FunctionPointerTypeSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitProperty(PropertySymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitRangeVariable(RangeVariableSymbol symbol)
{
DefaultVisit(symbol);
}
public virtual void VisitTypeParameter(TypeParameterSymbol symbol)
{
DefaultVisit(symbol);
}
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Features/VisualBasic/Portable/IntroduceVariable/VisualBasicIntroduceVariableService_IntroduceQueryLocal.vb | ' 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.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable
Partial Friend Class VisualBasicIntroduceVariableService
Protected Overrides Function IntroduceQueryLocalAsync(
document As SemanticDocument,
expression As ExpressionSyntax,
allOccurrences As Boolean,
cancellationToken As CancellationToken) As Task(Of Document)
Dim oldOutermostQuery = expression.GetAncestorsOrThis(Of QueryExpressionSyntax)().LastOrDefault()
Dim newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant:=False,
containerOpt:=oldOutermostQuery, cancellationToken:=cancellationToken)
Dim newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken)
Dim letClause = SyntaxFactory.LetClause(
SyntaxFactory.ExpressionRangeVariable(
SyntaxFactory.VariableNameEquals(
SyntaxFactory.ModifiedIdentifier(newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()))),
expression)).WithAdditionalAnnotations(Formatter.Annotation)
Dim matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken)
Dim innermostClauses = New HashSet(Of QueryClauseSyntax)(
matches.Select(Function(expr) expr.GetAncestor(Of QueryClauseSyntax)()))
If innermostClauses.Count = 1 Then
' 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))
End If
Dim oldInnerMostCommonQuery = matches.FindInnermostCommonNode(Of QueryExpressionSyntax)()
Dim newInnerMostQuery = Rewrite(document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken)
Dim allAffectedClauses = New HashSet(Of QueryClauseSyntax)(
matches.SelectMany(Function(expr) expr.GetAncestorsOrThis(Of QueryClauseSyntax)()))
Dim oldClauses = oldInnerMostCommonQuery.Clauses
Dim newClauses = newInnerMostQuery.Clauses
Dim firstClauseAffectedInQuery = oldClauses.First(AddressOf allAffectedClauses.Contains)
Dim firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery)
Dim finalClauses = newClauses.Take(firstClauseAffectedIndex).
Concat(letClause).
Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList()
Dim finalQuery = newInnerMostQuery.WithClauses(SyntaxFactory.List(finalClauses))
Dim newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery)
Return Task.FromResult(document.Document.WithSyntaxRoot(newRoot))
End Function
Private Function IntroduceQueryLocalForSingleOccurrence(
document As SemanticDocument,
expression As ExpressionSyntax,
newLocalName As NameSyntax,
letClause As LetClauseSyntax,
allOccurrences As Boolean,
cancellationToken As CancellationToken) As Document
Dim oldClause = expression.GetAncestor(Of QueryClauseSyntax)()
Dim newClause = Rewrite(document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken)
Dim oldQuery = DirectCast(oldClause.Parent, QueryExpressionSyntax)
Dim newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause)
Dim newRoot = document.Root.ReplaceNode(oldQuery, newQuery)
Return document.Document.WithSyntaxRoot(newRoot)
End Function
Private Shared Function GetNewQuery(
oldQuery As QueryExpressionSyntax,
oldClause As QueryClauseSyntax,
newClause As QueryClauseSyntax,
letClause As LetClauseSyntax) As QueryExpressionSyntax
Dim oldClauses = oldQuery.Clauses
Dim oldClauseIndex = oldClauses.IndexOf(oldClause)
Dim newClauses = oldClauses.Take(oldClauseIndex).
Concat(letClause).
Concat(newClause).
Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList()
Return oldQuery.WithClauses(SyntaxFactory.List(newClauses))
End Function
End Class
End Namespace
| ' 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.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable
Partial Friend Class VisualBasicIntroduceVariableService
Protected Overrides Function IntroduceQueryLocalAsync(
document As SemanticDocument,
expression As ExpressionSyntax,
allOccurrences As Boolean,
cancellationToken As CancellationToken) As Task(Of Document)
Dim oldOutermostQuery = expression.GetAncestorsOrThis(Of QueryExpressionSyntax)().LastOrDefault()
Dim newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant:=False,
containerOpt:=oldOutermostQuery, cancellationToken:=cancellationToken)
Dim newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken)
Dim letClause = SyntaxFactory.LetClause(
SyntaxFactory.ExpressionRangeVariable(
SyntaxFactory.VariableNameEquals(
SyntaxFactory.ModifiedIdentifier(newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()))),
expression)).WithAdditionalAnnotations(Formatter.Annotation)
Dim matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken)
Dim innermostClauses = New HashSet(Of QueryClauseSyntax)(
matches.Select(Function(expr) expr.GetAncestor(Of QueryClauseSyntax)()))
If innermostClauses.Count = 1 Then
' 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))
End If
Dim oldInnerMostCommonQuery = matches.FindInnermostCommonNode(Of QueryExpressionSyntax)()
Dim newInnerMostQuery = Rewrite(document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken)
Dim allAffectedClauses = New HashSet(Of QueryClauseSyntax)(
matches.SelectMany(Function(expr) expr.GetAncestorsOrThis(Of QueryClauseSyntax)()))
Dim oldClauses = oldInnerMostCommonQuery.Clauses
Dim newClauses = newInnerMostQuery.Clauses
Dim firstClauseAffectedInQuery = oldClauses.First(AddressOf allAffectedClauses.Contains)
Dim firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery)
Dim finalClauses = newClauses.Take(firstClauseAffectedIndex).
Concat(letClause).
Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList()
Dim finalQuery = newInnerMostQuery.WithClauses(SyntaxFactory.List(finalClauses))
Dim newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery)
Return Task.FromResult(document.Document.WithSyntaxRoot(newRoot))
End Function
Private Function IntroduceQueryLocalForSingleOccurrence(
document As SemanticDocument,
expression As ExpressionSyntax,
newLocalName As NameSyntax,
letClause As LetClauseSyntax,
allOccurrences As Boolean,
cancellationToken As CancellationToken) As Document
Dim oldClause = expression.GetAncestor(Of QueryClauseSyntax)()
Dim newClause = Rewrite(document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken)
Dim oldQuery = DirectCast(oldClause.Parent, QueryExpressionSyntax)
Dim newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause)
Dim newRoot = document.Root.ReplaceNode(oldQuery, newQuery)
Return document.Document.WithSyntaxRoot(newRoot)
End Function
Private Shared Function GetNewQuery(
oldQuery As QueryExpressionSyntax,
oldClause As QueryClauseSyntax,
newClause As QueryClauseSyntax,
letClause As LetClauseSyntax) As QueryExpressionSyntax
Dim oldClauses = oldQuery.Clauses
Dim oldClauseIndex = oldClauses.IndexOf(oldClause)
Dim newClauses = oldClauses.Take(oldClauseIndex).
Concat(letClause).
Concat(newClause).
Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList()
Return oldQuery.WithClauses(SyntaxFactory.List(newClauses))
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/VisualStudio/Core/Def/Interactive/ScriptingOleCommandTarget.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;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
/// <summary>
/// This command target routes commands in interactive window, .csx files and also interactive
/// commands in .cs files.
/// </summary>
internal sealed class ScriptingOleCommandTarget : AbstractOleCommandTarget
{
internal ScriptingOleCommandTarget(
IWpfTextView wpfTextView,
IComponentModel componentModel)
: base(wpfTextView, componentModel)
{
}
protected override ITextBuffer? GetSubjectBufferContainingCaret()
{
var result = WpfTextView.GetBufferContainingCaret(contentType: ContentTypeNames.RoslynContentType);
if (result == null)
{
result = WpfTextView.GetBufferContainingCaret(contentType: PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
}
return 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.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
/// <summary>
/// This command target routes commands in interactive window, .csx files and also interactive
/// commands in .cs files.
/// </summary>
internal sealed class ScriptingOleCommandTarget : AbstractOleCommandTarget
{
internal ScriptingOleCommandTarget(
IWpfTextView wpfTextView,
IComponentModel componentModel)
: base(wpfTextView, componentModel)
{
}
protected override ITextBuffer? GetSubjectBufferContainingCaret()
{
var result = WpfTextView.GetBufferContainingCaret(contentType: ContentTypeNames.RoslynContentType);
if (result == null)
{
result = WpfTextView.GetBufferContainingCaret(contentType: PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
}
return result;
}
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/CSharp/Portable/Symbols/PublicModel/FunctionPointerTypeSymbol.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;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class FunctionPointerTypeSymbol : TypeSymbol, IFunctionPointerTypeSymbol
{
private readonly Symbols.FunctionPointerTypeSymbol _underlying;
public FunctionPointerTypeSymbol(Symbols.FunctionPointerTypeSymbol underlying, CodeAnalysis.NullableAnnotation nullableAnnotation)
: base(nullableAnnotation)
{
RoslynDebug.Assert(underlying is object);
_underlying = underlying;
}
public IMethodSymbol Signature => _underlying.Signature.GetPublicSymbol();
internal override Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying;
internal override Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying;
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
protected override void Accept(SymbolVisitor visitor)
=> visitor.VisitFunctionPointerType(this);
protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor)
where TResult : default
{
return visitor.VisitFunctionPointerType(this);
}
protected override ITypeSymbol WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
Debug.Assert(nullableAnnotation != this.NullableAnnotation);
Debug.Assert(nullableAnnotation != _underlying.DefaultNullableAnnotation);
return new FunctionPointerTypeSymbol(_underlying, nullableAnnotation);
}
}
}
| // 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;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class FunctionPointerTypeSymbol : TypeSymbol, IFunctionPointerTypeSymbol
{
private readonly Symbols.FunctionPointerTypeSymbol _underlying;
public FunctionPointerTypeSymbol(Symbols.FunctionPointerTypeSymbol underlying, CodeAnalysis.NullableAnnotation nullableAnnotation)
: base(nullableAnnotation)
{
RoslynDebug.Assert(underlying is object);
_underlying = underlying;
}
public IMethodSymbol Signature => _underlying.Signature.GetPublicSymbol();
internal override Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying;
internal override Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying;
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
protected override void Accept(SymbolVisitor visitor)
=> visitor.VisitFunctionPointerType(this);
protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor)
where TResult : default
{
return visitor.VisitFunctionPointerType(this);
}
protected override ITypeSymbol WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
Debug.Assert(nullableAnnotation != this.NullableAnnotation);
Debug.Assert(nullableAnnotation != _underlying.DefaultNullableAnnotation);
return new FunctionPointerTypeSymbol(_underlying, nullableAnnotation);
}
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.pt-BR.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pt-BR" original="../VSPackage.resx">
<body>
<trans-unit id="110">
<source>Roslyn Diagnostics</source>
<target state="translated">Diagnóstico Roslyn</target>
<note />
</trans-unit>
<trans-unit id="112">
<source>Roslyn Diagnostics</source>
<target state="translated">Diagnóstico Roslyn</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pt-BR" original="../VSPackage.resx">
<body>
<trans-unit id="110">
<source>Roslyn Diagnostics</source>
<target state="translated">Diagnóstico Roslyn</target>
<note />
</trans-unit>
<trans-unit id="112">
<source>Roslyn Diagnostics</source>
<target state="translated">Diagnóstico Roslyn</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/Core/Portable/Compilation/NullableContext.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>
/// Represents the state of the nullable analysis at a specific point in a file. Bits one and
/// two correspond to whether the nullable feature is enabled. Bits three and four correspond
/// to whether the context was inherited from the global context.
/// </summary>
[Flags]
public enum NullableContext
{
/// <summary>
/// Nullable warnings and annotations are explicitly turned off at this location.
/// </summary>
Disabled = 0,
/// <summary>
/// Nullable warnings are enabled and will be reported at this file location.
/// </summary>
WarningsEnabled = 1,
/// <summary>
/// Nullable annotations are enabled and will be shown when APIs defined at
/// this location are used in other contexts.
/// </summary>
AnnotationsEnabled = 1 << 1,
/// <summary>
/// The nullable feature is fully enabled.
/// </summary>
Enabled = WarningsEnabled | AnnotationsEnabled,
/// <summary>
/// The nullable warning state is inherited from the project default.
/// </summary>
/// <remarks>
/// The project default can change depending on the file type. Generated
/// files have nullable off by default, regardless of the project-level
/// default setting.
/// </remarks>
WarningsContextInherited = 1 << 2,
/// <summary>
/// The nullable annotation state is inherited from the project default.
/// </summary>
/// <remarks>
/// The project default can change depending on the file type. Generated
/// files have nullable off by default, regardless of the project-level
/// default setting.
/// </remarks>
AnnotationsContextInherited = 1 << 3,
/// <summary>
/// The current state of both warnings and annotations are inherited from
/// the project default.
/// </summary>
/// <remarks>
/// This flag is set by default at the start of all files.
///
/// The project default can change depending on the file type. Generated
/// files have nullable off by default, regardless of the project-level
/// default setting.
/// </remarks>
ContextInherited = WarningsContextInherited | AnnotationsContextInherited
}
public static class NullableContextExtensions
{
private static bool IsFlagSet(NullableContext context, NullableContext flag) =>
(context & flag) == flag;
/// <summary>
/// Returns whether nullable warnings are enabled for this context.
/// </summary>
public static bool WarningsEnabled(this NullableContext context) =>
IsFlagSet(context, NullableContext.WarningsEnabled);
/// <summary>
/// Returns whether nullable annotations are enabled for this context.
/// </summary>
public static bool AnnotationsEnabled(this NullableContext context) =>
IsFlagSet(context, NullableContext.AnnotationsEnabled);
/// <summary>
/// Returns whether the nullable warning state was inherited from the project default for this file type.
/// </summary>
public static bool WarningsInherited(this NullableContext context) =>
IsFlagSet(context, NullableContext.WarningsContextInherited);
/// <summary>
/// Returns whether the nullable annotation state was inherited from the project default for this file type.
/// </summary>
public static bool AnnotationsInherited(this NullableContext context) =>
IsFlagSet(context, NullableContext.AnnotationsContextInherited);
}
}
| // 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>
/// Represents the state of the nullable analysis at a specific point in a file. Bits one and
/// two correspond to whether the nullable feature is enabled. Bits three and four correspond
/// to whether the context was inherited from the global context.
/// </summary>
[Flags]
public enum NullableContext
{
/// <summary>
/// Nullable warnings and annotations are explicitly turned off at this location.
/// </summary>
Disabled = 0,
/// <summary>
/// Nullable warnings are enabled and will be reported at this file location.
/// </summary>
WarningsEnabled = 1,
/// <summary>
/// Nullable annotations are enabled and will be shown when APIs defined at
/// this location are used in other contexts.
/// </summary>
AnnotationsEnabled = 1 << 1,
/// <summary>
/// The nullable feature is fully enabled.
/// </summary>
Enabled = WarningsEnabled | AnnotationsEnabled,
/// <summary>
/// The nullable warning state is inherited from the project default.
/// </summary>
/// <remarks>
/// The project default can change depending on the file type. Generated
/// files have nullable off by default, regardless of the project-level
/// default setting.
/// </remarks>
WarningsContextInherited = 1 << 2,
/// <summary>
/// The nullable annotation state is inherited from the project default.
/// </summary>
/// <remarks>
/// The project default can change depending on the file type. Generated
/// files have nullable off by default, regardless of the project-level
/// default setting.
/// </remarks>
AnnotationsContextInherited = 1 << 3,
/// <summary>
/// The current state of both warnings and annotations are inherited from
/// the project default.
/// </summary>
/// <remarks>
/// This flag is set by default at the start of all files.
///
/// The project default can change depending on the file type. Generated
/// files have nullable off by default, regardless of the project-level
/// default setting.
/// </remarks>
ContextInherited = WarningsContextInherited | AnnotationsContextInherited
}
public static class NullableContextExtensions
{
private static bool IsFlagSet(NullableContext context, NullableContext flag) =>
(context & flag) == flag;
/// <summary>
/// Returns whether nullable warnings are enabled for this context.
/// </summary>
public static bool WarningsEnabled(this NullableContext context) =>
IsFlagSet(context, NullableContext.WarningsEnabled);
/// <summary>
/// Returns whether nullable annotations are enabled for this context.
/// </summary>
public static bool AnnotationsEnabled(this NullableContext context) =>
IsFlagSet(context, NullableContext.AnnotationsEnabled);
/// <summary>
/// Returns whether the nullable warning state was inherited from the project default for this file type.
/// </summary>
public static bool WarningsInherited(this NullableContext context) =>
IsFlagSet(context, NullableContext.WarningsContextInherited);
/// <summary>
/// Returns whether the nullable annotation state was inherited from the project default for this file type.
/// </summary>
public static bool AnnotationsInherited(this NullableContext context) =>
IsFlagSet(context, NullableContext.AnnotationsContextInherited);
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/EditorFeatures/TestUtilities/Classification/FormattedClassifications.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.Diagnostics;
using Microsoft.CodeAnalysis.Classification;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification
{
public static partial class FormattedClassifications
{
private static FormattedClassification New(string text, string typeName)
=> new FormattedClassification(text, typeName);
[DebuggerStepThrough]
public static FormattedClassification Struct(string text)
=> New(text, ClassificationTypeNames.StructName);
[DebuggerStepThrough]
public static FormattedClassification Enum(string text)
=> New(text, ClassificationTypeNames.EnumName);
[DebuggerStepThrough]
public static FormattedClassification Interface(string text)
=> New(text, ClassificationTypeNames.InterfaceName);
[DebuggerStepThrough]
public static FormattedClassification Class(string text)
=> New(text, ClassificationTypeNames.ClassName);
[DebuggerStepThrough]
public static FormattedClassification Record(string text)
=> New(text, ClassificationTypeNames.RecordClassName);
[DebuggerStepThrough]
public static FormattedClassification RecordStruct(string text)
=> New(text, ClassificationTypeNames.RecordStructName);
[DebuggerStepThrough]
public static FormattedClassification Delegate(string text)
=> New(text, ClassificationTypeNames.DelegateName);
[DebuggerStepThrough]
public static FormattedClassification TypeParameter(string text)
=> New(text, ClassificationTypeNames.TypeParameterName);
[DebuggerStepThrough]
public static FormattedClassification Namespace(string text)
=> New(text, ClassificationTypeNames.NamespaceName);
[DebuggerStepThrough]
public static FormattedClassification Label(string text)
=> New(text, ClassificationTypeNames.LabelName);
[DebuggerStepThrough]
public static FormattedClassification Field(string text)
=> New(text, ClassificationTypeNames.FieldName);
[DebuggerStepThrough]
public static FormattedClassification EnumMember(string text)
=> New(text, ClassificationTypeNames.EnumMemberName);
[DebuggerStepThrough]
public static FormattedClassification Constant(string text)
=> New(text, ClassificationTypeNames.ConstantName);
[DebuggerStepThrough]
public static FormattedClassification Local(string text)
=> New(text, ClassificationTypeNames.LocalName);
[DebuggerStepThrough]
public static FormattedClassification Parameter(string text)
=> New(text, ClassificationTypeNames.ParameterName);
[DebuggerStepThrough]
public static FormattedClassification Method(string text)
=> New(text, ClassificationTypeNames.MethodName);
[DebuggerStepThrough]
public static FormattedClassification ExtensionMethod(string text)
=> New(text, ClassificationTypeNames.ExtensionMethodName);
[DebuggerStepThrough]
public static FormattedClassification Property(string text)
=> New(text, ClassificationTypeNames.PropertyName);
[DebuggerStepThrough]
public static FormattedClassification Event(string text)
=> New(text, ClassificationTypeNames.EventName);
[DebuggerStepThrough]
public static FormattedClassification Static(string text)
=> New(text, ClassificationTypeNames.StaticSymbol);
[DebuggerStepThrough]
public static FormattedClassification String(string text)
=> New(text, ClassificationTypeNames.StringLiteral);
[DebuggerStepThrough]
public static FormattedClassification Verbatim(string text)
=> New(text, ClassificationTypeNames.VerbatimStringLiteral);
[DebuggerStepThrough]
public static FormattedClassification Escape(string text)
=> New(text, ClassificationTypeNames.StringEscapeCharacter);
[DebuggerStepThrough]
public static FormattedClassification Keyword(string text)
=> New(text, ClassificationTypeNames.Keyword);
[DebuggerStepThrough]
public static FormattedClassification ControlKeyword(string text)
=> New(text, ClassificationTypeNames.ControlKeyword);
[DebuggerStepThrough]
public static FormattedClassification WhiteSpace(string text)
=> New(text, ClassificationTypeNames.WhiteSpace);
[DebuggerStepThrough]
public static FormattedClassification Text(string text)
=> New(text, ClassificationTypeNames.Text);
[DebuggerStepThrough]
public static FormattedClassification NumericLiteral(string text)
=> New(text, ClassificationTypeNames.NumericLiteral);
[DebuggerStepThrough]
public static FormattedClassification PPKeyword(string text)
=> New(text, ClassificationTypeNames.PreprocessorKeyword);
[DebuggerStepThrough]
public static FormattedClassification PPText(string text)
=> New(text, ClassificationTypeNames.PreprocessorText);
[DebuggerStepThrough]
public static FormattedClassification Identifier(string text)
=> New(text, ClassificationTypeNames.Identifier);
[DebuggerStepThrough]
public static FormattedClassification Inactive(string text)
=> New(text, ClassificationTypeNames.ExcludedCode);
[DebuggerStepThrough]
public static FormattedClassification Comment(string text)
=> New(text, ClassificationTypeNames.Comment);
[DebuggerStepThrough]
public static FormattedClassification Number(string text)
=> New(text, ClassificationTypeNames.NumericLiteral);
public static FormattedClassification LineContinuation { get; }
= New("_", ClassificationTypeNames.Punctuation);
[DebuggerStepThrough]
public static FormattedClassification Module(string text)
=> New(text, ClassificationTypeNames.ModuleName);
[DebuggerStepThrough]
public static FormattedClassification VBXmlName(string text)
=> New(text, ClassificationTypeNames.XmlLiteralName);
[DebuggerStepThrough]
public static FormattedClassification VBXmlText(string text)
=> New(text, ClassificationTypeNames.XmlLiteralText);
[DebuggerStepThrough]
public static FormattedClassification VBXmlProcessingInstruction(string text)
=> New(text, ClassificationTypeNames.XmlLiteralProcessingInstruction);
[DebuggerStepThrough]
public static FormattedClassification VBXmlEmbeddedExpression(string text)
=> New(text, ClassificationTypeNames.XmlLiteralEmbeddedExpression);
[DebuggerStepThrough]
public static FormattedClassification VBXmlDelimiter(string text)
=> New(text, ClassificationTypeNames.XmlLiteralDelimiter);
[DebuggerStepThrough]
public static FormattedClassification VBXmlComment(string text)
=> New(text, ClassificationTypeNames.XmlLiteralComment);
[DebuggerStepThrough]
public static FormattedClassification VBXmlCDataSection(string text)
=> New(text, ClassificationTypeNames.XmlLiteralCDataSection);
[DebuggerStepThrough]
public static FormattedClassification VBXmlAttributeValue(string text)
=> New(text, ClassificationTypeNames.XmlLiteralAttributeValue);
[DebuggerStepThrough]
public static FormattedClassification VBXmlAttributeQuotes(string text)
=> New(text, ClassificationTypeNames.XmlLiteralAttributeQuotes);
[DebuggerStepThrough]
public static FormattedClassification VBXmlAttributeName(string text)
=> New(text, ClassificationTypeNames.XmlLiteralAttributeName);
[DebuggerStepThrough]
public static FormattedClassification VBXmlEntityReference(string text)
=> New(text, ClassificationTypeNames.XmlLiteralEntityReference);
}
}
| // 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.Diagnostics;
using Microsoft.CodeAnalysis.Classification;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification
{
public static partial class FormattedClassifications
{
private static FormattedClassification New(string text, string typeName)
=> new FormattedClassification(text, typeName);
[DebuggerStepThrough]
public static FormattedClassification Struct(string text)
=> New(text, ClassificationTypeNames.StructName);
[DebuggerStepThrough]
public static FormattedClassification Enum(string text)
=> New(text, ClassificationTypeNames.EnumName);
[DebuggerStepThrough]
public static FormattedClassification Interface(string text)
=> New(text, ClassificationTypeNames.InterfaceName);
[DebuggerStepThrough]
public static FormattedClassification Class(string text)
=> New(text, ClassificationTypeNames.ClassName);
[DebuggerStepThrough]
public static FormattedClassification Record(string text)
=> New(text, ClassificationTypeNames.RecordClassName);
[DebuggerStepThrough]
public static FormattedClassification RecordStruct(string text)
=> New(text, ClassificationTypeNames.RecordStructName);
[DebuggerStepThrough]
public static FormattedClassification Delegate(string text)
=> New(text, ClassificationTypeNames.DelegateName);
[DebuggerStepThrough]
public static FormattedClassification TypeParameter(string text)
=> New(text, ClassificationTypeNames.TypeParameterName);
[DebuggerStepThrough]
public static FormattedClassification Namespace(string text)
=> New(text, ClassificationTypeNames.NamespaceName);
[DebuggerStepThrough]
public static FormattedClassification Label(string text)
=> New(text, ClassificationTypeNames.LabelName);
[DebuggerStepThrough]
public static FormattedClassification Field(string text)
=> New(text, ClassificationTypeNames.FieldName);
[DebuggerStepThrough]
public static FormattedClassification EnumMember(string text)
=> New(text, ClassificationTypeNames.EnumMemberName);
[DebuggerStepThrough]
public static FormattedClassification Constant(string text)
=> New(text, ClassificationTypeNames.ConstantName);
[DebuggerStepThrough]
public static FormattedClassification Local(string text)
=> New(text, ClassificationTypeNames.LocalName);
[DebuggerStepThrough]
public static FormattedClassification Parameter(string text)
=> New(text, ClassificationTypeNames.ParameterName);
[DebuggerStepThrough]
public static FormattedClassification Method(string text)
=> New(text, ClassificationTypeNames.MethodName);
[DebuggerStepThrough]
public static FormattedClassification ExtensionMethod(string text)
=> New(text, ClassificationTypeNames.ExtensionMethodName);
[DebuggerStepThrough]
public static FormattedClassification Property(string text)
=> New(text, ClassificationTypeNames.PropertyName);
[DebuggerStepThrough]
public static FormattedClassification Event(string text)
=> New(text, ClassificationTypeNames.EventName);
[DebuggerStepThrough]
public static FormattedClassification Static(string text)
=> New(text, ClassificationTypeNames.StaticSymbol);
[DebuggerStepThrough]
public static FormattedClassification String(string text)
=> New(text, ClassificationTypeNames.StringLiteral);
[DebuggerStepThrough]
public static FormattedClassification Verbatim(string text)
=> New(text, ClassificationTypeNames.VerbatimStringLiteral);
[DebuggerStepThrough]
public static FormattedClassification Escape(string text)
=> New(text, ClassificationTypeNames.StringEscapeCharacter);
[DebuggerStepThrough]
public static FormattedClassification Keyword(string text)
=> New(text, ClassificationTypeNames.Keyword);
[DebuggerStepThrough]
public static FormattedClassification ControlKeyword(string text)
=> New(text, ClassificationTypeNames.ControlKeyword);
[DebuggerStepThrough]
public static FormattedClassification WhiteSpace(string text)
=> New(text, ClassificationTypeNames.WhiteSpace);
[DebuggerStepThrough]
public static FormattedClassification Text(string text)
=> New(text, ClassificationTypeNames.Text);
[DebuggerStepThrough]
public static FormattedClassification NumericLiteral(string text)
=> New(text, ClassificationTypeNames.NumericLiteral);
[DebuggerStepThrough]
public static FormattedClassification PPKeyword(string text)
=> New(text, ClassificationTypeNames.PreprocessorKeyword);
[DebuggerStepThrough]
public static FormattedClassification PPText(string text)
=> New(text, ClassificationTypeNames.PreprocessorText);
[DebuggerStepThrough]
public static FormattedClassification Identifier(string text)
=> New(text, ClassificationTypeNames.Identifier);
[DebuggerStepThrough]
public static FormattedClassification Inactive(string text)
=> New(text, ClassificationTypeNames.ExcludedCode);
[DebuggerStepThrough]
public static FormattedClassification Comment(string text)
=> New(text, ClassificationTypeNames.Comment);
[DebuggerStepThrough]
public static FormattedClassification Number(string text)
=> New(text, ClassificationTypeNames.NumericLiteral);
public static FormattedClassification LineContinuation { get; }
= New("_", ClassificationTypeNames.Punctuation);
[DebuggerStepThrough]
public static FormattedClassification Module(string text)
=> New(text, ClassificationTypeNames.ModuleName);
[DebuggerStepThrough]
public static FormattedClassification VBXmlName(string text)
=> New(text, ClassificationTypeNames.XmlLiteralName);
[DebuggerStepThrough]
public static FormattedClassification VBXmlText(string text)
=> New(text, ClassificationTypeNames.XmlLiteralText);
[DebuggerStepThrough]
public static FormattedClassification VBXmlProcessingInstruction(string text)
=> New(text, ClassificationTypeNames.XmlLiteralProcessingInstruction);
[DebuggerStepThrough]
public static FormattedClassification VBXmlEmbeddedExpression(string text)
=> New(text, ClassificationTypeNames.XmlLiteralEmbeddedExpression);
[DebuggerStepThrough]
public static FormattedClassification VBXmlDelimiter(string text)
=> New(text, ClassificationTypeNames.XmlLiteralDelimiter);
[DebuggerStepThrough]
public static FormattedClassification VBXmlComment(string text)
=> New(text, ClassificationTypeNames.XmlLiteralComment);
[DebuggerStepThrough]
public static FormattedClassification VBXmlCDataSection(string text)
=> New(text, ClassificationTypeNames.XmlLiteralCDataSection);
[DebuggerStepThrough]
public static FormattedClassification VBXmlAttributeValue(string text)
=> New(text, ClassificationTypeNames.XmlLiteralAttributeValue);
[DebuggerStepThrough]
public static FormattedClassification VBXmlAttributeQuotes(string text)
=> New(text, ClassificationTypeNames.XmlLiteralAttributeQuotes);
[DebuggerStepThrough]
public static FormattedClassification VBXmlAttributeName(string text)
=> New(text, ClassificationTypeNames.XmlLiteralAttributeName);
[DebuggerStepThrough]
public static FormattedClassification VBXmlEntityReference(string text)
=> New(text, ClassificationTypeNames.XmlLiteralEntityReference);
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/Test/Resources/Core/SymbolsTests/Cyclic/Cyclic2.vb | ' 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.
'vbc /t:library /vbruntime- Cyclic2.vb /r:Cyclic1.dll
Public Class Class2
Sub Goo
Dim x As New Class1
End Sub
End Class
| ' 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.
'vbc /t:library /vbruntime- Cyclic2.vb /r:Cyclic1.dll
Public Class Class2
Sub Goo
Dim x As New Class1
End Sub
End Class
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/CSharp/Portable/Declarations/DeclarationKind.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;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum DeclarationKind : byte
{
Namespace,
Class,
Interface,
Struct,
Enum,
Delegate,
Script,
Submission,
ImplicitClass,
Record,
RecordStruct
}
internal static partial class EnumConversions
{
internal static DeclarationKind ToDeclarationKind(this SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.ClassDeclaration: return DeclarationKind.Class;
case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface;
case SyntaxKind.StructDeclaration: return DeclarationKind.Struct;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return DeclarationKind.Namespace;
case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum;
case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate;
case SyntaxKind.RecordDeclaration: return DeclarationKind.Record;
case SyntaxKind.RecordStructDeclaration: return DeclarationKind.RecordStruct;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
}
| // 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;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum DeclarationKind : byte
{
Namespace,
Class,
Interface,
Struct,
Enum,
Delegate,
Script,
Submission,
ImplicitClass,
Record,
RecordStruct
}
internal static partial class EnumConversions
{
internal static DeclarationKind ToDeclarationKind(this SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.ClassDeclaration: return DeclarationKind.Class;
case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface;
case SyntaxKind.StructDeclaration: return DeclarationKind.Struct;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return DeclarationKind.Namespace;
case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum;
case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate;
case SyntaxKind.RecordDeclaration: return DeclarationKind.Record;
case SyntaxKind.RecordStructDeclaration: return DeclarationKind.RecordStruct;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/Compilers/CSharp/Portable/Symbols/PublicModel/PointerTypeSymbol.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 PointerTypeSymbol : TypeSymbol, IPointerTypeSymbol
{
private readonly Symbols.PointerTypeSymbol _underlying;
private ITypeSymbol _lazyPointedAtType;
public PointerTypeSymbol(Symbols.PointerTypeSymbol underlying, CodeAnalysis.NullableAnnotation nullableAnnotation)
: base(nullableAnnotation)
{
Debug.Assert(underlying is object);
_underlying = underlying;
}
protected override ITypeSymbol WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
Debug.Assert(nullableAnnotation != _underlying.DefaultNullableAnnotation);
Debug.Assert(nullableAnnotation != this.NullableAnnotation);
return new PointerTypeSymbol(_underlying, nullableAnnotation);
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
internal override Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying;
internal override Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying;
ITypeSymbol IPointerTypeSymbol.PointedAtType
{
get
{
if (_lazyPointedAtType is null)
{
Interlocked.CompareExchange(ref _lazyPointedAtType, _underlying.PointedAtTypeWithAnnotations.GetPublicSymbol(), null);
}
return _lazyPointedAtType;
}
}
ImmutableArray<CustomModifier> IPointerTypeSymbol.CustomModifiers
{
get { return _underlying.PointedAtTypeWithAnnotations.CustomModifiers; }
}
#region ISymbol Members
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitPointerType(this);
}
protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitPointerType(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 PointerTypeSymbol : TypeSymbol, IPointerTypeSymbol
{
private readonly Symbols.PointerTypeSymbol _underlying;
private ITypeSymbol _lazyPointedAtType;
public PointerTypeSymbol(Symbols.PointerTypeSymbol underlying, CodeAnalysis.NullableAnnotation nullableAnnotation)
: base(nullableAnnotation)
{
Debug.Assert(underlying is object);
_underlying = underlying;
}
protected override ITypeSymbol WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
Debug.Assert(nullableAnnotation != _underlying.DefaultNullableAnnotation);
Debug.Assert(nullableAnnotation != this.NullableAnnotation);
return new PointerTypeSymbol(_underlying, nullableAnnotation);
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
internal override Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying;
internal override Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying;
ITypeSymbol IPointerTypeSymbol.PointedAtType
{
get
{
if (_lazyPointedAtType is null)
{
Interlocked.CompareExchange(ref _lazyPointedAtType, _underlying.PointedAtTypeWithAnnotations.GetPublicSymbol(), null);
}
return _lazyPointedAtType;
}
}
ImmutableArray<CustomModifier> IPointerTypeSymbol.CustomModifiers
{
get { return _underlying.PointedAtTypeWithAnnotations.CustomModifiers; }
}
#region ISymbol Members
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitPointerType(this);
}
protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitPointerType(this);
}
#endregion
}
}
| -1 |
|
dotnet/roslyn | 55,953 | Typo fixes in docs | faso | 2021-08-27T10:48:05Z | 2021-08-27T16:39:47Z | 9956971e856c24df865bf421c0510eb0d704fc40 | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | Typo fixes in docs. | ./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.OptionChangedEventSource.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.Options;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class OptionChangedEventSource : AbstractWorkspaceTrackingTaggerEventSource
{
private readonly IOption _option;
private IOptionService? _optionService;
public OptionChangedEventSource(ITextBuffer subjectBuffer, IOption option) : base(subjectBuffer)
=> _option = option;
protected override void ConnectToWorkspace(Workspace workspace)
{
_optionService = workspace.Services.GetService<IOptionService>();
if (_optionService != null)
{
_optionService.OptionChanged += OnOptionChanged;
}
}
protected override void DisconnectFromWorkspace(Workspace workspace)
{
if (_optionService != null)
{
_optionService.OptionChanged -= OnOptionChanged;
_optionService = null;
}
}
private void OnOptionChanged(object? sender, OptionChangedEventArgs e)
{
if (e.Option == _option)
{
this.RaiseChanged();
}
}
}
}
}
| // 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.Options;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class OptionChangedEventSource : AbstractWorkspaceTrackingTaggerEventSource
{
private readonly IOption _option;
private IOptionService? _optionService;
public OptionChangedEventSource(ITextBuffer subjectBuffer, IOption option) : base(subjectBuffer)
=> _option = option;
protected override void ConnectToWorkspace(Workspace workspace)
{
_optionService = workspace.Services.GetService<IOptionService>();
if (_optionService != null)
{
_optionService.OptionChanged += OnOptionChanged;
}
}
protected override void DisconnectFromWorkspace(Workspace workspace)
{
if (_optionService != null)
{
_optionService.OptionChanged -= OnOptionChanged;
_optionService = null;
}
}
private void OnOptionChanged(object? sender, OptionChangedEventArgs e)
{
if (e.Option == _option)
{
this.RaiseChanged();
}
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/Compilers/CSharp/Portable/CodeGen/EmitStatement.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.Linq;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.Binder;
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
internal partial class CodeGenerator
{
private void EmitStatement(BoundStatement statement)
{
switch (statement.Kind)
{
case BoundKind.Block:
EmitBlock((BoundBlock)statement);
break;
case BoundKind.Scope:
EmitScope((BoundScope)statement);
break;
case BoundKind.SequencePoint:
this.EmitSequencePointStatement((BoundSequencePoint)statement);
break;
case BoundKind.SequencePointWithSpan:
this.EmitSequencePointStatement((BoundSequencePointWithSpan)statement);
break;
case BoundKind.SavePreviousSequencePoint:
this.EmitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)statement);
break;
case BoundKind.RestorePreviousSequencePoint:
this.EmitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)statement);
break;
case BoundKind.StepThroughSequencePoint:
this.EmitStepThroughSequencePoint((BoundStepThroughSequencePoint)statement);
break;
case BoundKind.ExpressionStatement:
EmitExpression(((BoundExpressionStatement)statement).Expression, false);
break;
case BoundKind.StatementList:
EmitStatementList((BoundStatementList)statement);
break;
case BoundKind.ReturnStatement:
EmitReturnStatement((BoundReturnStatement)statement);
break;
case BoundKind.GotoStatement:
EmitGotoStatement((BoundGotoStatement)statement);
break;
case BoundKind.LabelStatement:
EmitLabelStatement((BoundLabelStatement)statement);
break;
case BoundKind.ConditionalGoto:
EmitConditionalGoto((BoundConditionalGoto)statement);
break;
case BoundKind.ThrowStatement:
EmitThrowStatement((BoundThrowStatement)statement);
break;
case BoundKind.TryStatement:
EmitTryStatement((BoundTryStatement)statement);
break;
case BoundKind.SwitchDispatch:
EmitSwitchDispatch((BoundSwitchDispatch)statement);
break;
case BoundKind.StateMachineScope:
EmitStateMachineScope((BoundStateMachineScope)statement);
break;
case BoundKind.NoOpStatement:
EmitNoOpStatement((BoundNoOpStatement)statement);
break;
default:
// Code gen should not be invoked if there are errors.
throw ExceptionUtilities.UnexpectedValue(statement.Kind);
}
#if DEBUG
if (_stackLocals == null || _stackLocals.Count == 0)
{
_builder.AssertStackEmpty();
}
#endif
ReleaseExpressionTemps();
}
private int EmitStatementAndCountInstructions(BoundStatement statement)
{
int n = _builder.InstructionsEmitted;
this.EmitStatement(statement);
return _builder.InstructionsEmitted - n;
}
private void EmitStatementList(BoundStatementList list)
{
for (int i = 0, n = list.Statements.Length; i < n; i++)
{
EmitStatement(list.Statements[i]);
}
}
private void EmitNoOpStatement(BoundNoOpStatement statement)
{
switch (statement.Flavor)
{
case NoOpStatementFlavor.Default:
if (_ilEmitStyle == ILEmitStyle.Debug)
{
_builder.EmitOpCode(ILOpCode.Nop);
}
break;
case NoOpStatementFlavor.AwaitYieldPoint:
Debug.Assert((_asyncYieldPoints == null) == (_asyncResumePoints == null));
if (_asyncYieldPoints == null)
{
_asyncYieldPoints = ArrayBuilder<int>.GetInstance();
_asyncResumePoints = ArrayBuilder<int>.GetInstance();
}
Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
_asyncYieldPoints.Add(_builder.AllocateILMarker());
break;
case NoOpStatementFlavor.AwaitResumePoint:
Debug.Assert(_asyncYieldPoints != null);
Debug.Assert(_asyncYieldPoints != null);
_asyncResumePoints.Add(_builder.AllocateILMarker());
Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
break;
default:
throw ExceptionUtilities.UnexpectedValue(statement.Flavor);
}
}
private void EmitThrowStatement(BoundThrowStatement node)
{
EmitThrow(node.ExpressionOpt);
}
private void EmitThrow(BoundExpression thrown)
{
if (thrown != null)
{
this.EmitExpression(thrown, true);
var exprType = thrown.Type;
// Expression type will be null for "throw null;".
if (exprType?.TypeKind == TypeKind.TypeParameter)
{
this.EmitBox(exprType, thrown.Syntax);
}
}
_builder.EmitThrow(isRethrow: thrown == null);
}
private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto)
{
object label = boundConditionalGoto.Label;
Debug.Assert(label != null);
EmitCondBranch(boundConditionalGoto.Condition, ref label, boundConditionalGoto.JumpIfTrue);
}
// 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed
//pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at
//the next instruction.
private static bool CanPassToBrfalse(TypeSymbol ts)
{
if (ts.IsEnumType())
{
// valid enums are all primitives
return true;
}
var tc = ts.PrimitiveTypeCode;
switch (tc)
{
case Microsoft.Cci.PrimitiveTypeCode.Float32:
case Microsoft.Cci.PrimitiveTypeCode.Float64:
return false;
case Microsoft.Cci.PrimitiveTypeCode.NotPrimitive:
// if this is a generic type param, verifier will want us to box
// EmitCondBranch knows that
return ts.IsReferenceType;
default:
Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Invalid);
Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Void);
return true;
}
}
private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense)
{
var opKind = condition.OperatorKind.Operator();
Debug.Assert(opKind == BinaryOperatorKind.Equal ||
opKind == BinaryOperatorKind.NotEqual);
BoundExpression nonConstOp;
BoundExpression constOp = (condition.Left.ConstantValue != null) ? condition.Left : null;
if (constOp != null)
{
nonConstOp = condition.Right;
}
else
{
constOp = (condition.Right.ConstantValue != null) ? condition.Right : null;
if (constOp == null)
{
return null;
}
nonConstOp = condition.Left;
}
var nonConstType = nonConstOp.Type;
if (!CanPassToBrfalse(nonConstType))
{
return null;
}
bool isBool = nonConstType.PrimitiveTypeCode == Microsoft.Cci.PrimitiveTypeCode.Boolean;
bool isZero = constOp.ConstantValue.IsDefaultValue;
// bool is special, only it can be compared to true and false...
if (!isBool && !isZero)
{
return null;
}
// if comparing to zero, flip the sense
if (isZero)
{
sense = !sense;
}
// if comparing != flip the sense
if (opKind == BinaryOperatorKind.NotEqual)
{
sense = !sense;
}
return nonConstOp;
}
private const int IL_OP_CODE_ROW_LENGTH = 4;
private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[]
{
// < <= > >=
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed
ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert
ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert
};
/// <summary>
/// Produces opcode for a jump that corresponds to given operation and sense.
/// Also produces a reverse opcode - opcode for the same condition with inverted sense.
/// </summary>
private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode)
{
int opIdx;
switch (op.OperatorKind.Operator())
{
case BinaryOperatorKind.Equal:
revOpCode = !sense ? ILOpCode.Beq : ILOpCode.Bne_un;
return sense ? ILOpCode.Beq : ILOpCode.Bne_un;
case BinaryOperatorKind.NotEqual:
revOpCode = !sense ? ILOpCode.Bne_un : ILOpCode.Beq;
return sense ? ILOpCode.Bne_un : ILOpCode.Beq;
case BinaryOperatorKind.LessThan:
opIdx = 0;
break;
case BinaryOperatorKind.LessThanOrEqual:
opIdx = 1;
break;
case BinaryOperatorKind.GreaterThan:
opIdx = 2;
break;
case BinaryOperatorKind.GreaterThanOrEqual:
opIdx = 3;
break;
default:
throw ExceptionUtilities.UnexpectedValue(op.OperatorKind.Operator());
}
if (IsUnsignedBinaryOperator(op))
{
opIdx += 2 * IL_OP_CODE_ROW_LENGTH; //unsigned
}
else if (IsFloat(op.OperatorKind))
{
opIdx += 4 * IL_OP_CODE_ROW_LENGTH; //float
}
int revOpIdx = opIdx;
if (!sense)
{
opIdx += IL_OP_CODE_ROW_LENGTH; //invert op
}
else
{
revOpIdx += IL_OP_CODE_ROW_LENGTH; //invert rev
}
revOpCode = s_condJumpOpCodes[revOpIdx];
return s_condJumpOpCodes[opIdx];
}
// generate a jump to dest if (condition == sense) is true
private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense)
{
_recursionDepth++;
if (_recursionDepth > 1)
{
StackGuard.EnsureSufficientExecutionStack(_recursionDepth);
EmitCondBranchCore(condition, ref dest, sense);
}
else
{
EmitCondBranchCoreWithStackGuard(condition, ref dest, sense);
}
_recursionDepth--;
}
private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense)
{
Debug.Assert(_recursionDepth == 1);
try
{
EmitCondBranchCore(condition, ref dest, sense);
Debug.Assert(_recursionDepth == 1);
}
catch (InsufficientExecutionStackException)
{
_diagnostics.Add(ErrorCode.ERR_InsufficientStack,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition));
throw new EmitCancelledException();
}
}
private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense)
{
oneMoreTime:
ILOpCode ilcode;
if (condition.ConstantValue != null)
{
bool taken = condition.ConstantValue.IsDefaultValue != sense;
if (taken)
{
dest = dest ?? new object();
_builder.EmitBranch(ILOpCode.Br, dest);
}
else
{
// otherwise this branch will never be taken, so just fall through...
}
return;
}
switch (condition.Kind)
{
case BoundKind.BinaryOperator:
var binOp = (BoundBinaryOperator)condition;
bool testBothArgs = sense;
switch (binOp.OperatorKind.OperatorWithLogical())
{
case BinaryOperatorKind.LogicalOr:
testBothArgs = !testBothArgs;
// Fall through
goto case BinaryOperatorKind.LogicalAnd;
case BinaryOperatorKind.LogicalAnd:
if (testBothArgs)
{
// gotoif(a != sense) fallThrough
// gotoif(b == sense) dest
// fallThrough:
object fallThrough = null;
EmitCondBranch(binOp.Left, ref fallThrough, !sense);
EmitCondBranch(binOp.Right, ref dest, sense);
if (fallThrough != null)
{
_builder.MarkLabel(fallThrough);
}
}
else
{
// gotoif(a == sense) labDest
// gotoif(b == sense) labDest
EmitCondBranch(binOp.Left, ref dest, sense);
condition = binOp.Right;
goto oneMoreTime;
}
return;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
var reduced = TryReduce(binOp, ref sense);
if (reduced != null)
{
condition = reduced;
goto oneMoreTime;
}
// Fall through
goto case BinaryOperatorKind.LessThan;
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
EmitExpression(binOp.Left, true);
EmitExpression(binOp.Right, true);
ILOpCode revOpCode;
ilcode = CodeForJump(binOp, sense, out revOpCode);
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest, revOpCode);
return;
}
// none of above.
// then it is regular binary expression - Or, And, Xor ...
goto default;
case BoundKind.LoweredConditionalAccess:
{
var ca = (BoundLoweredConditionalAccess)condition;
var receiver = ca.Receiver;
var receiverType = receiver.Type;
// we need a copy if we deal with nonlocal value (to capture the value)
// or if we deal with stack local (reads are destructive)
var complexCase = !receiverType.IsReferenceType ||
LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
(receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) ||
(ca.WhenNullOpt?.IsDefaultValue() == false);
if (complexCase)
{
goto default;
}
if (sense)
{
// gotoif(receiver != null) fallThrough
// gotoif(receiver.Access) dest
// fallThrough:
object fallThrough = null;
EmitCondBranch(receiver, ref fallThrough, sense: false);
// receiver is a reference type, and we only intend to read it
EmitReceiverRef(receiver, AddressKind.ReadOnly);
EmitCondBranch(ca.WhenNotNull, ref dest, sense: true);
if (fallThrough != null)
{
_builder.MarkLabel(fallThrough);
}
}
else
{
// gotoif(receiver == null) labDest
// gotoif(!receiver.Access) labDest
EmitCondBranch(receiver, ref dest, sense: false);
// receiver is a reference type, and we only intend to read it
EmitReceiverRef(receiver, AddressKind.ReadOnly);
condition = ca.WhenNotNull;
goto oneMoreTime;
}
}
return;
case BoundKind.UnaryOperator:
var unOp = (BoundUnaryOperator)condition;
if (unOp.OperatorKind == UnaryOperatorKind.BoolLogicalNegation)
{
sense = !sense;
condition = unOp.Operand;
goto oneMoreTime;
}
goto default;
case BoundKind.IsOperator:
var isOp = (BoundIsOperator)condition;
var operand = isOp.Operand;
EmitExpression(operand, true);
Debug.Assert((object)operand.Type != null);
if (!operand.Type.IsVerifierReference())
{
// box the operand for isinst if it is not a verifier reference
EmitBox(operand.Type, operand.Syntax);
}
_builder.EmitOpCode(ILOpCode.Isinst);
EmitSymbolToken(isOp.TargetType.Type, isOp.TargetType.Syntax);
ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest);
return;
case BoundKind.Sequence:
var seq = (BoundSequence)condition;
EmitSequenceCondBranch(seq, ref dest, sense);
return;
default:
EmitExpression(condition, true);
var conditionType = condition.Type;
if (conditionType.IsReferenceType && !conditionType.IsVerifierReference())
{
EmitBox(conditionType, condition.Syntax);
}
ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest);
return;
}
}
private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense)
{
DefineLocals(sequence);
EmitSideEffects(sequence);
EmitCondBranch(sequence.Value, ref dest, sense);
// sequence is used as a value, can release all locals
FreeLocals(sequence);
}
private void EmitLabelStatement(BoundLabelStatement boundLabelStatement)
{
_builder.MarkLabel(boundLabelStatement.Label);
}
private void EmitGotoStatement(BoundGotoStatement boundGotoStatement)
{
_builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label);
}
// used by HandleReturn method which tries to inject
// indirect ret sequence as a last statement in the block
// that is the last statement of the current method
// NOTE: it is important that there is no code after this "ret"
// it is desirable, for debug purposes, that this ret is emitted inside top level { }
private bool IsLastBlockInMethod(BoundBlock block)
{
if (_boundBody == block)
{
return true;
}
//sometimes top level node is a statement list containing
//epilogue and then a block. If we are having that block, it will do.
var list = _boundBody as BoundStatementList;
if (list != null && list.Statements.LastOrDefault() == block)
{
return true;
}
return false;
}
private void EmitBlock(BoundBlock block)
{
var hasLocals = !block.Locals.IsEmpty;
if (hasLocals)
{
_builder.OpenLocalScope();
foreach (var local in block.Locals)
{
Debug.Assert(local.RefKind == RefKind.None || local.SynthesizedKind.IsLongLived(),
"A ref local ended up in a block and claims it is shortlived. That is dangerous. Are we sure it is short lived?");
var declaringReferences = local.DeclaringSyntaxReferences;
DefineLocal(local, !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : block.Syntax);
}
}
EmitStatements(block.Statements);
if (_indirectReturnState == IndirectReturnState.Needed &&
IsLastBlockInMethod(block))
{
HandleReturn();
}
if (hasLocals)
{
foreach (var local in block.Locals)
{
FreeLocal(local);
}
_builder.CloseLocalScope();
}
}
private void EmitStatements(ImmutableArray<BoundStatement> statements)
{
foreach (var statement in statements)
{
EmitStatement(statement);
}
}
private void EmitScope(BoundScope block)
{
Debug.Assert(!block.Locals.IsEmpty);
_builder.OpenLocalScope();
foreach (var local in block.Locals)
{
Debug.Assert(local.Name != null);
Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.UserDefined &&
(local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchSection || local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchExpressionArm));
if (!local.IsConst && !IsStackLocal(local))
{
_builder.AddLocalToScope(_builder.LocalSlotManager.GetLocal(local));
}
}
EmitStatements(block.Statements);
_builder.CloseLocalScope();
}
private void EmitStateMachineScope(BoundStateMachineScope scope)
{
_builder.OpenLocalScope(ScopeType.StateMachineVariable);
foreach (var field in scope.Fields)
{
_builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex);
}
EmitStatement(scope.Statement);
_builder.CloseLocalScope();
}
// There are two ways a value can be returned from a function:
// - Using ret opcode
// - Store return value if any to a predefined temp and jump to the epilogue block
// Sometimes ret is not an option (try/catch etc.). We also do this when emitting
// debuggable code. This function is a stub for the logic that decides that.
private bool ShouldUseIndirectReturn()
{
// If the method/lambda body is a block we define a sequence point for the closing brace of the body
// and associate it with the ret instruction. If there is a return statement we need to store the value
// to a long-lived synthesized local since a sequence point requires an empty evaluation stack.
//
// The emitted pattern is:
// <evaluate return statement expression>
// stloc $ReturnValue
// ldloc $ReturnValue // sequence point
// ret
//
// Do not emit this pattern if the method doesn't include user code or doesn't have a block body.
return _ilEmitStyle == ILEmitStyle.Debug && _method.GenerateDebugInfo && _methodBodySyntaxOpt?.IsKind(SyntaxKind.Block) == true ||
_builder.InExceptionHandler;
}
// Compiler generated return mapped to a block is very likely the synthetic return
// that was added at the end of the last block of a void method by analysis.
// This is likely to be the last return in the method, so if we have not yet
// emitted return sequence, it is convenient to do it right here (if we can).
private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement)
{
return boundReturnStatement.WasCompilerGenerated &&
(boundReturnStatement.Syntax.IsKind(SyntaxKind.Block) || _method?.IsImplicitConstructor == true) &&
!_builder.InExceptionHandler;
}
private void EmitReturnStatement(BoundReturnStatement boundReturnStatement)
{
var expressionOpt = boundReturnStatement.ExpressionOpt;
if (boundReturnStatement.RefKind == RefKind.None)
{
this.EmitExpression(expressionOpt, true);
}
else
{
// NOTE: passing "ReadOnlyStrict" here.
// we should never return an address of a copy
var unexpectedTemp = this.EmitAddress(expressionOpt, this._method.RefKind == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
Debug.Assert(unexpectedTemp == null, "ref-returning a temp?");
}
if (ShouldUseIndirectReturn())
{
if (expressionOpt != null)
{
_builder.EmitLocalStore(LazyReturnTemp);
}
if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement))
{
HandleReturn();
}
else
{
_builder.EmitBranch(ILOpCode.Br, s_returnLabel);
if (_indirectReturnState == IndirectReturnState.NotNeeded)
{
_indirectReturnState = IndirectReturnState.Needed;
}
}
}
else
{
if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement))
{
if (expressionOpt != null)
{
_builder.EmitLocalStore(LazyReturnTemp);
}
HandleReturn();
}
else
{
if (expressionOpt != null)
{
// Ensure the return type has been translated. (Necessary
// for cases of untranslated anonymous types.)
_module.Translate(expressionOpt.Type, boundReturnStatement.Syntax, _diagnostics);
}
_builder.EmitRet(expressionOpt == null);
}
}
}
private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false)
{
Debug.Assert(!statement.CatchBlocks.IsDefault);
// Stack must be empty at beginning of try block.
_builder.AssertStackEmpty();
// IL requires catches and finally block to be distinct try
// blocks so if the source contained both a catch and
// a finally, nested scopes are emitted.
bool emitNestedScopes = (!emitCatchesOnly &&
(statement.CatchBlocks.Length > 0) &&
(statement.FinallyBlockOpt != null));
_builder.OpenLocalScope(ScopeType.TryCatchFinally);
_builder.OpenLocalScope(ScopeType.Try);
// IL requires catches and finally block to be distinct try
// blocks so if the source contained both a catch and
// a finally, nested scopes are emitted.
_tryNestingLevel++;
if (emitNestedScopes)
{
EmitTryStatement(statement, emitCatchesOnly: true);
}
else
{
EmitBlock(statement.TryBlock);
}
_tryNestingLevel--;
// Close the Try scope
_builder.CloseLocalScope();
if (!emitNestedScopes)
{
foreach (var catchBlock in statement.CatchBlocks)
{
EmitCatchBlock(catchBlock);
}
}
if (!emitCatchesOnly && (statement.FinallyBlockOpt != null))
{
_builder.OpenLocalScope(statement.PreferFaultHandler ? ScopeType.Fault : ScopeType.Finally);
EmitBlock(statement.FinallyBlockOpt);
// close Finally scope
_builder.CloseLocalScope();
// close the whole try statement scope
_builder.CloseLocalScope();
// in a case where we emit surrogate Finally using Fault, we emit code like this
//
// try{
// . . .
// } fault {
// finallyBlock;
// }
// finallyBlock;
//
// This is where the second copy of finallyBlock is emitted.
if (statement.PreferFaultHandler)
{
var finallyClone = FinallyCloner.MakeFinallyClone(statement);
EmitBlock(finallyClone);
}
}
else
{
// close the whole try statement scope
_builder.CloseLocalScope();
}
}
/// <remarks>
/// The interesting part in the following method is the support for exception filters.
/// === Example:
///
/// try
/// {
/// TryBlock
/// }
/// catch (ExceptionType ex) when (Condition)
/// {
/// Handler
/// }
///
/// gets emitted as something like ===>
///
/// Try
/// TryBlock
/// Filter
/// var tmp = Pop() as {ExceptionType}
/// if (tmp == null)
/// {
/// Push 0
/// }
/// else
/// {
/// ex = tmp
/// Push Condition ? 1 : 0
/// }
/// End Filter // leaves 1 or 0 on the stack
/// Catch // gets called after finalization of nested exception frames if condition above produced 1
/// Pop // CLR pushes the exception object again
/// variable ex can be used here
/// Handler
/// EndCatch
///
/// When evaluating `Condition` requires additional statements be executed first, those
/// statements are stored in `catchBlock.ExceptionFilterPrologueOpt` and emitted before the condition.
/// </remarks>
private void EmitCatchBlock(BoundCatchBlock catchBlock)
{
object typeCheckFailedLabel = null;
_builder.AdjustStack(1); // Account for exception on the stack.
// Open appropriate exception handler scope. (Catch or Filter)
// if it is a Filter, emit prologue that checks if the type on the stack
// converts to what we want.
if (catchBlock.ExceptionFilterOpt == null)
{
var exceptionType = ((object)catchBlock.ExceptionTypeOpt != null) ?
_module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics) :
_module.GetSpecialType(SpecialType.System_Object, catchBlock.Syntax, _diagnostics);
_builder.OpenLocalScope(ScopeType.Catch, exceptionType);
RecordAsyncCatchHandlerOffset(catchBlock);
// Dev12 inserts the sequence point on catch clause without a filter, just before
// the exception object is assigned to the variable.
//
// Also in Dev12 the exception variable scope span starts right after the stloc instruction and
// ends right before leave instruction. So when stopped at the sequence point Dev12 inserts,
// the exception variable is not visible.
if (_emitPdbSequencePoints)
{
var syntax = catchBlock.Syntax as CatchClauseSyntax;
if (syntax != null)
{
TextSpan spSpan;
var declaration = syntax.Declaration;
if (declaration == null)
{
spSpan = syntax.CatchKeyword.Span;
}
else
{
spSpan = TextSpan.FromBounds(syntax.SpanStart, syntax.Declaration.Span.End);
}
this.EmitSequencePoint(catchBlock.SyntaxTree, spSpan);
}
}
}
else
{
_builder.OpenLocalScope(ScopeType.Filter);
RecordAsyncCatchHandlerOffset(catchBlock);
// Filtering starts with simulating regular catch through a
// type check. If this is not our type then we are done.
var typeCheckPassedLabel = new object();
typeCheckFailedLabel = new object();
if ((object)catchBlock.ExceptionTypeOpt != null)
{
var exceptionType = _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics);
_builder.EmitOpCode(ILOpCode.Isinst);
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics);
_builder.EmitOpCode(ILOpCode.Dup);
_builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel);
_builder.EmitOpCode(ILOpCode.Pop);
_builder.EmitIntConstant(0);
_builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel);
}
else
{
// no formal exception type means we always pass the check
}
_builder.MarkLabel(typeCheckPassedLabel);
}
foreach (var local in catchBlock.Locals)
{
var declaringReferences = local.DeclaringSyntaxReferences;
var localSyntax = !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : catchBlock.Syntax;
DefineLocal(local, localSyntax);
}
var exceptionSourceOpt = catchBlock.ExceptionSourceOpt;
if (exceptionSourceOpt != null)
{
// here we have our exception on the stack in a form of a reference type (O)
// it means that we have to "unbox" it before storing to the local
// if exception's type is a generic type parameter.
if (!exceptionSourceOpt.Type.IsVerifierReference())
{
Debug.Assert(exceptionSourceOpt.Type.IsTypeParameter()); // only expecting type parameters
_builder.EmitOpCode(ILOpCode.Unbox_any);
EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax);
}
BoundExpression exceptionSource = exceptionSourceOpt;
while (exceptionSource.Kind == BoundKind.Sequence)
{
var seq = (BoundSequence)exceptionSource;
Debug.Assert(seq.Locals.IsDefaultOrEmpty);
EmitSideEffects(seq);
exceptionSource = seq.Value;
}
switch (exceptionSource.Kind)
{
case BoundKind.Local:
var exceptionSourceLocal = (BoundLocal)exceptionSource;
Debug.Assert(exceptionSourceLocal.LocalSymbol.RefKind == RefKind.None);
if (!IsStackLocal(exceptionSourceLocal.LocalSymbol))
{
_builder.EmitLocalStore(GetLocal(exceptionSourceLocal));
}
break;
case BoundKind.FieldAccess:
var left = (BoundFieldAccess)exceptionSource;
Debug.Assert(!left.FieldSymbol.IsStatic, "Not supported");
Debug.Assert(!left.ReceiverOpt.Type.IsTypeParameter());
var stateMachineField = left.FieldSymbol as StateMachineFieldSymbol;
if (((object)stateMachineField != null) && (stateMachineField.SlotIndex >= 0))
{
_builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineField.SlotIndex);
}
// When assigning to a field
// we need to push param address below the exception
var temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax);
_builder.EmitLocalStore(temp);
var receiverTemp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable);
Debug.Assert(receiverTemp == null);
_builder.EmitLocalLoad(temp);
FreeTemp(temp);
EmitFieldStore(left);
break;
default:
throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind);
}
}
else
{
_builder.EmitOpCode(ILOpCode.Pop);
}
if (catchBlock.ExceptionFilterPrologueOpt != null)
{
Debug.Assert(_builder.IsStackEmpty);
EmitStatements(catchBlock.ExceptionFilterPrologueOpt.Statements);
}
// Emit the actual filter expression, if we have one, and normalize
// results.
if (catchBlock.ExceptionFilterOpt != null)
{
EmitCondExpr(catchBlock.ExceptionFilterOpt, true);
// Normalize the return value because values other than 0 or 1
// produce unspecified results.
_builder.EmitIntConstant(0);
_builder.EmitOpCode(ILOpCode.Cgt_un);
_builder.MarkLabel(typeCheckFailedLabel);
// Now we are starting the actual handler
_builder.MarkFilterConditionEnd();
// Pop the exception; it should have already been stored to the
// variable by the filter.
_builder.EmitOpCode(ILOpCode.Pop);
}
EmitBlock(catchBlock.Body);
_builder.CloseLocalScope();
}
private void RecordAsyncCatchHandlerOffset(BoundCatchBlock catchBlock)
{
if (catchBlock.IsSynthesizedAsyncCatchAll)
{
Debug.Assert(_asyncCatchHandlerOffset < 0); // only one expected
_asyncCatchHandlerOffset = _builder.AllocateILMarker();
}
}
private void EmitSwitchDispatch(BoundSwitchDispatch dispatch)
{
// Switch expression must have a valid switch governing type
Debug.Assert((object)dispatch.Expression.Type != null);
Debug.Assert(dispatch.Expression.Type.IsValidV6SwitchGoverningType());
// We must have rewritten nullable switch expression into non-nullable constructs.
Debug.Assert(!dispatch.Expression.Type.IsNullableType());
// This must be used only for nontrivial dispatches.
Debug.Assert(dispatch.Cases.Any());
EmitSwitchHeader(
dispatch.Expression,
dispatch.Cases.Select(p => new KeyValuePair<ConstantValue, object>(p.value, p.label)).ToArray(),
dispatch.DefaultLabel,
dispatch.EqualityMethod);
}
private void EmitSwitchHeader(
BoundExpression expression,
KeyValuePair<ConstantValue, object>[] switchCaseLabels,
LabelSymbol fallThroughLabel,
MethodSymbol equalityMethod)
{
Debug.Assert(expression.ConstantValue == null);
Debug.Assert((object)expression.Type != null &&
expression.Type.IsValidV6SwitchGoverningType());
Debug.Assert(switchCaseLabels.Length > 0);
Debug.Assert(switchCaseLabels != null);
LocalDefinition temp = null;
LocalOrParameter key;
BoundSequence sequence = null;
if (expression.Kind == BoundKind.Sequence)
{
sequence = (BoundSequence)expression;
DefineLocals(sequence);
EmitSideEffects(sequence);
expression = sequence.Value;
}
if (expression.Kind == BoundKind.SequencePointExpression)
{
var sequencePointExpression = (BoundSequencePointExpression)expression;
EmitSequencePoint(sequencePointExpression);
expression = sequencePointExpression.Expression;
}
switch (expression.Kind)
{
case BoundKind.Local:
var local = ((BoundLocal)expression).LocalSymbol;
if (local.RefKind == RefKind.None && !IsStackLocal(local))
{
key = this.GetLocal(local);
break;
}
goto default;
case BoundKind.Parameter:
var parameter = (BoundParameter)expression;
if (parameter.ParameterSymbol.RefKind == RefKind.None)
{
key = ParameterSlot(parameter);
break;
}
goto default;
default:
EmitExpression(expression, true);
temp = AllocateTemp(expression.Type, expression.Syntax);
_builder.EmitLocalStore(temp);
key = temp;
break;
}
// Emit switch jump table
if (expression.Type.SpecialType != SpecialType.System_String)
{
_builder.EmitIntegerSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Type.EnumUnderlyingTypeOrSelf().PrimitiveTypeCode);
}
else
{
this.EmitStringSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Syntax, equalityMethod);
}
if (temp != null)
{
FreeTemp(temp);
}
if (sequence != null)
{
// sequence was used as a value, can release all its locals.
FreeLocals(sequence);
}
}
private void EmitStringSwitchJumpTable(
KeyValuePair<ConstantValue, object>[] switchCaseLabels,
LabelSymbol fallThroughLabel,
LocalOrParameter key,
SyntaxNode syntaxNode,
MethodSymbol equalityMethod)
{
LocalDefinition keyHash = null;
// Condition is necessary, but not sufficient (e.g. might be missing a special or well-known member).
if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, switchCaseLabels.Length))
{
Debug.Assert(_module.SupportsPrivateImplClass);
var privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics);
Cci.IReference stringHashMethodRef = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName);
// Heuristics and well-known member availability determine the existence
// of this helper. Rather than reproduce that (language-specific) logic here,
// we simply check for the information we really want - whether the helper is
// available.
if (stringHashMethodRef != null)
{
// static uint ComputeStringHash(string s)
// pop 1 (s)
// push 1 (uint return value)
// stackAdjustment = (pushCount - popCount) = 0
_builder.EmitLoad(key);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
_builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics);
var UInt32Type = _module.Compilation.GetSpecialType(SpecialType.System_UInt32);
keyHash = AllocateTemp(UInt32Type, syntaxNode);
_builder.EmitLocalStore(keyHash);
}
}
Cci.IReference stringEqualityMethodRef = _module.Translate(equalityMethod, syntaxNode, _diagnostics);
Cci.IMethodReference stringLengthRef = null;
var stringLengthMethod = _module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__Length) as MethodSymbol;
if (stringLengthMethod != null && !stringLengthMethod.HasUseSiteError)
{
stringLengthRef = _module.Translate(stringLengthMethod, syntaxNode, _diagnostics);
}
SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate =
(keyArg, stringConstant, targetLabel) =>
{
if (stringConstant == ConstantValue.Null)
{
// if (key == null)
// goto targetLabel
_builder.EmitLoad(keyArg);
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
}
else if (stringConstant.StringValue.Length == 0 && stringLengthRef != null)
{
// if (key != null && key.Length == 0)
// goto targetLabel
object skipToNext = new object();
_builder.EmitLoad(keyArg);
_builder.EmitBranch(ILOpCode.Brfalse, skipToNext, ILOpCode.Brtrue);
_builder.EmitLoad(keyArg);
// Stack: key --> length
_builder.EmitOpCode(ILOpCode.Call, 0);
var diag = DiagnosticBag.GetInstance();
_builder.EmitToken(stringLengthRef, null, diag);
Debug.Assert(diag.IsEmptyWithoutResolution);
diag.Free();
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
_builder.MarkLabel(skipToNext);
}
else
{
this.EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, stringEqualityMethodRef);
}
};
_builder.EmitStringSwitchJumpTable(
caseLabels: switchCaseLabels,
fallThroughLabel: fallThroughLabel,
key: key,
keyHash: keyHash,
emitStringCondBranchDelegate: emitStringCondBranchDelegate,
computeStringHashcodeDelegate: SynthesizedStringSwitchHashMethod.ComputeStringHash);
if (keyHash != null)
{
FreeTemp(keyHash);
}
}
/// <summary>
/// Delegate to emit string compare call and conditional branch based on the compare result.
/// </summary>
/// <param name="key">Key to compare</param>
/// <param name="syntaxNode">Node for diagnostics.</param>
/// <param name="stringConstant">Case constant to compare the key against</param>
/// <param name="targetLabel">Target label to branch to if key = stringConstant</param>
/// <param name="stringEqualityMethodRef">String equality method</param>
private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, Microsoft.Cci.IReference stringEqualityMethodRef)
{
// Emit compare and branch:
// if (key == stringConstant)
// goto targetLabel;
Debug.Assert(stringEqualityMethodRef != null);
#if DEBUG
var assertDiagnostics = DiagnosticBag.GetInstance();
Debug.Assert(stringEqualityMethodRef == _module.Translate((MethodSymbol)_module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__op_Equality), (CSharpSyntaxNode)syntaxNode, assertDiagnostics));
assertDiagnostics.Free();
#endif
// static bool String.Equals(string a, string b)
// pop 2 (a, b)
// push 1 (bool return value)
// stackAdjustment = (pushCount - popCount) = -1
_builder.EmitLoad(key);
_builder.EmitConstantValue(stringConstant);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1);
_builder.EmitToken(stringEqualityMethodRef, syntaxNode, _diagnostics);
// Branch to targetLabel if String.Equals returned true.
_builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse);
}
/// <summary>
/// Gets already declared and initialized local.
/// </summary>
private LocalDefinition GetLocal(BoundLocal localExpression)
{
var symbol = localExpression.LocalSymbol;
return GetLocal(symbol);
}
private LocalDefinition GetLocal(LocalSymbol symbol)
{
return _builder.LocalSlotManager.GetLocal(symbol);
}
private LocalDefinition DefineLocal(LocalSymbol local, SyntaxNode syntaxNode)
{
var dynamicTransformFlags = !local.IsCompilerGenerated && local.Type.ContainsDynamic() ?
CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, RefKind.None, 0) :
ImmutableArray<bool>.Empty;
var tupleElementNames = !local.IsCompilerGenerated && local.Type.ContainsTupleNames() ?
CSharpCompilation.TupleNamesEncoder.Encode(local.Type) :
ImmutableArray<string>.Empty;
if (local.IsConst)
{
Debug.Assert(local.HasConstantValue);
MetadataConstant compileTimeValue = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics);
LocalConstantDefinition localConstantDef = new LocalConstantDefinition(
local.Name,
local.Locations.FirstOrDefault() ?? Location.None,
compileTimeValue,
dynamicTransformFlags: dynamicTransformFlags,
tupleElementNames: tupleElementNames);
_builder.AddLocalConstantToScope(localConstantDef);
return null;
}
if (IsStackLocal(local))
{
return null;
}
LocalSlotConstraints constraints;
Cci.ITypeReference translatedType;
if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) // Excludes pointer local and string local in fixed string case.
{
Debug.Assert(local.RefKind == RefKind.None);
Debug.Assert(local.TypeWithAnnotations.Type.IsPointerType());
constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned;
PointerTypeSymbol pointerType = (PointerTypeSymbol)local.Type;
TypeSymbol pointedAtType = pointerType.PointedAtType;
// We can't declare a reference to void, so if the pointed-at type is void, use native int
// (represented here by IntPtr) instead.
translatedType = pointedAtType.IsVoidType()
? _module.GetSpecialType(SpecialType.System_IntPtr, syntaxNode, _diagnostics)
: _module.Translate(pointedAtType, syntaxNode, _diagnostics);
}
else
{
constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) |
(local.RefKind != RefKind.None ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None);
translatedType = _module.Translate(local.Type, syntaxNode, _diagnostics);
}
// Even though we don't need the token immediately, we will need it later when signature for the local is emitted.
// Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc).
_module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics);
LocalDebugId localId;
var name = GetLocalDebugName(local, out localId);
var localDef = _builder.LocalSlotManager.DeclareLocal(
type: translatedType,
symbol: local,
name: name,
kind: local.SynthesizedKind,
id: localId,
pdbAttributes: local.SynthesizedKind.PdbAttributes(),
constraints: constraints,
dynamicTransformFlags: dynamicTransformFlags,
tupleElementNames: tupleElementNames,
isSlotReusable: local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release));
// If named, add it to the local debug scope.
if (localDef.Name != null &&
!(local.SynthesizedKind == SynthesizedLocalKind.UserDefined &&
// Visibility scope of such locals is represented by BoundScope node.
(local.ScopeDesignatorOpt?.Kind() is SyntaxKind.SwitchSection or SyntaxKind.SwitchExpressionArm)))
{
_builder.AddLocalToScope(localDef);
}
return localDef;
}
/// <summary>
/// Gets the name and id of the local that are going to be generated into the debug metadata.
/// </summary>
private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId)
{
localId = LocalDebugId.None;
if (local.IsImportedFromMetadata)
{
return local.Name;
}
var localKind = local.SynthesizedKind;
// only user-defined locals should be named during lowering:
Debug.Assert((local.Name == null) == (localKind != SynthesizedLocalKind.UserDefined));
// Generating debug names for instrumentation payloads should be allowed, as described in https://github.com/dotnet/roslyn/issues/11024.
// For now, skip naming locals generated by instrumentation as they might not have a local syntax offset.
// Locals generated by instrumentation might exist in methods which do not contain a body (auto property initializers).
if (!localKind.IsLongLived() || localKind == SynthesizedLocalKind.InstrumentationPayload)
{
return null;
}
if (_ilEmitStyle == ILEmitStyle.Debug)
{
var syntax = local.GetDeclaratorSyntax();
int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree);
int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset);
// user-defined locals should have 0 ordinal:
Debug.Assert(ordinal == 0 || localKind != SynthesizedLocalKind.UserDefined);
localId = new LocalDebugId(syntaxOffset, ordinal);
}
return local.Name ?? GeneratedNames.MakeSynthesizedLocalName(localKind, ref _uniqueNameId);
}
private bool IsSlotReusable(LocalSymbol local)
{
return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release);
}
/// <summary>
/// Releases a local.
/// </summary>
private void FreeLocal(LocalSymbol local)
{
// TODO: releasing named locals is NYI.
if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local))
{
_builder.LocalSlotManager.FreeLocal(local);
}
}
/// <summary>
/// Allocates a temp without identity.
/// </summary>
private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = LocalSlotConstraints.None)
{
return _builder.LocalSlotManager.AllocateSlot(
_module.Translate(type, syntaxNode, _diagnostics),
slotConstraints);
}
/// <summary>
/// Frees a temp.
/// </summary>
private void FreeTemp(LocalDefinition temp)
{
_builder.LocalSlotManager.FreeSlot(temp);
}
/// <summary>
/// Frees an optional temp.
/// </summary>
private void FreeOptTemp(LocalDefinition temp)
{
if (temp != null)
{
FreeTemp(temp);
}
}
/// <summary>
/// Clones all labels used in a finally block.
/// This allows creating an emittable clone of finally.
/// It is safe to do because no branches can go in or out of the finally handler.
/// </summary>
private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private Dictionary<LabelSymbol, GeneratedLabelSymbol> _labelClones;
private FinallyCloner() { }
/// <summary>
/// The argument is BoundTryStatement (and not a BoundBlock) specifically
/// to support only Finally blocks where it is guaranteed to not have incoming or leaving branches.
/// </summary>
public static BoundBlock MakeFinallyClone(BoundTryStatement node)
{
var cloner = new FinallyCloner();
return (BoundBlock)cloner.Visit(node.FinallyBlockOpt);
}
public override BoundNode VisitLabelStatement(BoundLabelStatement node)
{
return node.Update(GetLabelClone(node.Label));
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
var labelClone = GetLabelClone(node.Label);
// expressions do not contain labels or branches
BoundExpression caseExpressionOpt = node.CaseExpressionOpt;
// expressions do not contain labels or branches
BoundLabel labelExpressionOpt = node.LabelExpressionOpt;
return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt);
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
var labelClone = GetLabelClone(node.Label);
// expressions do not contain labels or branches
BoundExpression condition = node.Condition;
return node.Update(condition, node.JumpIfTrue, labelClone);
}
public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node)
{
// expressions do not contain labels or branches
BoundExpression expression = node.Expression;
var defaultClone = GetLabelClone(node.DefaultLabel);
var casesBuilder = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance();
foreach (var (value, label) in node.Cases)
{
casesBuilder.Add((value, GetLabelClone(label)));
}
return node.Update(expression, casesBuilder.ToImmutableAndFree(), defaultClone, node.EqualityMethod);
}
public override BoundNode VisitExpressionStatement(BoundExpressionStatement node)
{
// expressions do not contain labels or branches
return node;
}
private GeneratedLabelSymbol GetLabelClone(LabelSymbol label)
{
var labelClones = _labelClones;
if (labelClones == null)
{
_labelClones = labelClones = new Dictionary<LabelSymbol, GeneratedLabelSymbol>();
}
GeneratedLabelSymbol clone;
if (!labelClones.TryGetValue(label, out clone))
{
clone = new GeneratedLabelSymbol("cloned_" + label.Name);
labelClones.Add(label, clone);
}
return clone;
}
}
}
}
| // 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.Linq;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.Binder;
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
internal partial class CodeGenerator
{
private void EmitStatement(BoundStatement statement)
{
switch (statement.Kind)
{
case BoundKind.Block:
EmitBlock((BoundBlock)statement);
break;
case BoundKind.Scope:
EmitScope((BoundScope)statement);
break;
case BoundKind.SequencePoint:
this.EmitSequencePointStatement((BoundSequencePoint)statement);
break;
case BoundKind.SequencePointWithSpan:
this.EmitSequencePointStatement((BoundSequencePointWithSpan)statement);
break;
case BoundKind.SavePreviousSequencePoint:
this.EmitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)statement);
break;
case BoundKind.RestorePreviousSequencePoint:
this.EmitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)statement);
break;
case BoundKind.StepThroughSequencePoint:
this.EmitStepThroughSequencePoint((BoundStepThroughSequencePoint)statement);
break;
case BoundKind.ExpressionStatement:
EmitExpression(((BoundExpressionStatement)statement).Expression, false);
break;
case BoundKind.StatementList:
EmitStatementList((BoundStatementList)statement);
break;
case BoundKind.ReturnStatement:
EmitReturnStatement((BoundReturnStatement)statement);
break;
case BoundKind.GotoStatement:
EmitGotoStatement((BoundGotoStatement)statement);
break;
case BoundKind.LabelStatement:
EmitLabelStatement((BoundLabelStatement)statement);
break;
case BoundKind.ConditionalGoto:
EmitConditionalGoto((BoundConditionalGoto)statement);
break;
case BoundKind.ThrowStatement:
EmitThrowStatement((BoundThrowStatement)statement);
break;
case BoundKind.TryStatement:
EmitTryStatement((BoundTryStatement)statement);
break;
case BoundKind.SwitchDispatch:
EmitSwitchDispatch((BoundSwitchDispatch)statement);
break;
case BoundKind.StateMachineScope:
EmitStateMachineScope((BoundStateMachineScope)statement);
break;
case BoundKind.NoOpStatement:
EmitNoOpStatement((BoundNoOpStatement)statement);
break;
default:
// Code gen should not be invoked if there are errors.
throw ExceptionUtilities.UnexpectedValue(statement.Kind);
}
#if DEBUG
if (_stackLocals == null || _stackLocals.Count == 0)
{
_builder.AssertStackEmpty();
}
#endif
ReleaseExpressionTemps();
}
private int EmitStatementAndCountInstructions(BoundStatement statement)
{
int n = _builder.InstructionsEmitted;
this.EmitStatement(statement);
return _builder.InstructionsEmitted - n;
}
private void EmitStatementList(BoundStatementList list)
{
for (int i = 0, n = list.Statements.Length; i < n; i++)
{
EmitStatement(list.Statements[i]);
}
}
private void EmitNoOpStatement(BoundNoOpStatement statement)
{
switch (statement.Flavor)
{
case NoOpStatementFlavor.Default:
if (_ilEmitStyle == ILEmitStyle.Debug)
{
_builder.EmitOpCode(ILOpCode.Nop);
}
break;
case NoOpStatementFlavor.AwaitYieldPoint:
Debug.Assert((_asyncYieldPoints == null) == (_asyncResumePoints == null));
if (_asyncYieldPoints == null)
{
_asyncYieldPoints = ArrayBuilder<int>.GetInstance();
_asyncResumePoints = ArrayBuilder<int>.GetInstance();
}
Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
_asyncYieldPoints.Add(_builder.AllocateILMarker());
break;
case NoOpStatementFlavor.AwaitResumePoint:
Debug.Assert(_asyncYieldPoints != null);
Debug.Assert(_asyncYieldPoints != null);
_asyncResumePoints.Add(_builder.AllocateILMarker());
Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
break;
default:
throw ExceptionUtilities.UnexpectedValue(statement.Flavor);
}
}
private void EmitThrowStatement(BoundThrowStatement node)
{
EmitThrow(node.ExpressionOpt);
}
private void EmitThrow(BoundExpression thrown)
{
if (thrown != null)
{
this.EmitExpression(thrown, true);
var exprType = thrown.Type;
// Expression type will be null for "throw null;".
if (exprType?.TypeKind == TypeKind.TypeParameter)
{
this.EmitBox(exprType, thrown.Syntax);
}
}
_builder.EmitThrow(isRethrow: thrown == null);
}
private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto)
{
object label = boundConditionalGoto.Label;
Debug.Assert(label != null);
EmitCondBranch(boundConditionalGoto.Condition, ref label, boundConditionalGoto.JumpIfTrue);
}
// 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed
//pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at
//the next instruction.
private static bool CanPassToBrfalse(TypeSymbol ts)
{
if (ts.IsEnumType())
{
// valid enums are all primitives
return true;
}
var tc = ts.PrimitiveTypeCode;
switch (tc)
{
case Microsoft.Cci.PrimitiveTypeCode.Float32:
case Microsoft.Cci.PrimitiveTypeCode.Float64:
return false;
case Microsoft.Cci.PrimitiveTypeCode.NotPrimitive:
// if this is a generic type param, verifier will want us to box
// EmitCondBranch knows that
return ts.IsReferenceType;
default:
Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Invalid);
Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Void);
return true;
}
}
private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense)
{
var opKind = condition.OperatorKind.Operator();
Debug.Assert(opKind == BinaryOperatorKind.Equal ||
opKind == BinaryOperatorKind.NotEqual);
BoundExpression nonConstOp;
BoundExpression constOp = (condition.Left.ConstantValue != null) ? condition.Left : null;
if (constOp != null)
{
nonConstOp = condition.Right;
}
else
{
constOp = (condition.Right.ConstantValue != null) ? condition.Right : null;
if (constOp == null)
{
return null;
}
nonConstOp = condition.Left;
}
var nonConstType = nonConstOp.Type;
if (!CanPassToBrfalse(nonConstType))
{
return null;
}
bool isBool = nonConstType.PrimitiveTypeCode == Microsoft.Cci.PrimitiveTypeCode.Boolean;
bool isZero = constOp.ConstantValue.IsDefaultValue;
// bool is special, only it can be compared to true and false...
if (!isBool && !isZero)
{
return null;
}
// if comparing to zero, flip the sense
if (isZero)
{
sense = !sense;
}
// if comparing != flip the sense
if (opKind == BinaryOperatorKind.NotEqual)
{
sense = !sense;
}
return nonConstOp;
}
private const int IL_OP_CODE_ROW_LENGTH = 4;
private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[]
{
// < <= > >=
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed
ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert
ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert
};
/// <summary>
/// Produces opcode for a jump that corresponds to given operation and sense.
/// Also produces a reverse opcode - opcode for the same condition with inverted sense.
/// </summary>
private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode)
{
int opIdx;
switch (op.OperatorKind.Operator())
{
case BinaryOperatorKind.Equal:
revOpCode = !sense ? ILOpCode.Beq : ILOpCode.Bne_un;
return sense ? ILOpCode.Beq : ILOpCode.Bne_un;
case BinaryOperatorKind.NotEqual:
revOpCode = !sense ? ILOpCode.Bne_un : ILOpCode.Beq;
return sense ? ILOpCode.Bne_un : ILOpCode.Beq;
case BinaryOperatorKind.LessThan:
opIdx = 0;
break;
case BinaryOperatorKind.LessThanOrEqual:
opIdx = 1;
break;
case BinaryOperatorKind.GreaterThan:
opIdx = 2;
break;
case BinaryOperatorKind.GreaterThanOrEqual:
opIdx = 3;
break;
default:
throw ExceptionUtilities.UnexpectedValue(op.OperatorKind.Operator());
}
if (IsUnsignedBinaryOperator(op))
{
opIdx += 2 * IL_OP_CODE_ROW_LENGTH; //unsigned
}
else if (IsFloat(op.OperatorKind))
{
opIdx += 4 * IL_OP_CODE_ROW_LENGTH; //float
}
int revOpIdx = opIdx;
if (!sense)
{
opIdx += IL_OP_CODE_ROW_LENGTH; //invert op
}
else
{
revOpIdx += IL_OP_CODE_ROW_LENGTH; //invert rev
}
revOpCode = s_condJumpOpCodes[revOpIdx];
return s_condJumpOpCodes[opIdx];
}
// generate a jump to dest if (condition == sense) is true
private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense)
{
_recursionDepth++;
if (_recursionDepth > 1)
{
StackGuard.EnsureSufficientExecutionStack(_recursionDepth);
EmitCondBranchCore(condition, ref dest, sense);
}
else
{
EmitCondBranchCoreWithStackGuard(condition, ref dest, sense);
}
_recursionDepth--;
}
private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense)
{
Debug.Assert(_recursionDepth == 1);
try
{
EmitCondBranchCore(condition, ref dest, sense);
Debug.Assert(_recursionDepth == 1);
}
catch (InsufficientExecutionStackException)
{
_diagnostics.Add(ErrorCode.ERR_InsufficientStack,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition));
throw new EmitCancelledException();
}
}
private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense)
{
oneMoreTime:
ILOpCode ilcode;
if (condition.ConstantValue != null)
{
bool taken = condition.ConstantValue.IsDefaultValue != sense;
if (taken)
{
dest = dest ?? new object();
_builder.EmitBranch(ILOpCode.Br, dest);
}
else
{
// otherwise this branch will never be taken, so just fall through...
}
return;
}
switch (condition.Kind)
{
case BoundKind.BinaryOperator:
var binOp = (BoundBinaryOperator)condition;
bool testBothArgs = sense;
switch (binOp.OperatorKind.OperatorWithLogical())
{
case BinaryOperatorKind.LogicalOr:
testBothArgs = !testBothArgs;
// Fall through
goto case BinaryOperatorKind.LogicalAnd;
case BinaryOperatorKind.LogicalAnd:
if (testBothArgs)
{
// gotoif(a != sense) fallThrough
// gotoif(b == sense) dest
// fallThrough:
object fallThrough = null;
EmitCondBranch(binOp.Left, ref fallThrough, !sense);
EmitCondBranch(binOp.Right, ref dest, sense);
if (fallThrough != null)
{
_builder.MarkLabel(fallThrough);
}
}
else
{
// gotoif(a == sense) labDest
// gotoif(b == sense) labDest
EmitCondBranch(binOp.Left, ref dest, sense);
condition = binOp.Right;
goto oneMoreTime;
}
return;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
var reduced = TryReduce(binOp, ref sense);
if (reduced != null)
{
condition = reduced;
goto oneMoreTime;
}
// Fall through
goto case BinaryOperatorKind.LessThan;
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
EmitExpression(binOp.Left, true);
EmitExpression(binOp.Right, true);
ILOpCode revOpCode;
ilcode = CodeForJump(binOp, sense, out revOpCode);
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest, revOpCode);
return;
}
// none of above.
// then it is regular binary expression - Or, And, Xor ...
goto default;
case BoundKind.LoweredConditionalAccess:
{
var ca = (BoundLoweredConditionalAccess)condition;
var receiver = ca.Receiver;
var receiverType = receiver.Type;
// we need a copy if we deal with nonlocal value (to capture the value)
// or if we deal with stack local (reads are destructive)
var complexCase = !receiverType.IsReferenceType ||
LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
(receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) ||
(ca.WhenNullOpt?.IsDefaultValue() == false);
if (complexCase)
{
goto default;
}
if (sense)
{
// gotoif(receiver != null) fallThrough
// gotoif(receiver.Access) dest
// fallThrough:
object fallThrough = null;
EmitCondBranch(receiver, ref fallThrough, sense: false);
// receiver is a reference type, and we only intend to read it
EmitReceiverRef(receiver, AddressKind.ReadOnly);
EmitCondBranch(ca.WhenNotNull, ref dest, sense: true);
if (fallThrough != null)
{
_builder.MarkLabel(fallThrough);
}
}
else
{
// gotoif(receiver == null) labDest
// gotoif(!receiver.Access) labDest
EmitCondBranch(receiver, ref dest, sense: false);
// receiver is a reference type, and we only intend to read it
EmitReceiverRef(receiver, AddressKind.ReadOnly);
condition = ca.WhenNotNull;
goto oneMoreTime;
}
}
return;
case BoundKind.UnaryOperator:
var unOp = (BoundUnaryOperator)condition;
if (unOp.OperatorKind == UnaryOperatorKind.BoolLogicalNegation)
{
sense = !sense;
condition = unOp.Operand;
goto oneMoreTime;
}
goto default;
case BoundKind.IsOperator:
var isOp = (BoundIsOperator)condition;
var operand = isOp.Operand;
EmitExpression(operand, true);
Debug.Assert((object)operand.Type != null);
if (!operand.Type.IsVerifierReference())
{
// box the operand for isinst if it is not a verifier reference
EmitBox(operand.Type, operand.Syntax);
}
_builder.EmitOpCode(ILOpCode.Isinst);
EmitSymbolToken(isOp.TargetType.Type, isOp.TargetType.Syntax);
ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest);
return;
case BoundKind.Sequence:
var seq = (BoundSequence)condition;
EmitSequenceCondBranch(seq, ref dest, sense);
return;
default:
EmitExpression(condition, true);
var conditionType = condition.Type;
if (conditionType.IsReferenceType && !conditionType.IsVerifierReference())
{
EmitBox(conditionType, condition.Syntax);
}
ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
dest = dest ?? new object();
_builder.EmitBranch(ilcode, dest);
return;
}
}
private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense)
{
DefineLocals(sequence);
EmitSideEffects(sequence);
EmitCondBranch(sequence.Value, ref dest, sense);
// sequence is used as a value, can release all locals
FreeLocals(sequence);
}
private void EmitLabelStatement(BoundLabelStatement boundLabelStatement)
{
_builder.MarkLabel(boundLabelStatement.Label);
}
private void EmitGotoStatement(BoundGotoStatement boundGotoStatement)
{
_builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label);
}
// used by HandleReturn method which tries to inject
// indirect ret sequence as a last statement in the block
// that is the last statement of the current method
// NOTE: it is important that there is no code after this "ret"
// it is desirable, for debug purposes, that this ret is emitted inside top level { }
private bool IsLastBlockInMethod(BoundBlock block)
{
if (_boundBody == block)
{
return true;
}
//sometimes top level node is a statement list containing
//epilogue and then a block. If we are having that block, it will do.
var list = _boundBody as BoundStatementList;
if (list != null && list.Statements.LastOrDefault() == block)
{
return true;
}
return false;
}
private void EmitBlock(BoundBlock block)
{
var hasLocals = !block.Locals.IsEmpty;
if (hasLocals)
{
_builder.OpenLocalScope();
foreach (var local in block.Locals)
{
Debug.Assert(local.RefKind == RefKind.None || local.SynthesizedKind.IsLongLived(),
"A ref local ended up in a block and claims it is shortlived. That is dangerous. Are we sure it is short lived?");
var declaringReferences = local.DeclaringSyntaxReferences;
DefineLocal(local, !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : block.Syntax);
}
}
EmitStatements(block.Statements);
if (_indirectReturnState == IndirectReturnState.Needed &&
IsLastBlockInMethod(block))
{
HandleReturn();
}
if (hasLocals)
{
foreach (var local in block.Locals)
{
FreeLocal(local);
}
_builder.CloseLocalScope();
}
}
private void EmitStatements(ImmutableArray<BoundStatement> statements)
{
foreach (var statement in statements)
{
EmitStatement(statement);
}
}
private void EmitScope(BoundScope block)
{
Debug.Assert(!block.Locals.IsEmpty);
_builder.OpenLocalScope();
foreach (var local in block.Locals)
{
Debug.Assert(local.Name != null);
Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.UserDefined &&
(local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchSection || local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchExpressionArm));
if (!local.IsConst && !IsStackLocal(local))
{
_builder.AddLocalToScope(_builder.LocalSlotManager.GetLocal(local));
}
}
EmitStatements(block.Statements);
_builder.CloseLocalScope();
}
private void EmitStateMachineScope(BoundStateMachineScope scope)
{
_builder.OpenLocalScope(ScopeType.StateMachineVariable);
foreach (var field in scope.Fields)
{
if (field.SlotIndex >= 0)
{
_builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex);
}
}
EmitStatement(scope.Statement);
_builder.CloseLocalScope();
}
// There are two ways a value can be returned from a function:
// - Using ret opcode
// - Store return value if any to a predefined temp and jump to the epilogue block
// Sometimes ret is not an option (try/catch etc.). We also do this when emitting
// debuggable code. This function is a stub for the logic that decides that.
private bool ShouldUseIndirectReturn()
{
// If the method/lambda body is a block we define a sequence point for the closing brace of the body
// and associate it with the ret instruction. If there is a return statement we need to store the value
// to a long-lived synthesized local since a sequence point requires an empty evaluation stack.
//
// The emitted pattern is:
// <evaluate return statement expression>
// stloc $ReturnValue
// ldloc $ReturnValue // sequence point
// ret
//
// Do not emit this pattern if the method doesn't include user code or doesn't have a block body.
return _ilEmitStyle == ILEmitStyle.Debug && _method.GenerateDebugInfo && _methodBodySyntaxOpt?.IsKind(SyntaxKind.Block) == true ||
_builder.InExceptionHandler;
}
// Compiler generated return mapped to a block is very likely the synthetic return
// that was added at the end of the last block of a void method by analysis.
// This is likely to be the last return in the method, so if we have not yet
// emitted return sequence, it is convenient to do it right here (if we can).
private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement)
{
return boundReturnStatement.WasCompilerGenerated &&
(boundReturnStatement.Syntax.IsKind(SyntaxKind.Block) || _method?.IsImplicitConstructor == true) &&
!_builder.InExceptionHandler;
}
private void EmitReturnStatement(BoundReturnStatement boundReturnStatement)
{
var expressionOpt = boundReturnStatement.ExpressionOpt;
if (boundReturnStatement.RefKind == RefKind.None)
{
this.EmitExpression(expressionOpt, true);
}
else
{
// NOTE: passing "ReadOnlyStrict" here.
// we should never return an address of a copy
var unexpectedTemp = this.EmitAddress(expressionOpt, this._method.RefKind == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
Debug.Assert(unexpectedTemp == null, "ref-returning a temp?");
}
if (ShouldUseIndirectReturn())
{
if (expressionOpt != null)
{
_builder.EmitLocalStore(LazyReturnTemp);
}
if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement))
{
HandleReturn();
}
else
{
_builder.EmitBranch(ILOpCode.Br, s_returnLabel);
if (_indirectReturnState == IndirectReturnState.NotNeeded)
{
_indirectReturnState = IndirectReturnState.Needed;
}
}
}
else
{
if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement))
{
if (expressionOpt != null)
{
_builder.EmitLocalStore(LazyReturnTemp);
}
HandleReturn();
}
else
{
if (expressionOpt != null)
{
// Ensure the return type has been translated. (Necessary
// for cases of untranslated anonymous types.)
_module.Translate(expressionOpt.Type, boundReturnStatement.Syntax, _diagnostics);
}
_builder.EmitRet(expressionOpt == null);
}
}
}
private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false)
{
Debug.Assert(!statement.CatchBlocks.IsDefault);
// Stack must be empty at beginning of try block.
_builder.AssertStackEmpty();
// IL requires catches and finally block to be distinct try
// blocks so if the source contained both a catch and
// a finally, nested scopes are emitted.
bool emitNestedScopes = (!emitCatchesOnly &&
(statement.CatchBlocks.Length > 0) &&
(statement.FinallyBlockOpt != null));
_builder.OpenLocalScope(ScopeType.TryCatchFinally);
_builder.OpenLocalScope(ScopeType.Try);
// IL requires catches and finally block to be distinct try
// blocks so if the source contained both a catch and
// a finally, nested scopes are emitted.
_tryNestingLevel++;
if (emitNestedScopes)
{
EmitTryStatement(statement, emitCatchesOnly: true);
}
else
{
EmitBlock(statement.TryBlock);
}
_tryNestingLevel--;
// Close the Try scope
_builder.CloseLocalScope();
if (!emitNestedScopes)
{
foreach (var catchBlock in statement.CatchBlocks)
{
EmitCatchBlock(catchBlock);
}
}
if (!emitCatchesOnly && (statement.FinallyBlockOpt != null))
{
_builder.OpenLocalScope(statement.PreferFaultHandler ? ScopeType.Fault : ScopeType.Finally);
EmitBlock(statement.FinallyBlockOpt);
// close Finally scope
_builder.CloseLocalScope();
// close the whole try statement scope
_builder.CloseLocalScope();
// in a case where we emit surrogate Finally using Fault, we emit code like this
//
// try{
// . . .
// } fault {
// finallyBlock;
// }
// finallyBlock;
//
// This is where the second copy of finallyBlock is emitted.
if (statement.PreferFaultHandler)
{
var finallyClone = FinallyCloner.MakeFinallyClone(statement);
EmitBlock(finallyClone);
}
}
else
{
// close the whole try statement scope
_builder.CloseLocalScope();
}
}
/// <remarks>
/// The interesting part in the following method is the support for exception filters.
/// === Example:
///
/// try
/// {
/// TryBlock
/// }
/// catch (ExceptionType ex) when (Condition)
/// {
/// Handler
/// }
///
/// gets emitted as something like ===>
///
/// Try
/// TryBlock
/// Filter
/// var tmp = Pop() as {ExceptionType}
/// if (tmp == null)
/// {
/// Push 0
/// }
/// else
/// {
/// ex = tmp
/// Push Condition ? 1 : 0
/// }
/// End Filter // leaves 1 or 0 on the stack
/// Catch // gets called after finalization of nested exception frames if condition above produced 1
/// Pop // CLR pushes the exception object again
/// variable ex can be used here
/// Handler
/// EndCatch
///
/// When evaluating `Condition` requires additional statements be executed first, those
/// statements are stored in `catchBlock.ExceptionFilterPrologueOpt` and emitted before the condition.
/// </remarks>
private void EmitCatchBlock(BoundCatchBlock catchBlock)
{
object typeCheckFailedLabel = null;
_builder.AdjustStack(1); // Account for exception on the stack.
// Open appropriate exception handler scope. (Catch or Filter)
// if it is a Filter, emit prologue that checks if the type on the stack
// converts to what we want.
if (catchBlock.ExceptionFilterOpt == null)
{
var exceptionType = ((object)catchBlock.ExceptionTypeOpt != null) ?
_module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics) :
_module.GetSpecialType(SpecialType.System_Object, catchBlock.Syntax, _diagnostics);
_builder.OpenLocalScope(ScopeType.Catch, exceptionType);
RecordAsyncCatchHandlerOffset(catchBlock);
// Dev12 inserts the sequence point on catch clause without a filter, just before
// the exception object is assigned to the variable.
//
// Also in Dev12 the exception variable scope span starts right after the stloc instruction and
// ends right before leave instruction. So when stopped at the sequence point Dev12 inserts,
// the exception variable is not visible.
if (_emitPdbSequencePoints)
{
var syntax = catchBlock.Syntax as CatchClauseSyntax;
if (syntax != null)
{
TextSpan spSpan;
var declaration = syntax.Declaration;
if (declaration == null)
{
spSpan = syntax.CatchKeyword.Span;
}
else
{
spSpan = TextSpan.FromBounds(syntax.SpanStart, syntax.Declaration.Span.End);
}
this.EmitSequencePoint(catchBlock.SyntaxTree, spSpan);
}
}
}
else
{
_builder.OpenLocalScope(ScopeType.Filter);
RecordAsyncCatchHandlerOffset(catchBlock);
// Filtering starts with simulating regular catch through a
// type check. If this is not our type then we are done.
var typeCheckPassedLabel = new object();
typeCheckFailedLabel = new object();
if ((object)catchBlock.ExceptionTypeOpt != null)
{
var exceptionType = _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics);
_builder.EmitOpCode(ILOpCode.Isinst);
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics);
_builder.EmitOpCode(ILOpCode.Dup);
_builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel);
_builder.EmitOpCode(ILOpCode.Pop);
_builder.EmitIntConstant(0);
_builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel);
}
else
{
// no formal exception type means we always pass the check
}
_builder.MarkLabel(typeCheckPassedLabel);
}
foreach (var local in catchBlock.Locals)
{
var declaringReferences = local.DeclaringSyntaxReferences;
var localSyntax = !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : catchBlock.Syntax;
DefineLocal(local, localSyntax);
}
var exceptionSourceOpt = catchBlock.ExceptionSourceOpt;
if (exceptionSourceOpt != null)
{
// here we have our exception on the stack in a form of a reference type (O)
// it means that we have to "unbox" it before storing to the local
// if exception's type is a generic type parameter.
if (!exceptionSourceOpt.Type.IsVerifierReference())
{
Debug.Assert(exceptionSourceOpt.Type.IsTypeParameter()); // only expecting type parameters
_builder.EmitOpCode(ILOpCode.Unbox_any);
EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax);
}
BoundExpression exceptionSource = exceptionSourceOpt;
while (exceptionSource.Kind == BoundKind.Sequence)
{
var seq = (BoundSequence)exceptionSource;
Debug.Assert(seq.Locals.IsDefaultOrEmpty);
EmitSideEffects(seq);
exceptionSource = seq.Value;
}
switch (exceptionSource.Kind)
{
case BoundKind.Local:
var exceptionSourceLocal = (BoundLocal)exceptionSource;
Debug.Assert(exceptionSourceLocal.LocalSymbol.RefKind == RefKind.None);
if (!IsStackLocal(exceptionSourceLocal.LocalSymbol))
{
_builder.EmitLocalStore(GetLocal(exceptionSourceLocal));
}
break;
case BoundKind.FieldAccess:
var left = (BoundFieldAccess)exceptionSource;
Debug.Assert(!left.FieldSymbol.IsStatic, "Not supported");
Debug.Assert(!left.ReceiverOpt.Type.IsTypeParameter());
var stateMachineField = left.FieldSymbol as StateMachineFieldSymbol;
if (((object)stateMachineField != null) && (stateMachineField.SlotIndex >= 0))
{
_builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineField.SlotIndex);
}
// When assigning to a field
// we need to push param address below the exception
var temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax);
_builder.EmitLocalStore(temp);
var receiverTemp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable);
Debug.Assert(receiverTemp == null);
_builder.EmitLocalLoad(temp);
FreeTemp(temp);
EmitFieldStore(left);
break;
default:
throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind);
}
}
else
{
_builder.EmitOpCode(ILOpCode.Pop);
}
if (catchBlock.ExceptionFilterPrologueOpt != null)
{
Debug.Assert(_builder.IsStackEmpty);
EmitStatements(catchBlock.ExceptionFilterPrologueOpt.Statements);
}
// Emit the actual filter expression, if we have one, and normalize
// results.
if (catchBlock.ExceptionFilterOpt != null)
{
EmitCondExpr(catchBlock.ExceptionFilterOpt, true);
// Normalize the return value because values other than 0 or 1
// produce unspecified results.
_builder.EmitIntConstant(0);
_builder.EmitOpCode(ILOpCode.Cgt_un);
_builder.MarkLabel(typeCheckFailedLabel);
// Now we are starting the actual handler
_builder.MarkFilterConditionEnd();
// Pop the exception; it should have already been stored to the
// variable by the filter.
_builder.EmitOpCode(ILOpCode.Pop);
}
EmitBlock(catchBlock.Body);
_builder.CloseLocalScope();
}
private void RecordAsyncCatchHandlerOffset(BoundCatchBlock catchBlock)
{
if (catchBlock.IsSynthesizedAsyncCatchAll)
{
Debug.Assert(_asyncCatchHandlerOffset < 0); // only one expected
_asyncCatchHandlerOffset = _builder.AllocateILMarker();
}
}
private void EmitSwitchDispatch(BoundSwitchDispatch dispatch)
{
// Switch expression must have a valid switch governing type
Debug.Assert((object)dispatch.Expression.Type != null);
Debug.Assert(dispatch.Expression.Type.IsValidV6SwitchGoverningType());
// We must have rewritten nullable switch expression into non-nullable constructs.
Debug.Assert(!dispatch.Expression.Type.IsNullableType());
// This must be used only for nontrivial dispatches.
Debug.Assert(dispatch.Cases.Any());
EmitSwitchHeader(
dispatch.Expression,
dispatch.Cases.Select(p => new KeyValuePair<ConstantValue, object>(p.value, p.label)).ToArray(),
dispatch.DefaultLabel,
dispatch.EqualityMethod);
}
private void EmitSwitchHeader(
BoundExpression expression,
KeyValuePair<ConstantValue, object>[] switchCaseLabels,
LabelSymbol fallThroughLabel,
MethodSymbol equalityMethod)
{
Debug.Assert(expression.ConstantValue == null);
Debug.Assert((object)expression.Type != null &&
expression.Type.IsValidV6SwitchGoverningType());
Debug.Assert(switchCaseLabels.Length > 0);
Debug.Assert(switchCaseLabels != null);
LocalDefinition temp = null;
LocalOrParameter key;
BoundSequence sequence = null;
if (expression.Kind == BoundKind.Sequence)
{
sequence = (BoundSequence)expression;
DefineLocals(sequence);
EmitSideEffects(sequence);
expression = sequence.Value;
}
if (expression.Kind == BoundKind.SequencePointExpression)
{
var sequencePointExpression = (BoundSequencePointExpression)expression;
EmitSequencePoint(sequencePointExpression);
expression = sequencePointExpression.Expression;
}
switch (expression.Kind)
{
case BoundKind.Local:
var local = ((BoundLocal)expression).LocalSymbol;
if (local.RefKind == RefKind.None && !IsStackLocal(local))
{
key = this.GetLocal(local);
break;
}
goto default;
case BoundKind.Parameter:
var parameter = (BoundParameter)expression;
if (parameter.ParameterSymbol.RefKind == RefKind.None)
{
key = ParameterSlot(parameter);
break;
}
goto default;
default:
EmitExpression(expression, true);
temp = AllocateTemp(expression.Type, expression.Syntax);
_builder.EmitLocalStore(temp);
key = temp;
break;
}
// Emit switch jump table
if (expression.Type.SpecialType != SpecialType.System_String)
{
_builder.EmitIntegerSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Type.EnumUnderlyingTypeOrSelf().PrimitiveTypeCode);
}
else
{
this.EmitStringSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Syntax, equalityMethod);
}
if (temp != null)
{
FreeTemp(temp);
}
if (sequence != null)
{
// sequence was used as a value, can release all its locals.
FreeLocals(sequence);
}
}
private void EmitStringSwitchJumpTable(
KeyValuePair<ConstantValue, object>[] switchCaseLabels,
LabelSymbol fallThroughLabel,
LocalOrParameter key,
SyntaxNode syntaxNode,
MethodSymbol equalityMethod)
{
LocalDefinition keyHash = null;
// Condition is necessary, but not sufficient (e.g. might be missing a special or well-known member).
if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, switchCaseLabels.Length))
{
Debug.Assert(_module.SupportsPrivateImplClass);
var privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics);
Cci.IReference stringHashMethodRef = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName);
// Heuristics and well-known member availability determine the existence
// of this helper. Rather than reproduce that (language-specific) logic here,
// we simply check for the information we really want - whether the helper is
// available.
if (stringHashMethodRef != null)
{
// static uint ComputeStringHash(string s)
// pop 1 (s)
// push 1 (uint return value)
// stackAdjustment = (pushCount - popCount) = 0
_builder.EmitLoad(key);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
_builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics);
var UInt32Type = _module.Compilation.GetSpecialType(SpecialType.System_UInt32);
keyHash = AllocateTemp(UInt32Type, syntaxNode);
_builder.EmitLocalStore(keyHash);
}
}
Cci.IReference stringEqualityMethodRef = _module.Translate(equalityMethod, syntaxNode, _diagnostics);
Cci.IMethodReference stringLengthRef = null;
var stringLengthMethod = _module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__Length) as MethodSymbol;
if (stringLengthMethod != null && !stringLengthMethod.HasUseSiteError)
{
stringLengthRef = _module.Translate(stringLengthMethod, syntaxNode, _diagnostics);
}
SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate =
(keyArg, stringConstant, targetLabel) =>
{
if (stringConstant == ConstantValue.Null)
{
// if (key == null)
// goto targetLabel
_builder.EmitLoad(keyArg);
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
}
else if (stringConstant.StringValue.Length == 0 && stringLengthRef != null)
{
// if (key != null && key.Length == 0)
// goto targetLabel
object skipToNext = new object();
_builder.EmitLoad(keyArg);
_builder.EmitBranch(ILOpCode.Brfalse, skipToNext, ILOpCode.Brtrue);
_builder.EmitLoad(keyArg);
// Stack: key --> length
_builder.EmitOpCode(ILOpCode.Call, 0);
var diag = DiagnosticBag.GetInstance();
_builder.EmitToken(stringLengthRef, null, diag);
Debug.Assert(diag.IsEmptyWithoutResolution);
diag.Free();
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
_builder.MarkLabel(skipToNext);
}
else
{
this.EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, stringEqualityMethodRef);
}
};
_builder.EmitStringSwitchJumpTable(
caseLabels: switchCaseLabels,
fallThroughLabel: fallThroughLabel,
key: key,
keyHash: keyHash,
emitStringCondBranchDelegate: emitStringCondBranchDelegate,
computeStringHashcodeDelegate: SynthesizedStringSwitchHashMethod.ComputeStringHash);
if (keyHash != null)
{
FreeTemp(keyHash);
}
}
/// <summary>
/// Delegate to emit string compare call and conditional branch based on the compare result.
/// </summary>
/// <param name="key">Key to compare</param>
/// <param name="syntaxNode">Node for diagnostics.</param>
/// <param name="stringConstant">Case constant to compare the key against</param>
/// <param name="targetLabel">Target label to branch to if key = stringConstant</param>
/// <param name="stringEqualityMethodRef">String equality method</param>
private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, Microsoft.Cci.IReference stringEqualityMethodRef)
{
// Emit compare and branch:
// if (key == stringConstant)
// goto targetLabel;
Debug.Assert(stringEqualityMethodRef != null);
#if DEBUG
var assertDiagnostics = DiagnosticBag.GetInstance();
Debug.Assert(stringEqualityMethodRef == _module.Translate((MethodSymbol)_module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__op_Equality), (CSharpSyntaxNode)syntaxNode, assertDiagnostics));
assertDiagnostics.Free();
#endif
// static bool String.Equals(string a, string b)
// pop 2 (a, b)
// push 1 (bool return value)
// stackAdjustment = (pushCount - popCount) = -1
_builder.EmitLoad(key);
_builder.EmitConstantValue(stringConstant);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1);
_builder.EmitToken(stringEqualityMethodRef, syntaxNode, _diagnostics);
// Branch to targetLabel if String.Equals returned true.
_builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse);
}
/// <summary>
/// Gets already declared and initialized local.
/// </summary>
private LocalDefinition GetLocal(BoundLocal localExpression)
{
var symbol = localExpression.LocalSymbol;
return GetLocal(symbol);
}
private LocalDefinition GetLocal(LocalSymbol symbol)
{
return _builder.LocalSlotManager.GetLocal(symbol);
}
private LocalDefinition DefineLocal(LocalSymbol local, SyntaxNode syntaxNode)
{
var dynamicTransformFlags = !local.IsCompilerGenerated && local.Type.ContainsDynamic() ?
CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, RefKind.None, 0) :
ImmutableArray<bool>.Empty;
var tupleElementNames = !local.IsCompilerGenerated && local.Type.ContainsTupleNames() ?
CSharpCompilation.TupleNamesEncoder.Encode(local.Type) :
ImmutableArray<string>.Empty;
if (local.IsConst)
{
Debug.Assert(local.HasConstantValue);
MetadataConstant compileTimeValue = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics);
LocalConstantDefinition localConstantDef = new LocalConstantDefinition(
local.Name,
local.Locations.FirstOrDefault() ?? Location.None,
compileTimeValue,
dynamicTransformFlags: dynamicTransformFlags,
tupleElementNames: tupleElementNames);
_builder.AddLocalConstantToScope(localConstantDef);
return null;
}
if (IsStackLocal(local))
{
return null;
}
LocalSlotConstraints constraints;
Cci.ITypeReference translatedType;
if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) // Excludes pointer local and string local in fixed string case.
{
Debug.Assert(local.RefKind == RefKind.None);
Debug.Assert(local.TypeWithAnnotations.Type.IsPointerType());
constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned;
PointerTypeSymbol pointerType = (PointerTypeSymbol)local.Type;
TypeSymbol pointedAtType = pointerType.PointedAtType;
// We can't declare a reference to void, so if the pointed-at type is void, use native int
// (represented here by IntPtr) instead.
translatedType = pointedAtType.IsVoidType()
? _module.GetSpecialType(SpecialType.System_IntPtr, syntaxNode, _diagnostics)
: _module.Translate(pointedAtType, syntaxNode, _diagnostics);
}
else
{
constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) |
(local.RefKind != RefKind.None ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None);
translatedType = _module.Translate(local.Type, syntaxNode, _diagnostics);
}
// Even though we don't need the token immediately, we will need it later when signature for the local is emitted.
// Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc).
_module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics);
LocalDebugId localId;
var name = GetLocalDebugName(local, out localId);
var localDef = _builder.LocalSlotManager.DeclareLocal(
type: translatedType,
symbol: local,
name: name,
kind: local.SynthesizedKind,
id: localId,
pdbAttributes: local.SynthesizedKind.PdbAttributes(),
constraints: constraints,
dynamicTransformFlags: dynamicTransformFlags,
tupleElementNames: tupleElementNames,
isSlotReusable: local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release));
// If named, add it to the local debug scope.
if (localDef.Name != null &&
!(local.SynthesizedKind == SynthesizedLocalKind.UserDefined &&
// Visibility scope of such locals is represented by BoundScope node.
(local.ScopeDesignatorOpt?.Kind() is SyntaxKind.SwitchSection or SyntaxKind.SwitchExpressionArm)))
{
_builder.AddLocalToScope(localDef);
}
return localDef;
}
/// <summary>
/// Gets the name and id of the local that are going to be generated into the debug metadata.
/// </summary>
private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId)
{
localId = LocalDebugId.None;
if (local.IsImportedFromMetadata)
{
return local.Name;
}
var localKind = local.SynthesizedKind;
// only user-defined locals should be named during lowering:
Debug.Assert((local.Name == null) == (localKind != SynthesizedLocalKind.UserDefined));
// Generating debug names for instrumentation payloads should be allowed, as described in https://github.com/dotnet/roslyn/issues/11024.
// For now, skip naming locals generated by instrumentation as they might not have a local syntax offset.
// Locals generated by instrumentation might exist in methods which do not contain a body (auto property initializers).
if (!localKind.IsLongLived() || localKind == SynthesizedLocalKind.InstrumentationPayload)
{
return null;
}
if (_ilEmitStyle == ILEmitStyle.Debug)
{
var syntax = local.GetDeclaratorSyntax();
int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree);
int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset);
// user-defined locals should have 0 ordinal:
Debug.Assert(ordinal == 0 || localKind != SynthesizedLocalKind.UserDefined);
localId = new LocalDebugId(syntaxOffset, ordinal);
}
return local.Name ?? GeneratedNames.MakeSynthesizedLocalName(localKind, ref _uniqueNameId);
}
private bool IsSlotReusable(LocalSymbol local)
{
return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release);
}
/// <summary>
/// Releases a local.
/// </summary>
private void FreeLocal(LocalSymbol local)
{
// TODO: releasing named locals is NYI.
if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local))
{
_builder.LocalSlotManager.FreeLocal(local);
}
}
/// <summary>
/// Allocates a temp without identity.
/// </summary>
private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = LocalSlotConstraints.None)
{
return _builder.LocalSlotManager.AllocateSlot(
_module.Translate(type, syntaxNode, _diagnostics),
slotConstraints);
}
/// <summary>
/// Frees a temp.
/// </summary>
private void FreeTemp(LocalDefinition temp)
{
_builder.LocalSlotManager.FreeSlot(temp);
}
/// <summary>
/// Frees an optional temp.
/// </summary>
private void FreeOptTemp(LocalDefinition temp)
{
if (temp != null)
{
FreeTemp(temp);
}
}
/// <summary>
/// Clones all labels used in a finally block.
/// This allows creating an emittable clone of finally.
/// It is safe to do because no branches can go in or out of the finally handler.
/// </summary>
private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private Dictionary<LabelSymbol, GeneratedLabelSymbol> _labelClones;
private FinallyCloner() { }
/// <summary>
/// The argument is BoundTryStatement (and not a BoundBlock) specifically
/// to support only Finally blocks where it is guaranteed to not have incoming or leaving branches.
/// </summary>
public static BoundBlock MakeFinallyClone(BoundTryStatement node)
{
var cloner = new FinallyCloner();
return (BoundBlock)cloner.Visit(node.FinallyBlockOpt);
}
public override BoundNode VisitLabelStatement(BoundLabelStatement node)
{
return node.Update(GetLabelClone(node.Label));
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
var labelClone = GetLabelClone(node.Label);
// expressions do not contain labels or branches
BoundExpression caseExpressionOpt = node.CaseExpressionOpt;
// expressions do not contain labels or branches
BoundLabel labelExpressionOpt = node.LabelExpressionOpt;
return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt);
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
var labelClone = GetLabelClone(node.Label);
// expressions do not contain labels or branches
BoundExpression condition = node.Condition;
return node.Update(condition, node.JumpIfTrue, labelClone);
}
public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node)
{
// expressions do not contain labels or branches
BoundExpression expression = node.Expression;
var defaultClone = GetLabelClone(node.DefaultLabel);
var casesBuilder = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance();
foreach (var (value, label) in node.Cases)
{
casesBuilder.Add((value, GetLabelClone(label)));
}
return node.Update(expression, casesBuilder.ToImmutableAndFree(), defaultClone, node.EqualityMethod);
}
public override BoundNode VisitExpressionStatement(BoundExpressionStatement node)
{
// expressions do not contain labels or branches
return node;
}
private GeneratedLabelSymbol GetLabelClone(LabelSymbol label)
{
var labelClones = _labelClones;
if (labelClones == null)
{
_labelClones = labelClones = new Dictionary<LabelSymbol, GeneratedLabelSymbol>();
}
GeneratedLabelSymbol clone;
if (!labelClones.TryGetValue(label, out clone))
{
clone = new GeneratedLabelSymbol("cloned_" + label.Name);
labelClones.Add(label, clone);
}
return clone;
}
}
}
}
| 1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/Compilers/CSharp/Test/Semantic/Semantics/AwaitExpressionTests.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.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using System.Linq;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// Tests related to binding (but not lowering) await expressions.
/// </summary>
public class AwaitExpressionTests : CompilingTestBase
{
[Fact]
public void TestAwaitInfoExtensionMethod()
{
var text =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
static class App{
public static async Task Main(){
var x = new MyAwaitable();
x.SetValue(42);
Console.WriteLine(await x + ""!"");
}
}
struct MyAwaitable
{
private ValueTask<int> task;
private TaskCompletionSource<int> source;
private TaskCompletionSource<int> Source
{
get
{
if (source == null)
{
source = new TaskCompletionSource<int>();
task = new ValueTask<int>(source.Task);
}
return source;
}
}
internal ValueTask<int> Task
{
get
{
_ = Source;
return task;
}
}
public void SetValue(int i)
{
Source.SetResult(i);
}
}
static class MyAwaitableExtension
{
public static System.Runtime.CompilerServices.ValueTaskAwaiter<int> GetAwaiter(this MyAwaitable a)
{
return a.Task.GetAwaiter();
}
}";
var csCompilation = CreateCompilation(text, targetFramework: TargetFramework.NetCoreAppAndCSharp);
var tree = csCompilation.SyntaxTrees.Single();
var model = csCompilation.GetSemanticModel(tree);
var awaitExpression = tree.GetRoot().DescendantNodes().OfType<AwaitExpressionSyntax>().First();
Assert.Equal("await x", awaitExpression.ToString());
var info = model.GetAwaitExpressionInfo(awaitExpression);
Assert.Equal(
"System.Runtime.CompilerServices.ValueTaskAwaiter<System.Int32> MyAwaitableExtension.GetAwaiter(this MyAwaitable a)",
info.GetAwaiterMethod.ToTestDisplayString()
);
Assert.Equal(
"System.Int32 System.Runtime.CompilerServices.ValueTaskAwaiter<System.Int32>.GetResult()",
info.GetResultMethod.ToTestDisplayString()
);
Assert.Equal(
"System.Boolean System.Runtime.CompilerServices.ValueTaskAwaiter<System.Int32>.IsCompleted { get; }",
info.IsCompletedProperty.ToTestDisplayString()
);
}
[Fact]
[WorkItem(711413, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/711413")]
public void TestAwaitInfo()
{
var text =
@"using System.Threading.Tasks;
class C
{
async void Goo(Task<int> t)
{
int c = 1 + await t;
}
}";
var info = GetAwaitExpressionInfo(text);
Assert.Equal("System.Runtime.CompilerServices.TaskAwaiter<System.Int32> System.Threading.Tasks.Task<System.Int32>.GetAwaiter()", info.GetAwaiterMethod.ToTestDisplayString());
Assert.Equal("System.Int32 System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.GetResult()", info.GetResultMethod.ToTestDisplayString());
Assert.Equal("System.Boolean System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.IsCompleted { get; }", info.IsCompletedProperty.ToTestDisplayString());
}
[Fact]
[WorkItem(1084696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084696")]
public void TestAwaitInfo2()
{
var text =
@"using System;
using System.Threading.Tasks;
public class C {
public C(Task<int> t) {
Func<Task> f = async() => await t;
}
}";
var info = GetAwaitExpressionInfo(text);
Assert.Equal("System.Runtime.CompilerServices.TaskAwaiter<System.Int32> System.Threading.Tasks.Task<System.Int32>.GetAwaiter()", info.GetAwaiterMethod.ToTestDisplayString());
Assert.Equal("System.Int32 System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.GetResult()", info.GetResultMethod.ToTestDisplayString());
Assert.Equal("System.Boolean System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.IsCompleted { get; }", info.IsCompletedProperty.ToTestDisplayString());
}
[Fact]
[WorkItem(744146, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/744146")]
public void DefaultAwaitExpressionInfo()
{
AwaitExpressionInfo info = default;
Assert.Null(info.GetAwaiterMethod);
Assert.Null(info.GetResultMethod);
Assert.Null(info.IsCompletedProperty);
Assert.False(info.IsDynamic);
Assert.Equal(0, info.GetHashCode());
}
private AwaitExpressionInfo GetAwaitExpressionInfo(string text, out CSharpCompilation compilation, params DiagnosticDescription[] diagnostics)
{
var tree = Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
var comp = CreateCompilationWithMscorlib45(new SyntaxTree[] { tree }, new MetadataReference[] { SystemRef });
comp.VerifyDiagnostics(diagnostics);
compilation = comp;
var syntaxNode = (AwaitExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression).AsNode();
var treeModel = comp.GetSemanticModel(tree);
return treeModel.GetAwaitExpressionInfo(syntaxNode);
}
private AwaitExpressionInfo GetAwaitExpressionInfo(string text, params DiagnosticDescription[] diagnostics)
{
CSharpCompilation temp;
return GetAwaitExpressionInfo(text, out temp, diagnostics);
}
[Fact]
[WorkItem(748533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/748533")]
public void Bug748533()
{
var text =
@"
using System;
using System.Threading;
using System.Threading.Tasks;
class A
{
public async Task<T> GetVal<T>(T t)
{
await Task.Delay(10);
return t;
}
public async void Run<T>(T t) where T : struct
{
int tests = 0;
tests++;
dynamic f = (await GetVal((Func<Task<int>>)(async () => 1)))();
if (await f == 1)
Driver.Count++;
tests++;
dynamic ff = new Func<Task<int>>((Func<Task<int>>)(async () => 1));
if (await ff() == 1)
Driver.Count++;
Driver.Result = Driver.Count - tests;
Driver.CompletedSignal.Set();
}
}
class Driver
{
public static int Result = -1;
public static int Count = 0;
public static AutoResetEvent CompletedSignal = new AutoResetEvent(false);
static int Main()
{
var t = new A();
t.Run(6);
CompletedSignal.WaitOne();
return Driver.Result;
}
}
";
var comp = CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (16,62): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// dynamic f = (await GetVal((Func<Task<int>>)(async () => 1)))();
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(16, 62),
// (20,69): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// dynamic ff = new Func<Task<int>>((Func<Task<int>>)(async () => 1));
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(20, 69),
// (17,13): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
// if (await f == 1)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await f").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create"));
}
[Fact]
[WorkItem(576316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576316")]
public void Bug576316()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async Task Goo()
{
Console.WriteLine(new TypedReference().Equals(await Task.FromResult(0)));
}
}";
var comp = CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (8,27): error CS4007: 'await' cannot be used in an expression containing the type 'System.TypedReference'
// Console.WriteLine(new TypedReference().Equals(await Task.FromResult(0)));
Diagnostic(ErrorCode.ERR_ByRefTypeAndAwait, "await Task.FromResult(0)").WithArguments("System.TypedReference").WithLocation(8, 55));
}
[Fact]
[WorkItem(3951, "https://github.com/dotnet/roslyn/issues/3951")]
public void TestAwaitInNonAsync()
{
var text =
@"using System.Threading.Tasks;
class C
{
void Goo(Task<int> t)
{
var v = await t;
}
}";
CSharpCompilation compilation;
var info = GetAwaitExpressionInfo(text, out compilation,
// (7,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// int c = 1 + await t;
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await t").WithLocation(7, 17)
);
Assert.Equal("System.Runtime.CompilerServices.TaskAwaiter<System.Int32> System.Threading.Tasks.Task<System.Int32>.GetAwaiter()", info.GetAwaiterMethod.ToTestDisplayString());
Assert.Equal("System.Int32 System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.GetResult()", info.GetResultMethod.ToTestDisplayString());
Assert.Equal("System.Boolean System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.IsCompleted { get; }", info.IsCompletedProperty.ToTestDisplayString());
var semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees[0]);
var decl = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().AsSingleton();
var symbolV = (ILocalSymbol)semanticModel.GetDeclaredSymbol(decl);
Assert.Equal("System.Int32", symbolV.Type.ToTestDisplayString());
}
[Fact]
public void Dynamic()
{
string source =
@"using System.Threading.Tasks;
class Program
{
static async Task Main()
{
dynamic d = Task.CompletedTask;
await d;
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = (AwaitExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression).AsNode();
var info = model.GetAwaitExpressionInfo(expr);
Assert.True(info.IsDynamic);
Assert.Null(info.GetAwaiterMethod);
Assert.Null(info.IsCompletedProperty);
Assert.Null(info.GetResultMethod);
}
}
}
| // 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.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using System.Linq;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// Tests related to await expressions.
/// </summary>
public class AwaitExpressionTests : CompilingTestBase
{
[Fact]
public void TestAwaitInfoExtensionMethod()
{
var text =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
static class App{
public static async Task Main(){
var x = new MyAwaitable();
x.SetValue(42);
Console.WriteLine(await x + ""!"");
}
}
struct MyAwaitable
{
private ValueTask<int> task;
private TaskCompletionSource<int> source;
private TaskCompletionSource<int> Source
{
get
{
if (source == null)
{
source = new TaskCompletionSource<int>();
task = new ValueTask<int>(source.Task);
}
return source;
}
}
internal ValueTask<int> Task
{
get
{
_ = Source;
return task;
}
}
public void SetValue(int i)
{
Source.SetResult(i);
}
}
static class MyAwaitableExtension
{
public static System.Runtime.CompilerServices.ValueTaskAwaiter<int> GetAwaiter(this MyAwaitable a)
{
return a.Task.GetAwaiter();
}
}";
var csCompilation = CreateCompilation(text, targetFramework: TargetFramework.NetCoreAppAndCSharp);
var tree = csCompilation.SyntaxTrees.Single();
var model = csCompilation.GetSemanticModel(tree);
var awaitExpression = tree.GetRoot().DescendantNodes().OfType<AwaitExpressionSyntax>().First();
Assert.Equal("await x", awaitExpression.ToString());
var info = model.GetAwaitExpressionInfo(awaitExpression);
Assert.Equal(
"System.Runtime.CompilerServices.ValueTaskAwaiter<System.Int32> MyAwaitableExtension.GetAwaiter(this MyAwaitable a)",
info.GetAwaiterMethod.ToTestDisplayString()
);
Assert.Equal(
"System.Int32 System.Runtime.CompilerServices.ValueTaskAwaiter<System.Int32>.GetResult()",
info.GetResultMethod.ToTestDisplayString()
);
Assert.Equal(
"System.Boolean System.Runtime.CompilerServices.ValueTaskAwaiter<System.Int32>.IsCompleted { get; }",
info.IsCompletedProperty.ToTestDisplayString()
);
}
[Fact]
[WorkItem(711413, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/711413")]
public void TestAwaitInfo()
{
var text =
@"using System.Threading.Tasks;
class C
{
async void Goo(Task<int> t)
{
int c = 1 + await t;
}
}";
var info = GetAwaitExpressionInfo(text);
Assert.Equal("System.Runtime.CompilerServices.TaskAwaiter<System.Int32> System.Threading.Tasks.Task<System.Int32>.GetAwaiter()", info.GetAwaiterMethod.ToTestDisplayString());
Assert.Equal("System.Int32 System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.GetResult()", info.GetResultMethod.ToTestDisplayString());
Assert.Equal("System.Boolean System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.IsCompleted { get; }", info.IsCompletedProperty.ToTestDisplayString());
}
[Fact]
[WorkItem(1084696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084696")]
public void TestAwaitInfo2()
{
var text =
@"using System;
using System.Threading.Tasks;
public class C {
public C(Task<int> t) {
Func<Task> f = async() => await t;
}
}";
var info = GetAwaitExpressionInfo(text);
Assert.Equal("System.Runtime.CompilerServices.TaskAwaiter<System.Int32> System.Threading.Tasks.Task<System.Int32>.GetAwaiter()", info.GetAwaiterMethod.ToTestDisplayString());
Assert.Equal("System.Int32 System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.GetResult()", info.GetResultMethod.ToTestDisplayString());
Assert.Equal("System.Boolean System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.IsCompleted { get; }", info.IsCompletedProperty.ToTestDisplayString());
}
[Fact]
[WorkItem(744146, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/744146")]
public void DefaultAwaitExpressionInfo()
{
AwaitExpressionInfo info = default;
Assert.Null(info.GetAwaiterMethod);
Assert.Null(info.GetResultMethod);
Assert.Null(info.IsCompletedProperty);
Assert.False(info.IsDynamic);
Assert.Equal(0, info.GetHashCode());
}
private AwaitExpressionInfo GetAwaitExpressionInfo(string text, out CSharpCompilation compilation, params DiagnosticDescription[] diagnostics)
{
var tree = Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
var comp = CreateCompilationWithMscorlib45(new SyntaxTree[] { tree }, new MetadataReference[] { SystemRef });
comp.VerifyDiagnostics(diagnostics);
compilation = comp;
var syntaxNode = (AwaitExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression).AsNode();
var treeModel = comp.GetSemanticModel(tree);
return treeModel.GetAwaitExpressionInfo(syntaxNode);
}
private AwaitExpressionInfo GetAwaitExpressionInfo(string text, params DiagnosticDescription[] diagnostics)
{
CSharpCompilation temp;
return GetAwaitExpressionInfo(text, out temp, diagnostics);
}
[Fact]
[WorkItem(748533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/748533")]
public void Bug748533()
{
var text =
@"
using System;
using System.Threading;
using System.Threading.Tasks;
class A
{
public async Task<T> GetVal<T>(T t)
{
await Task.Delay(10);
return t;
}
public async void Run<T>(T t) where T : struct
{
int tests = 0;
tests++;
dynamic f = (await GetVal((Func<Task<int>>)(async () => 1)))();
if (await f == 1)
Driver.Count++;
tests++;
dynamic ff = new Func<Task<int>>((Func<Task<int>>)(async () => 1));
if (await ff() == 1)
Driver.Count++;
Driver.Result = Driver.Count - tests;
Driver.CompletedSignal.Set();
}
}
class Driver
{
public static int Result = -1;
public static int Count = 0;
public static AutoResetEvent CompletedSignal = new AutoResetEvent(false);
static int Main()
{
var t = new A();
t.Run(6);
CompletedSignal.WaitOne();
return Driver.Result;
}
}
";
var comp = CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (16,62): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// dynamic f = (await GetVal((Func<Task<int>>)(async () => 1)))();
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(16, 62),
// (20,69): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// dynamic ff = new Func<Task<int>>((Func<Task<int>>)(async () => 1));
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(20, 69),
// (17,13): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
// if (await f == 1)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await f").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create"));
}
[Fact]
[WorkItem(576316, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576316")]
public void Bug576316()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async Task Goo()
{
Console.WriteLine(new TypedReference().Equals(await Task.FromResult(0)));
}
}";
var comp = CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (8,27): error CS4007: 'await' cannot be used in an expression containing the type 'System.TypedReference'
// Console.WriteLine(new TypedReference().Equals(await Task.FromResult(0)));
Diagnostic(ErrorCode.ERR_ByRefTypeAndAwait, "await Task.FromResult(0)").WithArguments("System.TypedReference").WithLocation(8, 55));
}
[Fact]
[WorkItem(3951, "https://github.com/dotnet/roslyn/issues/3951")]
public void TestAwaitInNonAsync()
{
var text =
@"using System.Threading.Tasks;
class C
{
void Goo(Task<int> t)
{
var v = await t;
}
}";
CSharpCompilation compilation;
var info = GetAwaitExpressionInfo(text, out compilation,
// (7,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// int c = 1 + await t;
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await t").WithLocation(7, 17)
);
Assert.Equal("System.Runtime.CompilerServices.TaskAwaiter<System.Int32> System.Threading.Tasks.Task<System.Int32>.GetAwaiter()", info.GetAwaiterMethod.ToTestDisplayString());
Assert.Equal("System.Int32 System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.GetResult()", info.GetResultMethod.ToTestDisplayString());
Assert.Equal("System.Boolean System.Runtime.CompilerServices.TaskAwaiter<System.Int32>.IsCompleted { get; }", info.IsCompletedProperty.ToTestDisplayString());
var semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees[0]);
var decl = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().AsSingleton();
var symbolV = (ILocalSymbol)semanticModel.GetDeclaredSymbol(decl);
Assert.Equal("System.Int32", symbolV.Type.ToTestDisplayString());
}
[Fact]
public void Dynamic()
{
string source =
@"using System.Threading.Tasks;
class Program
{
static async Task Main()
{
dynamic d = Task.CompletedTask;
await d;
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = (AwaitExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression).AsNode();
var info = model.GetAwaitExpressionInfo(expr);
Assert.True(info.IsDynamic);
Assert.Null(info.GetAwaiterMethod);
Assert.Null(info.IsCompletedProperty);
Assert.Null(info.GetResultMethod);
}
[Fact]
[WorkItem(52639, "https://github.com/dotnet/roslyn/issues/52639")]
public void Issue52639_1()
{
var text =
@"
using System;
using System.Threading.Tasks;
class Test1
{
public async Task<ActionResult> Test(MyBaseClass model)
{
switch (model)
{
case FirstImplementation firstImplementation:
firstImplementation.MyString1 = await Task.FromResult(""test"");
break;
default:
throw new ArgumentOutOfRangeException(nameof(model));
}
switch (model)
{
case FirstImplementation firstImplementation:
await Task.FromResult(1);
return PartialView(""View"", firstImplementation);
default:
throw new ArgumentOutOfRangeException(nameof(model));
}
}
private ActionResult PartialView(string v, FirstImplementation firstImplementation)
{
return new ActionResult { F = firstImplementation };
}
static void Main()
{
var c = new Test1();
var f = new FirstImplementation();
if (c.Test(f).Result.F == f && f.MyString1 == ""test"")
{
System.Console.WriteLine(""Passed"");
}
else
{
System.Console.WriteLine(""Failed"");
}
}
}
internal class ActionResult
{
public FirstImplementation F;
}
public abstract class MyBaseClass
{
public string MyString { get; set; }
}
public class FirstImplementation : MyBaseClass
{
public string MyString1 { get; set; }
}
public class SecondImplementation : MyBaseClass
{
public string MyString2 { get; set; }
}
";
CompileAndVerify(text, options: TestOptions.ReleaseExe, expectedOutput: "Passed").VerifyDiagnostics();
CompileAndVerify(text, options: TestOptions.DebugExe, expectedOutput: "Passed").VerifyDiagnostics();
}
[Fact]
[WorkItem(52639, "https://github.com/dotnet/roslyn/issues/52639")]
public void Issue52639_2()
{
var text =
@"
using System.Threading.Tasks;
class C
{
string F;
async Task<C> Test(C c)
{
c.F = await Task.FromResult(""a"");
switch (c)
{
case C c1:
await Task.FromResult(1);
return c1;
}
return null;
}
static void Main()
{
var c = new C();
if (c.Test(c).Result == c && c.F == ""a"")
{
System.Console.WriteLine(""Passed"");
}
else
{
System.Console.WriteLine(""Failed"");
}
}
}
";
CompileAndVerify(text, options: TestOptions.ReleaseExe, expectedOutput: "Passed").VerifyDiagnostics();
CompileAndVerify(text, options: TestOptions.DebugExe, expectedOutput: "Passed").VerifyDiagnostics();
}
}
}
| 1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/Compilers/VisualBasic/Portable/CodeGen/EmitStatement.vb | ' 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.
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen
Partial Friend Class CodeGenerator
Private Sub EmitStatement(statement As BoundStatement)
Select Case statement.Kind
Case BoundKind.Block
EmitBlock(DirectCast(statement, BoundBlock))
Case BoundKind.SequencePoint
EmitSequencePointStatement(DirectCast(statement, BoundSequencePoint))
Case BoundKind.SequencePointWithSpan
EmitSequencePointStatement(DirectCast(statement, BoundSequencePointWithSpan))
Case BoundKind.ExpressionStatement
EmitExpression((DirectCast(statement, BoundExpressionStatement)).Expression, False)
Case BoundKind.NoOpStatement
EmitNoOpStatement(DirectCast(statement, BoundNoOpStatement))
Case BoundKind.StatementList
Dim list = DirectCast(statement, BoundStatementList)
Dim n As Integer = list.Statements.Length
For i = 0 To n - 1
EmitStatement(list.Statements(i))
Next
Case BoundKind.ReturnStatement
EmitReturnStatement(DirectCast(statement, BoundReturnStatement))
Case BoundKind.ThrowStatement
EmitThrowStatement(DirectCast(statement, BoundThrowStatement))
Case BoundKind.GotoStatement
EmitGotoStatement(DirectCast(statement, BoundGotoStatement))
Case BoundKind.LabelStatement
EmitLabelStatement(DirectCast(statement, BoundLabelStatement))
Case BoundKind.ConditionalGoto
EmitConditionalGoto(DirectCast(statement, BoundConditionalGoto))
Case BoundKind.TryStatement
EmitTryStatement(DirectCast(statement, BoundTryStatement))
Case BoundKind.SelectStatement
EmitSelectStatement(DirectCast(statement, BoundSelectStatement))
Case BoundKind.UnstructuredExceptionOnErrorSwitch
EmitUnstructuredExceptionOnErrorSwitch(DirectCast(statement, BoundUnstructuredExceptionOnErrorSwitch))
Case BoundKind.UnstructuredExceptionResumeSwitch
EmitUnstructuredExceptionResumeSwitch(DirectCast(statement, BoundUnstructuredExceptionResumeSwitch))
Case BoundKind.StateMachineScope
EmitStateMachineScope(DirectCast(statement, BoundStateMachineScope))
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind)
End Select
#If DEBUG Then
If Me._stackLocals Is Nothing OrElse Not Me._stackLocals.Any Then
_builder.AssertStackEmpty()
End If
#End If
End Sub
Private Function EmitStatementAndCountInstructions(statement As BoundStatement) As Integer
Dim n = _builder.InstructionsEmitted
EmitStatement(statement)
Return _builder.InstructionsEmitted - n
End Function
Private Sub EmitNoOpStatement(statement As BoundNoOpStatement)
Select Case statement.Flavor
Case NoOpStatementFlavor.Default
If _ilEmitStyle = ILEmitStyle.Debug Then
_builder.EmitOpCode(ILOpCode.Nop)
End If
Case NoOpStatementFlavor.AwaitYieldPoint
Debug.Assert((_asyncYieldPoints Is Nothing) = (_asyncResumePoints Is Nothing))
If _asyncYieldPoints Is Nothing Then
_asyncYieldPoints = ArrayBuilder(Of Integer).GetInstance
_asyncResumePoints = ArrayBuilder(Of Integer).GetInstance
End If
Debug.Assert(_asyncYieldPoints.Count = _asyncResumePoints.Count)
_asyncYieldPoints.Add(_builder.AllocateILMarker())
Case NoOpStatementFlavor.AwaitResumePoint
Debug.Assert(_asyncYieldPoints IsNot Nothing)
Debug.Assert(_asyncResumePoints IsNot Nothing)
Debug.Assert((_asyncYieldPoints.Count - 1) = _asyncResumePoints.Count)
_asyncResumePoints.Add(_builder.AllocateILMarker())
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Flavor)
End Select
End Sub
Private Sub EmitTryStatement(statement As BoundTryStatement, Optional emitCatchesOnly As Boolean = False)
Debug.Assert(Not statement.CatchBlocks.IsDefault)
' Stack must be empty at beginning of try block.
_builder.AssertStackEmpty()
' IL requires catches and finally block to be distinct try
' blocks so if the source contained both a catch and
' a finally, nested scopes are emitted.
Dim emitNestedScopes As Boolean = (Not emitCatchesOnly AndAlso (statement.CatchBlocks.Length > 0) AndAlso (statement.FinallyBlockOpt IsNot Nothing))
_builder.OpenLocalScope(ScopeType.TryCatchFinally)
_builder.OpenLocalScope(ScopeType.Try)
Me._tryNestingLevel += 1
If emitNestedScopes Then
EmitTryStatement(statement, emitCatchesOnly:=True)
Else
EmitBlock(statement.TryBlock)
End If
Debug.Assert(Me._tryNestingLevel > 0)
Me._tryNestingLevel -= 1
' close Try scope
_builder.CloseLocalScope()
If Not emitNestedScopes Then
For Each catchBlock In statement.CatchBlocks
EmitCatchBlock(catchBlock)
Next
End If
If Not emitCatchesOnly AndAlso (statement.FinallyBlockOpt IsNot Nothing) Then
_builder.OpenLocalScope(ScopeType.Finally)
EmitBlock(statement.FinallyBlockOpt)
_builder.CloseLocalScope()
End If
_builder.CloseLocalScope()
If Not emitCatchesOnly AndAlso statement.ExitLabelOpt IsNot Nothing Then
_builder.MarkLabel(statement.ExitLabelOpt)
End If
End Sub
'The interesting part in the following method is the support for exception filters.
'=== Example:
'
'Try
' <SomeCode>
'Catch ex as NullReferenceException When ex.Message isnot Nothing
' <Handler>
'End Try
'
'gets emitted as something like ===>
'
'Try
' <SomeCode>
'Filter
' Condition ' starts with exception on the stack
' Dim temp As NullReferenceException = TryCast(Pop, NullReferenceException)
' if temp is Nothing
' Push 0
' Else
' ex = temp
' Push if ((ex.Message isnot Nothing), 1, 0)
' End If
' End Condition ' leaves 1 or 0 on the stack
' Handler ' gets called after finalization of nested exception frames if condition above produced 1
' <Handler>
' End Handler
'End Try
Private Sub EmitCatchBlock(catchBlock As BoundCatchBlock)
Dim oldCatchBlock = _currentCatchBlock
_currentCatchBlock = catchBlock
Dim typeCheckFailedLabel As Object = Nothing
Dim exceptionSource = catchBlock.ExceptionSourceOpt
Dim exceptionType As Cci.ITypeReference
If exceptionSource IsNot Nothing Then
exceptionType = Me._module.Translate(exceptionSource.Type, exceptionSource.Syntax, _diagnostics)
Else
' if type is not specified it is assumed to be System.Exception
exceptionType = Me._module.Translate(Me._module.Compilation.GetWellKnownType(WellKnownType.System_Exception), catchBlock.Syntax, _diagnostics)
End If
' exception on stack
_builder.AdjustStack(1)
If catchBlock.ExceptionFilterOpt IsNot Nothing AndAlso catchBlock.ExceptionFilterOpt.Kind = BoundKind.UnstructuredExceptionHandlingCatchFilter Then
' This is a special catch created for Unstructured Exception Handling
Debug.Assert(catchBlock.LocalOpt Is Nothing)
Debug.Assert(exceptionSource Is Nothing)
'
' Generate the OnError filter.
'
' The On Error filter catches an exception when a handler is active and the method
' isn't currently in the process of handling an earlier error. We know the method
' is handling an earlier error when we have a valid Resume target.
'
' The filter expression is the equivalent of:
'
' Catch e When (TypeOf e Is Exception) And (ActiveHandler <> 0) And (ResumeTarget = 0)
'
Dim filter = DirectCast(catchBlock.ExceptionFilterOpt, BoundUnstructuredExceptionHandlingCatchFilter)
_builder.OpenLocalScope(ScopeType.Filter)
'Determine if the exception object is or inherits from System.Exception
_builder.EmitOpCode(ILOpCode.Isinst)
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics)
_builder.EmitOpCode(ILOpCode.Ldnull)
_builder.EmitOpCode(ILOpCode.Cgt_un)
' Calculate ActiveHandler <> 0
EmitLocalLoad(filter.ActiveHandlerLocal, used:=True)
_builder.EmitIntConstant(0)
_builder.EmitOpCode(ILOpCode.Cgt_un)
' AND the values together.
_builder.EmitOpCode(ILOpCode.And)
' Calculate ResumeTarget = 0
EmitLocalLoad(filter.ResumeTargetLocal, used:=True)
_builder.EmitIntConstant(0)
_builder.EmitOpCode(ILOpCode.Ceq)
' AND the values together.
_builder.EmitOpCode(ILOpCode.And)
' Now we are starting the actual handler
_builder.MarkFilterConditionEnd()
_builder.EmitOpCode(ILOpCode.Castclass)
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics)
If ShouldNoteProjectErrors() Then
EmitSetProjectError(catchBlock.Syntax, catchBlock.ErrorLineNumberOpt)
Else
_builder.EmitOpCode(ILOpCode.Pop)
End If
Else
' open appropriate exception handler scope. (Catch or Filter)
' if it is a Filter, emit prologue that checks if the type on the stack
' converts to what we want.
If catchBlock.ExceptionFilterOpt Is Nothing Then
_builder.OpenLocalScope(ScopeType.Catch, exceptionType)
If catchBlock.IsSynthesizedAsyncCatchAll Then
Debug.Assert(_asyncCatchHandlerOffset < 0)
_asyncCatchHandlerOffset = _builder.AllocateILMarker()
End If
Else
_builder.OpenLocalScope(ScopeType.Filter)
' Filtering starts with simulating regular Catch through an imperative type check
' If this is not our type, then we are done
Dim typeCheckPassedLabel As New Object
typeCheckFailedLabel = New Object
_builder.EmitOpCode(ILOpCode.Isinst)
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics)
_builder.EmitOpCode(ILOpCode.Dup)
_builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel)
_builder.EmitOpCode(ILOpCode.Pop)
_builder.EmitIntConstant(0)
_builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel)
_builder.MarkLabel(typeCheckPassedLabel)
End If
' define local if we have one
Dim localOpt = catchBlock.LocalOpt
If localOpt IsNot Nothing Then
' TODO: this local can be released when we can release named locals.
Dim declNodes = localOpt.DeclaringSyntaxReferences
DefineLocal(localOpt, If(Not declNodes.IsEmpty, DirectCast(declNodes(0).GetSyntax(), VisualBasicSyntaxNode), catchBlock.Syntax))
End If
' assign the exception variable if we have one
If exceptionSource IsNot Nothing Then
If ShouldNoteProjectErrors() Then
_builder.EmitOpCode(ILOpCode.Dup)
EmitSetProjectError(catchBlock.Syntax, catchBlock.ErrorLineNumberOpt)
End If
' here we have our exception on the stack in a form of a reference type (O)
' it means that we have to "unbox" it before storing to the local
' if exception's type is a generic type parameter.
If exceptionSource.Type.IsTypeParameter Then
_builder.EmitOpCode(ILOpCode.Unbox_any)
EmitSymbolToken(exceptionSource.Type, exceptionSource.Syntax)
End If
' TODO: parts of the following code is common with AssignmentExpression
' the only major difference is that assignee is on the stack
' consider factoring out common code.
While exceptionSource.Kind = BoundKind.Sequence
Dim seq = DirectCast(exceptionSource, BoundSequence)
EmitSideEffects(seq.SideEffects)
If seq.ValueOpt Is Nothing Then
Exit While
Else
exceptionSource = seq.ValueOpt
End If
End While
Select Case exceptionSource.Kind
Case BoundKind.Local
Debug.Assert(Not DirectCast(exceptionSource, BoundLocal).LocalSymbol.IsByRef)
_builder.EmitLocalStore(GetLocal(DirectCast(exceptionSource, BoundLocal)))
Case BoundKind.Parameter
Dim left = DirectCast(exceptionSource, BoundParameter)
' When assigning to a byref param
' we need to push param address below the exception
If left.ParameterSymbol.IsByRef Then
Dim temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax)
_builder.EmitLocalStore(temp)
_builder.EmitLoadArgumentOpcode(ParameterSlot(left))
_builder.EmitLocalLoad(temp)
FreeTemp(temp)
End If
EmitParameterStore(left)
Case BoundKind.FieldAccess
Dim left = DirectCast(exceptionSource, BoundFieldAccess)
If Not left.FieldSymbol.IsShared Then
Dim stateMachineField = TryCast(left.FieldSymbol, StateMachineFieldSymbol)
If (stateMachineField IsNot Nothing) AndAlso (stateMachineField.SlotIndex >= 0) Then
DefineUserDefinedStateMachineHoistedLocal(stateMachineField)
End If
' When assigning to a field
' we need to push param address below the exception
Dim temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax)
_builder.EmitLocalStore(temp)
Dim receiver = left.ReceiverOpt
' EmitFieldReceiver will handle receivers with type parameter type,
' but we do not know of a test case that will get here with receiver
' of type T. The assert is here to catch such a case. If the assert
' fails, remove the assert and add a corresponding test case.
Debug.Assert(receiver.Type.TypeKind <> TypeKind.TypeParameter)
Dim temp1 = EmitReceiverRef(receiver, isAccessConstrained:=False, addressKind:=AddressKind.[ReadOnly])
Debug.Assert(temp1 Is Nothing, "temp is unexpected when assigning to a field")
_builder.EmitLocalLoad(temp)
End If
EmitFieldStore(left)
Case Else
Throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind)
End Select
Else
If ShouldNoteProjectErrors() Then
EmitSetProjectError(catchBlock.Syntax, catchBlock.ErrorLineNumberOpt)
Else
_builder.EmitOpCode(ILOpCode.Pop)
End If
End If
' emit the actual filter expression, if we have one,
' and normalize results
If catchBlock.ExceptionFilterOpt IsNot Nothing Then
EmitCondExpr(catchBlock.ExceptionFilterOpt, True)
' Normalize the return value because values other than 0 or 1 produce unspecified results.
_builder.EmitIntConstant(0)
_builder.EmitOpCode(ILOpCode.Cgt_un)
_builder.MarkLabel(typeCheckFailedLabel)
' Now we are starting the actual handler
_builder.MarkFilterConditionEnd()
'pop the exception, it should have been already stored to the variable by the filter.
_builder.EmitOpCode(ILOpCode.Pop)
End If
End If
' emit actual handler body
' Note that it is a block so it will introduce its own scope for locals
' it should also have access to the exception local if we have declared one
' as that is scoped to the whole Catch/Filter
EmitBlock(catchBlock.Body)
' if the end of handler is reachable we should clear project errors.
' (if unreachable, this will not be emitted)
If ShouldNoteProjectErrors() AndAlso
(catchBlock.ExceptionFilterOpt Is Nothing OrElse catchBlock.ExceptionFilterOpt.Kind <> BoundKind.UnstructuredExceptionHandlingCatchFilter) Then
EmitClearProjectError(catchBlock.Syntax)
End If
_builder.CloseLocalScope()
_currentCatchBlock = oldCatchBlock
End Sub
''' <summary>
''' Tells if we should emit [Set/Clear]ProjectErrors when entering/leaving handlers
''' </summary>
Private Function ShouldNoteProjectErrors() As Boolean
Return Not Me._module.SourceModule.ContainingSourceAssembly.IsVbRuntime
End Function
Private Sub EmitSetProjectError(syntaxNode As SyntaxNode, errorLineNumberOpt As BoundExpression)
Dim setProjectErrorMethod As MethodSymbol
If errorLineNumberOpt Is Nothing Then
setProjectErrorMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError), MethodSymbol)
' consumes exception object from the stack
_builder.EmitOpCode(ILOpCode.Call, -1)
Else
setProjectErrorMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32), MethodSymbol)
EmitExpression(errorLineNumberOpt, used:=True)
' consumes exception object from the stack and the error line number
_builder.EmitOpCode(ILOpCode.Call, -2)
End If
Me.EmitSymbolToken(setProjectErrorMethod, syntaxNode)
End Sub
Private Sub EmitClearProjectError(syntaxNode As SyntaxNode)
Const clearProjectError As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError
Dim clearProjectErrorMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(clearProjectError), MethodSymbol)
' void static with no arguments
_builder.EmitOpCode(ILOpCode.Call, 0)
Me.EmitSymbolToken(clearProjectErrorMethod, syntaxNode)
End Sub
' specifies whether emitted conditional expression was a constant true/false or not a constant
Private Enum ConstResKind
ConstFalse
ConstTrue
NotAConst
End Enum
Private Sub EmitConditionalGoto(boundConditionalGoto As BoundConditionalGoto)
Dim label As Object = boundConditionalGoto.Label
Debug.Assert(label IsNot Nothing)
EmitCondBranch(boundConditionalGoto.Condition, label, boundConditionalGoto.JumpIfTrue)
End Sub
' 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed
'pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at
'the next instruction.
Private Function CanPassToBrfalse(ts As TypeSymbol) As Boolean
If ts.IsEnumType Then
' valid enums are all primitives
Return True
End If
Dim tc = ts.PrimitiveTypeCode
Select Case tc
Case Cci.PrimitiveTypeCode.Float32, Cci.PrimitiveTypeCode.Float64
Return False
Case Cci.PrimitiveTypeCode.NotPrimitive
' if this is a generic type param, verifier will want us to box
' EmitCondBranch knows that
Return ts.IsReferenceType
Case Else
Debug.Assert(tc <> Cci.PrimitiveTypeCode.Invalid)
Debug.Assert(tc <> Cci.PrimitiveTypeCode.Void)
Return True
End Select
End Function
Private Function TryReduce(condition As BoundBinaryOperator, ByRef sense As Boolean) As BoundExpression
Dim opKind = condition.OperatorKind And BinaryOperatorKind.OpMask
Debug.Assert(opKind = BinaryOperatorKind.Equals OrElse
opKind = BinaryOperatorKind.NotEquals OrElse
opKind = BinaryOperatorKind.Is OrElse
opKind = BinaryOperatorKind.IsNot)
Dim nonConstOp As BoundExpression
Dim constOp As ConstantValue = condition.Left.ConstantValueOpt
If constOp IsNot Nothing Then
nonConstOp = condition.Right
Else
constOp = condition.Right.ConstantValueOpt
If constOp Is Nothing Then
Return Nothing
End If
nonConstOp = condition.Left
End If
Dim nonConstType = nonConstOp.Type
Debug.Assert(nonConstType IsNot Nothing OrElse (nonConstOp.IsNothingLiteral() AndAlso (opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot)))
If nonConstType IsNot Nothing AndAlso Not CanPassToBrfalse(nonConstType) Then
Return Nothing
End If
Dim isBool As Boolean = nonConstType IsNot Nothing AndAlso nonConstType.PrimitiveTypeCode = Microsoft.Cci.PrimitiveTypeCode.Boolean
Dim isZero As Boolean = constOp.IsDefaultValue
If Not isBool AndAlso Not isZero Then
Return Nothing
End If
If isZero Then
sense = Not sense
End If
If opKind = BinaryOperatorKind.NotEquals OrElse opKind = BinaryOperatorKind.IsNot Then
sense = Not sense
End If
Return nonConstOp
End Function
Private Const s_IL_OP_CODE_ROW_LENGTH = 4
' // < <= > >=
' ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed
' ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert
' ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned
' ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert
' ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float
' ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert
Private Shared ReadOnly s_condJumpOpCodes As ILOpCode() = New ILOpCode() {
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge,
ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt,
ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un,
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un,
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge,
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un}
Private Function CodeForJump(expression As BoundBinaryOperator, sense As Boolean, <Out()> ByRef revOpCode As ILOpCode) As ILOpCode
Dim opIdx As Integer
Dim opKind = (expression.OperatorKind And BinaryOperatorKind.OpMask)
Dim operandType = expression.Left.Type
Debug.Assert(operandType IsNot Nothing OrElse (expression.Left.IsNothingLiteral() AndAlso (opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot)))
If operandType IsNot Nothing AndAlso operandType.IsBooleanType() Then
' Since VB True is -1 but is stored as 1 in IL, relational operations on Boolean must
' be reversed to yield the correct results. Note that = and <> do not need reversal.
Select Case opKind
Case BinaryOperatorKind.LessThan
opKind = BinaryOperatorKind.GreaterThan
Case BinaryOperatorKind.LessThanOrEqual
opKind = BinaryOperatorKind.GreaterThanOrEqual
Case BinaryOperatorKind.GreaterThan
opKind = BinaryOperatorKind.LessThan
Case BinaryOperatorKind.GreaterThanOrEqual
opKind = BinaryOperatorKind.LessThanOrEqual
End Select
End If
Select Case opKind
Case BinaryOperatorKind.IsNot
ValidateReferenceEqualityOperands(expression)
Return If(sense, ILOpCode.Bne_un, ILOpCode.Beq)
Case BinaryOperatorKind.Is
ValidateReferenceEqualityOperands(expression)
Return If(sense, ILOpCode.Beq, ILOpCode.Bne_un)
Case BinaryOperatorKind.Equals
Return If(sense, ILOpCode.Beq, ILOpCode.Bne_un)
Case BinaryOperatorKind.NotEquals
Return If(sense, ILOpCode.Bne_un, ILOpCode.Beq)
Case BinaryOperatorKind.LessThan
opIdx = 0
Case BinaryOperatorKind.LessThanOrEqual
opIdx = 1
Case BinaryOperatorKind.GreaterThan
opIdx = 2
Case BinaryOperatorKind.GreaterThanOrEqual
opIdx = 3
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
If operandType IsNot Nothing Then
If operandType.IsUnsignedIntegralType() Then
opIdx += 2 * s_IL_OP_CODE_ROW_LENGTH 'unsigned
Else
If operandType.IsFloatingType() Then
opIdx += 4 * s_IL_OP_CODE_ROW_LENGTH 'float
End If
End If
End If
Dim revOpIdx = opIdx
If Not sense Then
opIdx += s_IL_OP_CODE_ROW_LENGTH 'invert op
Else
revOpIdx += s_IL_OP_CODE_ROW_LENGTH 'invert orev
End If
revOpCode = s_condJumpOpCodes(revOpIdx)
Return s_condJumpOpCodes(opIdx)
End Function
' generate a jump to dest if (condition == sense) is true
' it is ok if lazyDest is Nothing
' if lazyDest is needed it will be initialized to a new object
Private Sub EmitCondBranch(condition As BoundExpression, ByRef lazyDest As Object, sense As Boolean)
_recursionDepth += 1
If _recursionDepth > 1 Then
StackGuard.EnsureSufficientExecutionStack(_recursionDepth)
EmitCondBranchCore(condition, lazyDest, sense)
Else
EmitCondBranchCoreWithStackGuard(condition, lazyDest, sense)
End If
_recursionDepth -= 1
End Sub
Private Sub EmitCondBranchCoreWithStackGuard(condition As BoundExpression, ByRef lazyDest As Object, sense As Boolean)
Debug.Assert(_recursionDepth = 1)
Try
EmitCondBranchCore(condition, lazyDest, sense)
Debug.Assert(_recursionDepth = 1)
Catch ex As InsufficientExecutionStackException
_diagnostics.Add(ERRID.ERR_TooLongOrComplexExpression,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition))
Throw New EmitCancelledException()
End Try
End Sub
Private Sub EmitCondBranchCore(condition As BoundExpression, ByRef lazyDest As Object, sense As Boolean)
oneMoreTime:
Dim ilcode As ILOpCode
Dim constExprValue = condition.ConstantValueOpt
If constExprValue IsNot Nothing Then
' make sure that only the bool bits are set or it is a Nothing literal
' or it is a string literal in which case it is equal to True
Debug.Assert(constExprValue.Discriminator = ConstantValueTypeDiscriminator.Boolean OrElse
constExprValue.Discriminator = ConstantValueTypeDiscriminator.String OrElse
constExprValue.IsNothing)
Dim taken As Boolean = constExprValue.IsDefaultValue <> sense
If taken Then
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ILOpCode.Br, lazyDest)
Else
' otherwise this branch will never be taken, so just fall through...
End If
Return
End If
Select Case condition.Kind
Case BoundKind.BinaryOperator
Dim binOp = DirectCast(condition, BoundBinaryOperator)
Dim testBothArgs As Boolean = sense
Select Case binOp.OperatorKind And BinaryOperatorKind.OpMask
Case BinaryOperatorKind.OrElse
testBothArgs = Not testBothArgs
GoTo BinaryOperatorKindLogicalAnd
Case BinaryOperatorKind.AndAlso
BinaryOperatorKindLogicalAnd:
If testBothArgs Then
' gotoif(a != sense) fallThrough
' gotoif(b == sense) dest
' fallThrough:
Dim lazyFallThrough = New Object
EmitCondBranch(binOp.Left, lazyFallThrough, Not sense)
EmitCondBranch(binOp.Right, lazyDest, sense)
If (lazyFallThrough IsNot Nothing) Then
_builder.MarkLabel(lazyFallThrough)
End If
Else
EmitCondBranch(binOp.Left, lazyDest, sense)
condition = binOp.Right
GoTo oneMoreTime
End If
Return
Case BinaryOperatorKind.IsNot,
BinaryOperatorKind.Is
ValidateReferenceEqualityOperands(binOp)
GoTo BinaryOperatorKindEqualsNotEquals
Case BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals
BinaryOperatorKindEqualsNotEquals:
Dim reduced = TryReduce(binOp, sense)
If reduced IsNot Nothing Then
condition = reduced
GoTo oneMoreTime
End If
GoTo BinaryOperatorKindLessThan
Case BinaryOperatorKind.LessThan,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.GreaterThanOrEqual
BinaryOperatorKindLessThan:
EmitExpression(binOp.Left, True)
EmitExpression(binOp.Right, True)
Dim revOpCode As ILOpCode
ilcode = CodeForJump(binOp, sense, revOpCode)
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ilcode, lazyDest, revOpCode)
Return
End Select
' none of above.
' then it is regular binary expression - Or, And, Xor ...
GoTo OtherExpressions
Case BoundKind.UnaryOperator
Dim unOp = DirectCast(condition, BoundUnaryOperator)
If (unOp.OperatorKind = UnaryOperatorKind.Not) Then
Debug.Assert(unOp.Type.IsBooleanType())
sense = Not sense
condition = unOp.Operand
GoTo oneMoreTime
Else
GoTo OtherExpressions
End If
Case BoundKind.TypeOf
Dim typeOfExpression = DirectCast(condition, BoundTypeOf)
EmitTypeOfExpression(typeOfExpression, used:=True, optimize:=True)
If typeOfExpression.IsTypeOfIsNotExpression Then
sense = Not sense
End If
ilcode = If(sense, ILOpCode.Brtrue, ILOpCode.Brfalse)
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ilcode, lazyDest)
Return
#If False Then
Case BoundKind.AsOperator
Dim asOp = DirectCast(condition, BoundIsOperator)
EmitExpression(asOp.Operand, True)
_builder.EmitOpCode(ILOpCode.Isinst)
EmitSymbolToken(asOp.TargetType.Type)
ilcode = If(sense, ILOpCode.Brtrue, ILOpCode.Brfalse)
_builder.EmitBranch(ilcode, dest)
Return
#End If
Case BoundKind.Sequence
Dim sequence = DirectCast(condition, BoundSequence)
EmitSequenceCondBranch(sequence, lazyDest, sense)
Return
Case Else
OtherExpressions:
EmitExpression(condition, True)
Dim conditionType = condition.Type
If Not conditionType.IsValueType AndAlso Not IsVerifierReference(conditionType) Then
EmitBox(conditionType, condition.Syntax)
End If
ilcode = If(sense, ILOpCode.Brtrue, ILOpCode.Brfalse)
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ilcode, lazyDest)
Return
End Select
End Sub
<Conditional("DEBUG")>
Private Sub ValidateReferenceEqualityOperands(binOp As BoundBinaryOperator)
Debug.Assert(binOp.Left.IsNothingLiteral() OrElse binOp.Left.Type.SpecialType = SpecialType.System_Object OrElse binOp.WasCompilerGenerated)
Debug.Assert(binOp.Right.IsNothingLiteral() OrElse binOp.Right.Type.SpecialType = SpecialType.System_Object OrElse binOp.WasCompilerGenerated)
End Sub
'TODO: is this to fold value? Same in C#?
Private Sub EmitSequenceCondBranch(sequence As BoundSequence, ByRef lazyDest As Object, sense As Boolean)
Dim hasLocals As Boolean = Not sequence.Locals.IsEmpty
If hasLocals Then
_builder.OpenLocalScope()
For Each local In sequence.Locals
Me.DefineLocal(local, sequence.Syntax)
Next
End If
Me.EmitSideEffects(sequence.SideEffects)
Debug.Assert(sequence.ValueOpt IsNot Nothing)
Me.EmitCondBranch(sequence.ValueOpt, lazyDest, sense)
If hasLocals Then
_builder.CloseLocalScope()
For Each local In sequence.Locals
Me.FreeLocal(local)
Next
End If
End Sub
Private Sub EmitLabelStatement(boundLabelStatement As BoundLabelStatement)
_builder.MarkLabel(boundLabelStatement.Label)
End Sub
Private Sub EmitGotoStatement(boundGotoStatement As BoundGotoStatement)
' if branch leaves current Catch block we need to emit ClearProjectError()
If ShouldNoteProjectErrors() Then
If _currentCatchBlock IsNot Nothing AndAlso
(_currentCatchBlock.ExceptionFilterOpt Is Nothing OrElse _currentCatchBlock.ExceptionFilterOpt.Kind <> BoundKind.UnstructuredExceptionHandlingCatchFilter) AndAlso
Not LabelFinder.NodeContainsLabel(_currentCatchBlock, boundGotoStatement.Label) Then
EmitClearProjectError(boundGotoStatement.Syntax)
End If
End If
_builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label)
End Sub
''' <summary>
''' tells if given node contains a label statement that defines given label symbol
''' </summary>
Private Class LabelFinder
Inherits StatementWalker
Private ReadOnly _label As LabelSymbol
Private _found As Boolean = False
Private Sub New(label As LabelSymbol)
Me._label = label
End Sub
Public Overrides Function Visit(node As BoundNode) As BoundNode
If Not _found AndAlso TypeOf node IsNot BoundExpression Then
Return MyBase.Visit(node)
End If
Return Nothing
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
If node.Label Is Me._label Then
_found = True
End If
Return MyBase.VisitLabelStatement(node)
End Function
Public Shared Function NodeContainsLabel(node As BoundNode, label As LabelSymbol) As Boolean
Dim finder = New LabelFinder(label)
finder.Visit(node)
Return finder._found
End Function
End Class
Private Sub EmitReturnStatement(boundReturnStatement As BoundReturnStatement)
Me.EmitExpression(boundReturnStatement.ExpressionOpt, True)
_builder.EmitRet(boundReturnStatement.ExpressionOpt Is Nothing)
End Sub
Private Sub EmitThrowStatement(boundThrowStatement As BoundThrowStatement)
Dim operand = boundThrowStatement.ExpressionOpt
If operand IsNot Nothing Then
EmitExpression(operand, used:=True)
Dim operandType = operand.Type
' "Throw Nothing" is not supported by the language
' so operand.Type should always be set.
Debug.Assert(operandType IsNot Nothing)
If (operandType IsNot Nothing) AndAlso (operandType.TypeKind = TypeKind.TypeParameter) Then
EmitBox(operandType, operand.Syntax)
End If
End If
_builder.EmitThrow(operand Is Nothing)
End Sub
Private Sub EmitSelectStatement(boundSelectStatement As BoundSelectStatement)
Debug.Assert(boundSelectStatement.RecommendSwitchTable)
Dim selectExpression = boundSelectStatement.ExpressionStatement.Expression
Dim caseBlocks = boundSelectStatement.CaseBlocks
Dim exitLabel = boundSelectStatement.ExitLabel
Dim fallThroughLabel = exitLabel
Debug.Assert(selectExpression.Type IsNot Nothing)
Debug.Assert(caseBlocks.Any())
' Create labels for case blocks
Dim caseBlockLabels As ImmutableArray(Of GeneratedLabelSymbol) = CreateCaseBlockLabels(caseBlocks)
' Create an array of key value pairs (key: case clause constant value, value: case block label)
' for emitting switch table based header.
' This function also ensures the correct fallThroughLabel is set, i.e. case else block label if one exists, otherwise exit label.
Dim caseLabelsForEmit As KeyValuePair(Of ConstantValue, Object)() = GetCaseLabelsForEmitSwitchHeader(caseBlocks, caseBlockLabels, fallThroughLabel)
' Emit switch table header
EmitSwitchTableHeader(selectExpression, caseLabelsForEmit, fallThroughLabel)
' Emit case blocks
EmitCaseBlocks(caseBlocks, caseBlockLabels, exitLabel)
' Emit exit label
_builder.MarkLabel(exitLabel)
End Sub
' Create a label for each case block
Private Function CreateCaseBlockLabels(caseBlocks As ImmutableArray(Of BoundCaseBlock)) As ImmutableArray(Of GeneratedLabelSymbol)
Debug.Assert(Not caseBlocks.IsEmpty)
Dim caseBlockLabels = ArrayBuilder(Of GeneratedLabelSymbol).GetInstance(caseBlocks.Length)
Dim cur As Integer = 0
For Each caseBlock In caseBlocks
cur = cur + 1
caseBlockLabels.Add(New GeneratedLabelSymbol("Case Block " + cur.ToString()))
Next
Return caseBlockLabels.ToImmutableAndFree()
End Function
' Creates an array of key value pairs (key: case clause constant value, value: case block label)
' for emitting switch table based header.
' This function also ensures the correct fallThroughLabel is set, i.e. case else block label if one exists, otherwise exit label.
Private Function GetCaseLabelsForEmitSwitchHeader(
caseBlocks As ImmutableArray(Of BoundCaseBlock),
caseBlockLabels As ImmutableArray(Of GeneratedLabelSymbol),
ByRef fallThroughLabel As LabelSymbol
) As KeyValuePair(Of ConstantValue, Object)()
Debug.Assert(Not caseBlocks.IsEmpty)
Debug.Assert(Not caseBlockLabels.IsEmpty)
Debug.Assert(caseBlocks.Length = caseBlockLabels.Length)
Dim labelsBuilder = ArrayBuilder(Of KeyValuePair(Of ConstantValue, Object)).GetInstance()
Dim constantsSet = New HashSet(Of ConstantValue)(New SwitchConstantValueHelper.SwitchLabelsComparer())
Dim cur As Integer = 0
For Each caseBlock In caseBlocks
Dim caseBlockLabel = caseBlockLabels(cur)
Dim caseClauses = caseBlock.CaseStatement.CaseClauses
If caseClauses.Any() Then
For Each caseClause In caseClauses
Dim constant As ConstantValue
Select Case caseClause.Kind
Case BoundKind.SimpleCaseClause
Dim simpleCaseClause = DirectCast(caseClause, BoundSimpleCaseClause)
Debug.Assert(simpleCaseClause.ValueOpt IsNot Nothing)
Debug.Assert(simpleCaseClause.ConditionOpt Is Nothing)
constant = simpleCaseClause.ValueOpt.ConstantValueOpt
Case BoundKind.RelationalCaseClause
Dim relationalCaseClause = DirectCast(caseClause, BoundRelationalCaseClause)
Debug.Assert(relationalCaseClause.OperatorKind = BinaryOperatorKind.Equals)
Debug.Assert(relationalCaseClause.ValueOpt IsNot Nothing)
Debug.Assert(relationalCaseClause.ConditionOpt Is Nothing)
constant = relationalCaseClause.ValueOpt.ConstantValueOpt
Case BoundKind.RangeCaseClause
' TODO: For now we use IF lists if we encounter
' TODO: BoundRangeCaseClause, we should not reach here.
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
End Select
Debug.Assert(constant IsNot Nothing)
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant))
' If we have duplicate case value constants, use the lexically first case constant.
If Not constantsSet.Contains(constant) Then
labelsBuilder.Add(New KeyValuePair(Of ConstantValue, Object)(constant, caseBlockLabel))
constantsSet.Add(constant)
End If
Next
Else
Debug.Assert(caseBlock.Syntax.Kind = SyntaxKind.CaseElseBlock)
' We have a case else block, update the fallThroughLabel to the corresponding caseBlockLabel
fallThroughLabel = caseBlockLabel
End If
cur = cur + 1
Next
Return labelsBuilder.ToArrayAndFree()
End Function
Private Sub EmitSwitchTableHeader(selectExpression As BoundExpression, caseLabels As KeyValuePair(Of ConstantValue, Object)(), fallThroughLabel As LabelSymbol)
Debug.Assert(selectExpression.Type IsNot Nothing)
Debug.Assert(caseLabels IsNot Nothing)
If Not caseLabels.Any() Then
' No case labels, emit branch to fallThroughLabel
_builder.EmitBranch(ILOpCode.Br, fallThroughLabel)
Else
Dim exprType = selectExpression.Type
Dim temp As LocalDefinition = Nothing
If exprType.SpecialType <> SpecialType.System_String Then
If selectExpression.Kind = BoundKind.Local AndAlso Not DirectCast(selectExpression, BoundLocal).LocalSymbol.IsByRef Then
_builder.EmitIntegerSwitchJumpTable(caseLabels, fallThroughLabel, GetLocal(DirectCast(selectExpression, BoundLocal)), keyTypeCode:=exprType.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode)
ElseIf selectExpression.Kind = BoundKind.Parameter AndAlso Not DirectCast(selectExpression, BoundParameter).ParameterSymbol.IsByRef Then
_builder.EmitIntegerSwitchJumpTable(caseLabels, fallThroughLabel, ParameterSlot(DirectCast(selectExpression, BoundParameter)), keyTypeCode:=exprType.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode)
Else
EmitExpression(selectExpression, True)
temp = AllocateTemp(exprType, selectExpression.Syntax)
_builder.EmitLocalStore(temp)
_builder.EmitIntegerSwitchJumpTable(caseLabels, fallThroughLabel, temp, keyTypeCode:=exprType.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode)
End If
Else
If selectExpression.Kind = BoundKind.Local AndAlso Not DirectCast(selectExpression, BoundLocal).LocalSymbol.IsByRef Then
EmitStringSwitchJumpTable(caseLabels, fallThroughLabel, GetLocal(DirectCast(selectExpression, BoundLocal)), selectExpression.Syntax)
Else
EmitExpression(selectExpression, True)
temp = AllocateTemp(exprType, selectExpression.Syntax)
_builder.EmitLocalStore(temp)
EmitStringSwitchJumpTable(caseLabels, fallThroughLabel, temp, selectExpression.Syntax)
End If
End If
If temp IsNot Nothing Then
FreeTemp(temp)
End If
End If
End Sub
Private Sub EmitStringSwitchJumpTable(caseLabels As KeyValuePair(Of ConstantValue, Object)(), fallThroughLabel As LabelSymbol, key As LocalDefinition, syntaxNode As SyntaxNode)
Dim genHashTableSwitch As Boolean = SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, caseLabels.Length)
Dim keyHash As LocalDefinition = Nothing
If genHashTableSwitch Then
Debug.Assert(_module.SupportsPrivateImplClass)
Dim privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics)
Dim stringHashMethodRef As Microsoft.Cci.IReference = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName)
Debug.Assert(stringHashMethodRef IsNot Nothing)
' static uint ComputeStringHash(string s)
' pop 1 (s)
' push 1 (uint return value)
' stackAdjustment = (pushCount - popCount) = 0
_builder.EmitLocalLoad(key)
_builder.EmitOpCode(ILOpCode.[Call], stackAdjustment:=0)
_builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics)
Dim UInt32Type = DirectCast(_module.GetSpecialType(SpecialType.System_UInt32, syntaxNode, _diagnostics).GetInternalSymbol(), TypeSymbol)
keyHash = AllocateTemp(UInt32Type, syntaxNode)
_builder.EmitLocalStore(keyHash)
End If
' Prefer embedded version of the member if present
Dim embeddedOperatorsType As NamedTypeSymbol = Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators)
Dim compareStringMember As WellKnownMember =
If(embeddedOperatorsType.IsErrorType AndAlso TypeOf embeddedOperatorsType Is MissingMetadataTypeSymbol,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean)
Dim stringCompareMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(compareStringMember), MethodSymbol)
Dim stringCompareMethodRef As Cci.IReference = Me._module.Translate(stringCompareMethod, needDeclaration:=False, syntaxNodeOpt:=syntaxNode, diagnostics:=_diagnostics)
Dim compareDelegate As SwitchStringJumpTableEmitter.EmitStringCompareAndBranch =
Sub(keyArg, stringConstant, targetLabel)
EmitStringCompareAndBranch(keyArg, syntaxNode, stringConstant, targetLabel, stringCompareMethodRef)
End Sub
_builder.EmitStringSwitchJumpTable(
caseLabels,
fallThroughLabel,
key,
keyHash,
compareDelegate,
AddressOf SynthesizedStringSwitchHashMethod.ComputeStringHash)
If keyHash IsNot Nothing Then
FreeTemp(keyHash)
End If
End Sub
''' <summary>
''' Delegate to emit string compare call and conditional branch based on the compare result.
''' </summary>
''' <param name="key">Key to compare</param>
''' <param name="syntaxNode">Node for diagnostics</param>
''' <param name="stringConstant">Case constant to compare the key against</param>
''' <param name="targetLabel">Target label to branch to if key = stringConstant</param>
''' <param name="stringCompareMethodRef">String equality method</param>
Private Sub EmitStringCompareAndBranch(key As LocalOrParameter, syntaxNode As SyntaxNode, stringConstant As ConstantValue, targetLabel As Object, stringCompareMethodRef As Microsoft.Cci.IReference)
' Emit compare and branch:
' If key = stringConstant Then
' Goto targetLabel
' End If
Debug.Assert(stringCompareMethodRef IsNot Nothing)
#If DEBUG Then
Dim assertDiagnostics = DiagnosticBag.GetInstance()
Debug.Assert(stringCompareMethodRef Is Me._module.Translate(DirectCast(
If(TypeOf Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators) Is MissingMetadataTypeSymbol,
Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean),
Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean)), MethodSymbol), needDeclaration:=False,
syntaxNodeOpt:=DirectCast(syntaxNode, VisualBasicSyntaxNode), diagnostics:=assertDiagnostics))
assertDiagnostics.Free()
#End If
' Public Shared Function CompareString(Left As String, Right As String, TextCompare As Boolean) As Integer
' pop 3 (Left, Right, TextCompare)
' push 1 (Integer return value)
' stackAdjustment = (pushCount - popCount) = -2
' NOTE: We generate string switch table only for Option Compare Binary, i.e. TextCompare = False
_builder.EmitLoad(key)
_builder.EmitConstantValue(stringConstant)
_builder.EmitConstantValue(ConstantValue.False)
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment:=-2)
_builder.EmitToken(stringCompareMethodRef, syntaxNode, _diagnostics)
' CompareString returns 0 if Left and Right strings are equal.
' Branch to targetLabel if CompareString returned 0.
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue)
End Sub
Private Sub EmitCaseBlocks(caseBlocks As ImmutableArray(Of BoundCaseBlock), caseBlockLabels As ImmutableArray(Of GeneratedLabelSymbol), exitLabel As LabelSymbol)
Debug.Assert(Not caseBlocks.IsEmpty)
Debug.Assert(Not caseBlockLabels.IsEmpty)
Debug.Assert(caseBlocks.Length = caseBlockLabels.Length)
Dim cur As Integer = 0
For Each caseBlock In caseBlocks
' Emit case block label
_builder.MarkLabel(caseBlockLabels(cur))
cur = cur + 1
' Emit case statement sequence point
Dim caseStatement = caseBlock.CaseStatement
If Not caseStatement.WasCompilerGenerated Then
Debug.Assert(caseStatement.Syntax IsNot Nothing)
If _emitPdbSequencePoints Then
EmitSequencePoint(caseStatement.Syntax)
End If
If _ilEmitStyle = ILEmitStyle.Debug Then
' Emit nop for the case statement otherwise the above sequence point
' will get associated with the first statement in subsequent case block.
' This matches the native compiler codegen.
_builder.EmitOpCode(ILOpCode.Nop)
End If
End If
' Emit case block body
EmitBlock(caseBlock.Body)
' Emit a branch to exit label
_builder.EmitBranch(ILOpCode.Br, exitLabel)
Next
End Sub
Private Sub EmitBlock(scope As BoundBlock)
Dim hasLocals As Boolean = Not scope.Locals.IsEmpty
If hasLocals Then
_builder.OpenLocalScope()
For Each local In scope.Locals
Dim declNodes = local.DeclaringSyntaxReferences
Me.DefineLocal(local, If(declNodes.IsEmpty, scope.Syntax, declNodes(0).GetVisualBasicSyntax()))
Next
End If
For Each statement In scope.Statements
EmitStatement(statement)
Next
If hasLocals Then
_builder.CloseLocalScope()
'TODO: can we free any locals here? Perhaps nameless temps?
End If
End Sub
Private Function DefineLocal(local As LocalSymbol, syntaxNode As SyntaxNode) As LocalDefinition
Dim dynamicTransformFlags = ImmutableArray(Of Boolean).Empty
Dim tupleElementNames = If(Not local.IsCompilerGenerated AndAlso local.Type.ContainsTupleNames(),
VisualBasicCompilation.TupleNamesEncoder.Encode(local.Type),
ImmutableArray(Of String).Empty)
' We're treating constants of type Decimal and DateTime as local here to not create a new instance for each time
' the value is accessed. This means there will be one local in the scope for this constant.
' This has the side effect that this constant will later on appear in the PDB file as a common local and one is able
' to modify the value in the debugger (which is a regression from Dev10).
' To fix this while keeping the behavior of having just one local for the const, one would need to preserve the
' information that this local is a ConstantButNotMetadataConstant (update ScopeManager.DeclareLocal & LocalDefinition)
' and modify PEWriter.Initialize to DefineLocalConstant instead of DefineLocalVariable if the local is
' ConstantButNotMetadataConstant.
' See bug #11047
If local.HasConstantValue Then
Dim compileTimeValue As MetadataConstant = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics)
Dim localConstantDef = New LocalConstantDefinition(
local.Name,
If(local.Locations.FirstOrDefault(), Location.None),
compileTimeValue,
dynamicTransformFlags:=dynamicTransformFlags,
tupleElementNames:=tupleElementNames)
' Reference in the scope for debugging purpose
_builder.AddLocalConstantToScope(localConstantDef)
Return Nothing
End If
If Me.IsStackLocal(local) Then
Return Nothing
End If
Dim translatedType = _module.Translate(local.Type, syntaxNodeOpt:=syntaxNode, diagnostics:=_diagnostics)
' Even though we don't need the token immediately, we will need it later when signature for the local is emitted.
' Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc).
_module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics)
Dim constraints = If(local.IsByRef, LocalSlotConstraints.ByRef, LocalSlotConstraints.None) Or
If(local.IsPinned, LocalSlotConstraints.Pinned, LocalSlotConstraints.None)
Dim localId As LocalDebugId = Nothing
Dim name As String = GetLocalDebugName(local, localId)
Dim synthesizedKind = local.SynthesizedKind
Dim localDef = _builder.LocalSlotManager.DeclareLocal(
type:=translatedType,
symbol:=local,
name:=name,
kind:=synthesizedKind,
id:=localId,
pdbAttributes:=synthesizedKind.PdbAttributes(),
constraints:=constraints,
dynamicTransformFlags:=dynamicTransformFlags,
tupleElementNames:=tupleElementNames,
isSlotReusable:=synthesizedKind.IsSlotReusable(_ilEmitStyle <> ILEmitStyle.Release))
' If named, add it to the local debug scope.
If localDef.Name IsNot Nothing Then
_builder.AddLocalToScope(localDef)
End If
Return localDef
End Function
''' <summary>
''' Gets the name And id of the local that are going to be generated into the debug metadata.
''' </summary>
Private Function GetLocalDebugName(local As LocalSymbol, <Out> ByRef localId As LocalDebugId) As String
localId = LocalDebugId.None
If local.IsImportedFromMetadata Then
Return local.Name
End If
' We include function value locals in async and iterator methods so that appropriate
' errors can be reported when users attempt to refer to them. However, there's no
' reason to actually emit them into the resulting MoveNext method, because they will
' never be accessed. Unfortunately, for implementation-specific reasons, dropping them
' would be non-trivial. Instead, we drop their names so that they do not appear while
' debugging (esp in the Locals window).
If local.DeclarationKind = LocalDeclarationKind.FunctionValue AndAlso
TypeOf _method Is SynthesizedStateMachineMethod Then
Return Nothing
End If
Dim localKind = local.SynthesizedKind
' only user-defined locals should be named during lowering:
Debug.Assert((local.Name Is Nothing) = (localKind <> SynthesizedLocalKind.UserDefined))
If Not localKind.IsLongLived() Then
Return Nothing
End If
If _ilEmitStyle = ILEmitStyle.Debug Then
Dim syntax = local.GetDeclaratorSyntax()
Dim syntaxOffset = _method.CalculateLocalSyntaxOffset(syntax.SpanStart, syntax.SyntaxTree)
Dim ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset)
' user-defined locals should have 0 ordinal
Debug.Assert(ordinal = 0 OrElse localKind <> SynthesizedLocalKind.UserDefined)
localId = New LocalDebugId(syntaxOffset, ordinal)
End If
If local.Name IsNot Nothing Then
Return local.Name
End If
Return GeneratedNames.MakeSynthesizedLocalName(localKind, _uniqueNameId)
End Function
Private Function IsSlotReusable(local As LocalSymbol) As Boolean
Return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle <> ILEmitStyle.Release)
End Function
Private Sub FreeLocal(local As LocalSymbol)
'TODO: releasing locals with name NYI.
'NOTE: VB considers named local's extent to be whole method
' so releasing them may just not be possible.
If local.Name Is Nothing AndAlso IsSlotReusable(local) AndAlso Not IsStackLocal(local) Then
_builder.LocalSlotManager.FreeLocal(local)
End If
End Sub
''' <summary>
''' Gets already declared and initialized local.
''' </summary>
Private Function GetLocal(localExpression As BoundLocal) As LocalDefinition
Dim symbol = localExpression.LocalSymbol
Return GetLocal(symbol)
End Function
Private Function GetLocal(symbol As LocalSymbol) As LocalDefinition
Return _builder.LocalSlotManager.GetLocal(symbol)
End Function
''' <summary>
''' Allocates a temp without identity.
''' </summary>
Private Function AllocateTemp(type As TypeSymbol, syntaxNode As SyntaxNode) As LocalDefinition
Return _builder.LocalSlotManager.AllocateSlot(
Me._module.Translate(type, syntaxNodeOpt:=syntaxNode, diagnostics:=_diagnostics),
LocalSlotConstraints.None)
End Function
''' <summary>
''' Frees a temp without identity.
''' </summary>
Private Sub FreeTemp(temp As LocalDefinition)
_builder.LocalSlotManager.FreeSlot(temp)
End Sub
''' <summary>
''' Frees an optional temp.
''' </summary>
Private Sub FreeOptTemp(temp As LocalDefinition)
If temp IsNot Nothing Then
FreeTemp(temp)
End If
End Sub
Private Sub EmitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch)
EmitExpression(node.Value, used:=True)
EmitSwitch(node.Jumps)
End Sub
Private Sub EmitSwitch(jumps As ImmutableArray(Of BoundGotoStatement))
Dim labels(jumps.Length - 1) As Object
For i As Integer = 0 To jumps.Length - 1
labels(i) = jumps(i).Label
Next
_builder.EmitSwitch(labels)
End Sub
Private Sub EmitStateMachineScope(scope As BoundStateMachineScope)
_builder.OpenLocalScope(ScopeType.StateMachineVariable)
For Each field In scope.Fields
DefineUserDefinedStateMachineHoistedLocal(DirectCast(field, StateMachineFieldSymbol))
Next
EmitStatement(scope.Statement)
_builder.CloseLocalScope()
End Sub
Private Sub DefineUserDefinedStateMachineHoistedLocal(field As StateMachineFieldSymbol)
Debug.Assert(field.SlotIndex >= 0)
If _module.debugInformationFormat = DebugInformationFormat.Pdb Then
'Native PDBs: VB EE uses name mangling to match up original locals and the fields where they are hoisted
'The scoping information is passed by recording PDB scopes of "fake" locals named the same
'as the fields. These locals are not emitted to IL.
' vb\language\debugger\procedurecontext.cpp
' 813 // Since state machines lift (almost) all locals of a method, the lifted fields should
' 814 // only be shown in the debugger when the original local variable was in scope. So
' 815 // we first check if there's a local by the given name and attempt to remove it from
' 816 // m_localVariableMap. If it was present, we decode the original local's name, otherwise
' 817 // we skip loading this lifted field since it is out of scope.
_builder.AddLocalToScope(New LocalDefinition(
symbolOpt:=Nothing,
nameOpt:=field.Name,
type:=Nothing,
slot:=field.SlotIndex,
synthesizedKind:=SynthesizedLocalKind.EmitterTemp,
id:=Nothing,
pdbAttributes:=LocalVariableAttributes.None,
constraints:=LocalSlotConstraints.None,
dynamicTransformFlags:=Nothing,
tupleElementNames:=Nothing))
Else
_builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex)
End If
End Sub
Private Sub EmitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch)
' Resume statements will branch here. Just load the resume local and
' branch to the switch table
EmitLabelStatement(node.ResumeLabel)
EmitExpression(node.ResumeTargetTemporary, used:=True)
Dim switchLabel As New Object()
_builder.EmitBranch(ILOpCode.Br_s, switchLabel)
_builder.AdjustStack(-1)
' Resume Next statements will branch here. Increment the resume local and
' fall through to the switch table
EmitLabelStatement(node.ResumeNextLabel)
EmitExpression(node.ResumeTargetTemporary, used:=True)
_builder.EmitIntConstant(1)
_builder.EmitOpCode(ILOpCode.Add)
' now start generating the resume switch table
_builder.MarkLabel(switchLabel)
' but first clear the resume local
_builder.EmitIntConstant(0)
_builder.EmitLocalStore(GetLocal(node.ResumeTargetTemporary))
EmitSwitch(node.Jumps)
End Sub
End Class
End Namespace
| ' 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.
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen
Partial Friend Class CodeGenerator
Private Sub EmitStatement(statement As BoundStatement)
Select Case statement.Kind
Case BoundKind.Block
EmitBlock(DirectCast(statement, BoundBlock))
Case BoundKind.SequencePoint
EmitSequencePointStatement(DirectCast(statement, BoundSequencePoint))
Case BoundKind.SequencePointWithSpan
EmitSequencePointStatement(DirectCast(statement, BoundSequencePointWithSpan))
Case BoundKind.ExpressionStatement
EmitExpression((DirectCast(statement, BoundExpressionStatement)).Expression, False)
Case BoundKind.NoOpStatement
EmitNoOpStatement(DirectCast(statement, BoundNoOpStatement))
Case BoundKind.StatementList
Dim list = DirectCast(statement, BoundStatementList)
Dim n As Integer = list.Statements.Length
For i = 0 To n - 1
EmitStatement(list.Statements(i))
Next
Case BoundKind.ReturnStatement
EmitReturnStatement(DirectCast(statement, BoundReturnStatement))
Case BoundKind.ThrowStatement
EmitThrowStatement(DirectCast(statement, BoundThrowStatement))
Case BoundKind.GotoStatement
EmitGotoStatement(DirectCast(statement, BoundGotoStatement))
Case BoundKind.LabelStatement
EmitLabelStatement(DirectCast(statement, BoundLabelStatement))
Case BoundKind.ConditionalGoto
EmitConditionalGoto(DirectCast(statement, BoundConditionalGoto))
Case BoundKind.TryStatement
EmitTryStatement(DirectCast(statement, BoundTryStatement))
Case BoundKind.SelectStatement
EmitSelectStatement(DirectCast(statement, BoundSelectStatement))
Case BoundKind.UnstructuredExceptionOnErrorSwitch
EmitUnstructuredExceptionOnErrorSwitch(DirectCast(statement, BoundUnstructuredExceptionOnErrorSwitch))
Case BoundKind.UnstructuredExceptionResumeSwitch
EmitUnstructuredExceptionResumeSwitch(DirectCast(statement, BoundUnstructuredExceptionResumeSwitch))
Case BoundKind.StateMachineScope
EmitStateMachineScope(DirectCast(statement, BoundStateMachineScope))
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind)
End Select
#If DEBUG Then
If Me._stackLocals Is Nothing OrElse Not Me._stackLocals.Any Then
_builder.AssertStackEmpty()
End If
#End If
End Sub
Private Function EmitStatementAndCountInstructions(statement As BoundStatement) As Integer
Dim n = _builder.InstructionsEmitted
EmitStatement(statement)
Return _builder.InstructionsEmitted - n
End Function
Private Sub EmitNoOpStatement(statement As BoundNoOpStatement)
Select Case statement.Flavor
Case NoOpStatementFlavor.Default
If _ilEmitStyle = ILEmitStyle.Debug Then
_builder.EmitOpCode(ILOpCode.Nop)
End If
Case NoOpStatementFlavor.AwaitYieldPoint
Debug.Assert((_asyncYieldPoints Is Nothing) = (_asyncResumePoints Is Nothing))
If _asyncYieldPoints Is Nothing Then
_asyncYieldPoints = ArrayBuilder(Of Integer).GetInstance
_asyncResumePoints = ArrayBuilder(Of Integer).GetInstance
End If
Debug.Assert(_asyncYieldPoints.Count = _asyncResumePoints.Count)
_asyncYieldPoints.Add(_builder.AllocateILMarker())
Case NoOpStatementFlavor.AwaitResumePoint
Debug.Assert(_asyncYieldPoints IsNot Nothing)
Debug.Assert(_asyncResumePoints IsNot Nothing)
Debug.Assert((_asyncYieldPoints.Count - 1) = _asyncResumePoints.Count)
_asyncResumePoints.Add(_builder.AllocateILMarker())
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Flavor)
End Select
End Sub
Private Sub EmitTryStatement(statement As BoundTryStatement, Optional emitCatchesOnly As Boolean = False)
Debug.Assert(Not statement.CatchBlocks.IsDefault)
' Stack must be empty at beginning of try block.
_builder.AssertStackEmpty()
' IL requires catches and finally block to be distinct try
' blocks so if the source contained both a catch and
' a finally, nested scopes are emitted.
Dim emitNestedScopes As Boolean = (Not emitCatchesOnly AndAlso (statement.CatchBlocks.Length > 0) AndAlso (statement.FinallyBlockOpt IsNot Nothing))
_builder.OpenLocalScope(ScopeType.TryCatchFinally)
_builder.OpenLocalScope(ScopeType.Try)
Me._tryNestingLevel += 1
If emitNestedScopes Then
EmitTryStatement(statement, emitCatchesOnly:=True)
Else
EmitBlock(statement.TryBlock)
End If
Debug.Assert(Me._tryNestingLevel > 0)
Me._tryNestingLevel -= 1
' close Try scope
_builder.CloseLocalScope()
If Not emitNestedScopes Then
For Each catchBlock In statement.CatchBlocks
EmitCatchBlock(catchBlock)
Next
End If
If Not emitCatchesOnly AndAlso (statement.FinallyBlockOpt IsNot Nothing) Then
_builder.OpenLocalScope(ScopeType.Finally)
EmitBlock(statement.FinallyBlockOpt)
_builder.CloseLocalScope()
End If
_builder.CloseLocalScope()
If Not emitCatchesOnly AndAlso statement.ExitLabelOpt IsNot Nothing Then
_builder.MarkLabel(statement.ExitLabelOpt)
End If
End Sub
'The interesting part in the following method is the support for exception filters.
'=== Example:
'
'Try
' <SomeCode>
'Catch ex as NullReferenceException When ex.Message isnot Nothing
' <Handler>
'End Try
'
'gets emitted as something like ===>
'
'Try
' <SomeCode>
'Filter
' Condition ' starts with exception on the stack
' Dim temp As NullReferenceException = TryCast(Pop, NullReferenceException)
' if temp is Nothing
' Push 0
' Else
' ex = temp
' Push if ((ex.Message isnot Nothing), 1, 0)
' End If
' End Condition ' leaves 1 or 0 on the stack
' Handler ' gets called after finalization of nested exception frames if condition above produced 1
' <Handler>
' End Handler
'End Try
Private Sub EmitCatchBlock(catchBlock As BoundCatchBlock)
Dim oldCatchBlock = _currentCatchBlock
_currentCatchBlock = catchBlock
Dim typeCheckFailedLabel As Object = Nothing
Dim exceptionSource = catchBlock.ExceptionSourceOpt
Dim exceptionType As Cci.ITypeReference
If exceptionSource IsNot Nothing Then
exceptionType = Me._module.Translate(exceptionSource.Type, exceptionSource.Syntax, _diagnostics)
Else
' if type is not specified it is assumed to be System.Exception
exceptionType = Me._module.Translate(Me._module.Compilation.GetWellKnownType(WellKnownType.System_Exception), catchBlock.Syntax, _diagnostics)
End If
' exception on stack
_builder.AdjustStack(1)
If catchBlock.ExceptionFilterOpt IsNot Nothing AndAlso catchBlock.ExceptionFilterOpt.Kind = BoundKind.UnstructuredExceptionHandlingCatchFilter Then
' This is a special catch created for Unstructured Exception Handling
Debug.Assert(catchBlock.LocalOpt Is Nothing)
Debug.Assert(exceptionSource Is Nothing)
'
' Generate the OnError filter.
'
' The On Error filter catches an exception when a handler is active and the method
' isn't currently in the process of handling an earlier error. We know the method
' is handling an earlier error when we have a valid Resume target.
'
' The filter expression is the equivalent of:
'
' Catch e When (TypeOf e Is Exception) And (ActiveHandler <> 0) And (ResumeTarget = 0)
'
Dim filter = DirectCast(catchBlock.ExceptionFilterOpt, BoundUnstructuredExceptionHandlingCatchFilter)
_builder.OpenLocalScope(ScopeType.Filter)
'Determine if the exception object is or inherits from System.Exception
_builder.EmitOpCode(ILOpCode.Isinst)
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics)
_builder.EmitOpCode(ILOpCode.Ldnull)
_builder.EmitOpCode(ILOpCode.Cgt_un)
' Calculate ActiveHandler <> 0
EmitLocalLoad(filter.ActiveHandlerLocal, used:=True)
_builder.EmitIntConstant(0)
_builder.EmitOpCode(ILOpCode.Cgt_un)
' AND the values together.
_builder.EmitOpCode(ILOpCode.And)
' Calculate ResumeTarget = 0
EmitLocalLoad(filter.ResumeTargetLocal, used:=True)
_builder.EmitIntConstant(0)
_builder.EmitOpCode(ILOpCode.Ceq)
' AND the values together.
_builder.EmitOpCode(ILOpCode.And)
' Now we are starting the actual handler
_builder.MarkFilterConditionEnd()
_builder.EmitOpCode(ILOpCode.Castclass)
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics)
If ShouldNoteProjectErrors() Then
EmitSetProjectError(catchBlock.Syntax, catchBlock.ErrorLineNumberOpt)
Else
_builder.EmitOpCode(ILOpCode.Pop)
End If
Else
' open appropriate exception handler scope. (Catch or Filter)
' if it is a Filter, emit prologue that checks if the type on the stack
' converts to what we want.
If catchBlock.ExceptionFilterOpt Is Nothing Then
_builder.OpenLocalScope(ScopeType.Catch, exceptionType)
If catchBlock.IsSynthesizedAsyncCatchAll Then
Debug.Assert(_asyncCatchHandlerOffset < 0)
_asyncCatchHandlerOffset = _builder.AllocateILMarker()
End If
Else
_builder.OpenLocalScope(ScopeType.Filter)
' Filtering starts with simulating regular Catch through an imperative type check
' If this is not our type, then we are done
Dim typeCheckPassedLabel As New Object
typeCheckFailedLabel = New Object
_builder.EmitOpCode(ILOpCode.Isinst)
_builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics)
_builder.EmitOpCode(ILOpCode.Dup)
_builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel)
_builder.EmitOpCode(ILOpCode.Pop)
_builder.EmitIntConstant(0)
_builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel)
_builder.MarkLabel(typeCheckPassedLabel)
End If
' define local if we have one
Dim localOpt = catchBlock.LocalOpt
If localOpt IsNot Nothing Then
' TODO: this local can be released when we can release named locals.
Dim declNodes = localOpt.DeclaringSyntaxReferences
DefineLocal(localOpt, If(Not declNodes.IsEmpty, DirectCast(declNodes(0).GetSyntax(), VisualBasicSyntaxNode), catchBlock.Syntax))
End If
' assign the exception variable if we have one
If exceptionSource IsNot Nothing Then
If ShouldNoteProjectErrors() Then
_builder.EmitOpCode(ILOpCode.Dup)
EmitSetProjectError(catchBlock.Syntax, catchBlock.ErrorLineNumberOpt)
End If
' here we have our exception on the stack in a form of a reference type (O)
' it means that we have to "unbox" it before storing to the local
' if exception's type is a generic type parameter.
If exceptionSource.Type.IsTypeParameter Then
_builder.EmitOpCode(ILOpCode.Unbox_any)
EmitSymbolToken(exceptionSource.Type, exceptionSource.Syntax)
End If
' TODO: parts of the following code is common with AssignmentExpression
' the only major difference is that assignee is on the stack
' consider factoring out common code.
While exceptionSource.Kind = BoundKind.Sequence
Dim seq = DirectCast(exceptionSource, BoundSequence)
EmitSideEffects(seq.SideEffects)
If seq.ValueOpt Is Nothing Then
Exit While
Else
exceptionSource = seq.ValueOpt
End If
End While
Select Case exceptionSource.Kind
Case BoundKind.Local
Debug.Assert(Not DirectCast(exceptionSource, BoundLocal).LocalSymbol.IsByRef)
_builder.EmitLocalStore(GetLocal(DirectCast(exceptionSource, BoundLocal)))
Case BoundKind.Parameter
Dim left = DirectCast(exceptionSource, BoundParameter)
' When assigning to a byref param
' we need to push param address below the exception
If left.ParameterSymbol.IsByRef Then
Dim temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax)
_builder.EmitLocalStore(temp)
_builder.EmitLoadArgumentOpcode(ParameterSlot(left))
_builder.EmitLocalLoad(temp)
FreeTemp(temp)
End If
EmitParameterStore(left)
Case BoundKind.FieldAccess
Dim left = DirectCast(exceptionSource, BoundFieldAccess)
If Not left.FieldSymbol.IsShared Then
Dim stateMachineField = TryCast(left.FieldSymbol, StateMachineFieldSymbol)
If (stateMachineField IsNot Nothing) AndAlso (stateMachineField.SlotIndex >= 0) Then
DefineUserDefinedStateMachineHoistedLocal(stateMachineField)
End If
' When assigning to a field
' we need to push param address below the exception
Dim temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax)
_builder.EmitLocalStore(temp)
Dim receiver = left.ReceiverOpt
' EmitFieldReceiver will handle receivers with type parameter type,
' but we do not know of a test case that will get here with receiver
' of type T. The assert is here to catch such a case. If the assert
' fails, remove the assert and add a corresponding test case.
Debug.Assert(receiver.Type.TypeKind <> TypeKind.TypeParameter)
Dim temp1 = EmitReceiverRef(receiver, isAccessConstrained:=False, addressKind:=AddressKind.[ReadOnly])
Debug.Assert(temp1 Is Nothing, "temp is unexpected when assigning to a field")
_builder.EmitLocalLoad(temp)
End If
EmitFieldStore(left)
Case Else
Throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind)
End Select
Else
If ShouldNoteProjectErrors() Then
EmitSetProjectError(catchBlock.Syntax, catchBlock.ErrorLineNumberOpt)
Else
_builder.EmitOpCode(ILOpCode.Pop)
End If
End If
' emit the actual filter expression, if we have one,
' and normalize results
If catchBlock.ExceptionFilterOpt IsNot Nothing Then
EmitCondExpr(catchBlock.ExceptionFilterOpt, True)
' Normalize the return value because values other than 0 or 1 produce unspecified results.
_builder.EmitIntConstant(0)
_builder.EmitOpCode(ILOpCode.Cgt_un)
_builder.MarkLabel(typeCheckFailedLabel)
' Now we are starting the actual handler
_builder.MarkFilterConditionEnd()
'pop the exception, it should have been already stored to the variable by the filter.
_builder.EmitOpCode(ILOpCode.Pop)
End If
End If
' emit actual handler body
' Note that it is a block so it will introduce its own scope for locals
' it should also have access to the exception local if we have declared one
' as that is scoped to the whole Catch/Filter
EmitBlock(catchBlock.Body)
' if the end of handler is reachable we should clear project errors.
' (if unreachable, this will not be emitted)
If ShouldNoteProjectErrors() AndAlso
(catchBlock.ExceptionFilterOpt Is Nothing OrElse catchBlock.ExceptionFilterOpt.Kind <> BoundKind.UnstructuredExceptionHandlingCatchFilter) Then
EmitClearProjectError(catchBlock.Syntax)
End If
_builder.CloseLocalScope()
_currentCatchBlock = oldCatchBlock
End Sub
''' <summary>
''' Tells if we should emit [Set/Clear]ProjectErrors when entering/leaving handlers
''' </summary>
Private Function ShouldNoteProjectErrors() As Boolean
Return Not Me._module.SourceModule.ContainingSourceAssembly.IsVbRuntime
End Function
Private Sub EmitSetProjectError(syntaxNode As SyntaxNode, errorLineNumberOpt As BoundExpression)
Dim setProjectErrorMethod As MethodSymbol
If errorLineNumberOpt Is Nothing Then
setProjectErrorMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError), MethodSymbol)
' consumes exception object from the stack
_builder.EmitOpCode(ILOpCode.Call, -1)
Else
setProjectErrorMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32), MethodSymbol)
EmitExpression(errorLineNumberOpt, used:=True)
' consumes exception object from the stack and the error line number
_builder.EmitOpCode(ILOpCode.Call, -2)
End If
Me.EmitSymbolToken(setProjectErrorMethod, syntaxNode)
End Sub
Private Sub EmitClearProjectError(syntaxNode As SyntaxNode)
Const clearProjectError As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError
Dim clearProjectErrorMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(clearProjectError), MethodSymbol)
' void static with no arguments
_builder.EmitOpCode(ILOpCode.Call, 0)
Me.EmitSymbolToken(clearProjectErrorMethod, syntaxNode)
End Sub
' specifies whether emitted conditional expression was a constant true/false or not a constant
Private Enum ConstResKind
ConstFalse
ConstTrue
NotAConst
End Enum
Private Sub EmitConditionalGoto(boundConditionalGoto As BoundConditionalGoto)
Dim label As Object = boundConditionalGoto.Label
Debug.Assert(label IsNot Nothing)
EmitCondBranch(boundConditionalGoto.Condition, label, boundConditionalGoto.JumpIfTrue)
End Sub
' 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed
'pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at
'the next instruction.
Private Function CanPassToBrfalse(ts As TypeSymbol) As Boolean
If ts.IsEnumType Then
' valid enums are all primitives
Return True
End If
Dim tc = ts.PrimitiveTypeCode
Select Case tc
Case Cci.PrimitiveTypeCode.Float32, Cci.PrimitiveTypeCode.Float64
Return False
Case Cci.PrimitiveTypeCode.NotPrimitive
' if this is a generic type param, verifier will want us to box
' EmitCondBranch knows that
Return ts.IsReferenceType
Case Else
Debug.Assert(tc <> Cci.PrimitiveTypeCode.Invalid)
Debug.Assert(tc <> Cci.PrimitiveTypeCode.Void)
Return True
End Select
End Function
Private Function TryReduce(condition As BoundBinaryOperator, ByRef sense As Boolean) As BoundExpression
Dim opKind = condition.OperatorKind And BinaryOperatorKind.OpMask
Debug.Assert(opKind = BinaryOperatorKind.Equals OrElse
opKind = BinaryOperatorKind.NotEquals OrElse
opKind = BinaryOperatorKind.Is OrElse
opKind = BinaryOperatorKind.IsNot)
Dim nonConstOp As BoundExpression
Dim constOp As ConstantValue = condition.Left.ConstantValueOpt
If constOp IsNot Nothing Then
nonConstOp = condition.Right
Else
constOp = condition.Right.ConstantValueOpt
If constOp Is Nothing Then
Return Nothing
End If
nonConstOp = condition.Left
End If
Dim nonConstType = nonConstOp.Type
Debug.Assert(nonConstType IsNot Nothing OrElse (nonConstOp.IsNothingLiteral() AndAlso (opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot)))
If nonConstType IsNot Nothing AndAlso Not CanPassToBrfalse(nonConstType) Then
Return Nothing
End If
Dim isBool As Boolean = nonConstType IsNot Nothing AndAlso nonConstType.PrimitiveTypeCode = Microsoft.Cci.PrimitiveTypeCode.Boolean
Dim isZero As Boolean = constOp.IsDefaultValue
If Not isBool AndAlso Not isZero Then
Return Nothing
End If
If isZero Then
sense = Not sense
End If
If opKind = BinaryOperatorKind.NotEquals OrElse opKind = BinaryOperatorKind.IsNot Then
sense = Not sense
End If
Return nonConstOp
End Function
Private Const s_IL_OP_CODE_ROW_LENGTH = 4
' // < <= > >=
' ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed
' ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert
' ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned
' ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert
' ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float
' ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert
Private Shared ReadOnly s_condJumpOpCodes As ILOpCode() = New ILOpCode() {
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge,
ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt,
ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un,
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un,
ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge,
ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un}
Private Function CodeForJump(expression As BoundBinaryOperator, sense As Boolean, <Out()> ByRef revOpCode As ILOpCode) As ILOpCode
Dim opIdx As Integer
Dim opKind = (expression.OperatorKind And BinaryOperatorKind.OpMask)
Dim operandType = expression.Left.Type
Debug.Assert(operandType IsNot Nothing OrElse (expression.Left.IsNothingLiteral() AndAlso (opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot)))
If operandType IsNot Nothing AndAlso operandType.IsBooleanType() Then
' Since VB True is -1 but is stored as 1 in IL, relational operations on Boolean must
' be reversed to yield the correct results. Note that = and <> do not need reversal.
Select Case opKind
Case BinaryOperatorKind.LessThan
opKind = BinaryOperatorKind.GreaterThan
Case BinaryOperatorKind.LessThanOrEqual
opKind = BinaryOperatorKind.GreaterThanOrEqual
Case BinaryOperatorKind.GreaterThan
opKind = BinaryOperatorKind.LessThan
Case BinaryOperatorKind.GreaterThanOrEqual
opKind = BinaryOperatorKind.LessThanOrEqual
End Select
End If
Select Case opKind
Case BinaryOperatorKind.IsNot
ValidateReferenceEqualityOperands(expression)
Return If(sense, ILOpCode.Bne_un, ILOpCode.Beq)
Case BinaryOperatorKind.Is
ValidateReferenceEqualityOperands(expression)
Return If(sense, ILOpCode.Beq, ILOpCode.Bne_un)
Case BinaryOperatorKind.Equals
Return If(sense, ILOpCode.Beq, ILOpCode.Bne_un)
Case BinaryOperatorKind.NotEquals
Return If(sense, ILOpCode.Bne_un, ILOpCode.Beq)
Case BinaryOperatorKind.LessThan
opIdx = 0
Case BinaryOperatorKind.LessThanOrEqual
opIdx = 1
Case BinaryOperatorKind.GreaterThan
opIdx = 2
Case BinaryOperatorKind.GreaterThanOrEqual
opIdx = 3
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
If operandType IsNot Nothing Then
If operandType.IsUnsignedIntegralType() Then
opIdx += 2 * s_IL_OP_CODE_ROW_LENGTH 'unsigned
Else
If operandType.IsFloatingType() Then
opIdx += 4 * s_IL_OP_CODE_ROW_LENGTH 'float
End If
End If
End If
Dim revOpIdx = opIdx
If Not sense Then
opIdx += s_IL_OP_CODE_ROW_LENGTH 'invert op
Else
revOpIdx += s_IL_OP_CODE_ROW_LENGTH 'invert orev
End If
revOpCode = s_condJumpOpCodes(revOpIdx)
Return s_condJumpOpCodes(opIdx)
End Function
' generate a jump to dest if (condition == sense) is true
' it is ok if lazyDest is Nothing
' if lazyDest is needed it will be initialized to a new object
Private Sub EmitCondBranch(condition As BoundExpression, ByRef lazyDest As Object, sense As Boolean)
_recursionDepth += 1
If _recursionDepth > 1 Then
StackGuard.EnsureSufficientExecutionStack(_recursionDepth)
EmitCondBranchCore(condition, lazyDest, sense)
Else
EmitCondBranchCoreWithStackGuard(condition, lazyDest, sense)
End If
_recursionDepth -= 1
End Sub
Private Sub EmitCondBranchCoreWithStackGuard(condition As BoundExpression, ByRef lazyDest As Object, sense As Boolean)
Debug.Assert(_recursionDepth = 1)
Try
EmitCondBranchCore(condition, lazyDest, sense)
Debug.Assert(_recursionDepth = 1)
Catch ex As InsufficientExecutionStackException
_diagnostics.Add(ERRID.ERR_TooLongOrComplexExpression,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition))
Throw New EmitCancelledException()
End Try
End Sub
Private Sub EmitCondBranchCore(condition As BoundExpression, ByRef lazyDest As Object, sense As Boolean)
oneMoreTime:
Dim ilcode As ILOpCode
Dim constExprValue = condition.ConstantValueOpt
If constExprValue IsNot Nothing Then
' make sure that only the bool bits are set or it is a Nothing literal
' or it is a string literal in which case it is equal to True
Debug.Assert(constExprValue.Discriminator = ConstantValueTypeDiscriminator.Boolean OrElse
constExprValue.Discriminator = ConstantValueTypeDiscriminator.String OrElse
constExprValue.IsNothing)
Dim taken As Boolean = constExprValue.IsDefaultValue <> sense
If taken Then
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ILOpCode.Br, lazyDest)
Else
' otherwise this branch will never be taken, so just fall through...
End If
Return
End If
Select Case condition.Kind
Case BoundKind.BinaryOperator
Dim binOp = DirectCast(condition, BoundBinaryOperator)
Dim testBothArgs As Boolean = sense
Select Case binOp.OperatorKind And BinaryOperatorKind.OpMask
Case BinaryOperatorKind.OrElse
testBothArgs = Not testBothArgs
GoTo BinaryOperatorKindLogicalAnd
Case BinaryOperatorKind.AndAlso
BinaryOperatorKindLogicalAnd:
If testBothArgs Then
' gotoif(a != sense) fallThrough
' gotoif(b == sense) dest
' fallThrough:
Dim lazyFallThrough = New Object
EmitCondBranch(binOp.Left, lazyFallThrough, Not sense)
EmitCondBranch(binOp.Right, lazyDest, sense)
If (lazyFallThrough IsNot Nothing) Then
_builder.MarkLabel(lazyFallThrough)
End If
Else
EmitCondBranch(binOp.Left, lazyDest, sense)
condition = binOp.Right
GoTo oneMoreTime
End If
Return
Case BinaryOperatorKind.IsNot,
BinaryOperatorKind.Is
ValidateReferenceEqualityOperands(binOp)
GoTo BinaryOperatorKindEqualsNotEquals
Case BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals
BinaryOperatorKindEqualsNotEquals:
Dim reduced = TryReduce(binOp, sense)
If reduced IsNot Nothing Then
condition = reduced
GoTo oneMoreTime
End If
GoTo BinaryOperatorKindLessThan
Case BinaryOperatorKind.LessThan,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.GreaterThanOrEqual
BinaryOperatorKindLessThan:
EmitExpression(binOp.Left, True)
EmitExpression(binOp.Right, True)
Dim revOpCode As ILOpCode
ilcode = CodeForJump(binOp, sense, revOpCode)
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ilcode, lazyDest, revOpCode)
Return
End Select
' none of above.
' then it is regular binary expression - Or, And, Xor ...
GoTo OtherExpressions
Case BoundKind.UnaryOperator
Dim unOp = DirectCast(condition, BoundUnaryOperator)
If (unOp.OperatorKind = UnaryOperatorKind.Not) Then
Debug.Assert(unOp.Type.IsBooleanType())
sense = Not sense
condition = unOp.Operand
GoTo oneMoreTime
Else
GoTo OtherExpressions
End If
Case BoundKind.TypeOf
Dim typeOfExpression = DirectCast(condition, BoundTypeOf)
EmitTypeOfExpression(typeOfExpression, used:=True, optimize:=True)
If typeOfExpression.IsTypeOfIsNotExpression Then
sense = Not sense
End If
ilcode = If(sense, ILOpCode.Brtrue, ILOpCode.Brfalse)
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ilcode, lazyDest)
Return
#If False Then
Case BoundKind.AsOperator
Dim asOp = DirectCast(condition, BoundIsOperator)
EmitExpression(asOp.Operand, True)
_builder.EmitOpCode(ILOpCode.Isinst)
EmitSymbolToken(asOp.TargetType.Type)
ilcode = If(sense, ILOpCode.Brtrue, ILOpCode.Brfalse)
_builder.EmitBranch(ilcode, dest)
Return
#End If
Case BoundKind.Sequence
Dim sequence = DirectCast(condition, BoundSequence)
EmitSequenceCondBranch(sequence, lazyDest, sense)
Return
Case Else
OtherExpressions:
EmitExpression(condition, True)
Dim conditionType = condition.Type
If Not conditionType.IsValueType AndAlso Not IsVerifierReference(conditionType) Then
EmitBox(conditionType, condition.Syntax)
End If
ilcode = If(sense, ILOpCode.Brtrue, ILOpCode.Brfalse)
lazyDest = If(lazyDest, New Object())
_builder.EmitBranch(ilcode, lazyDest)
Return
End Select
End Sub
<Conditional("DEBUG")>
Private Sub ValidateReferenceEqualityOperands(binOp As BoundBinaryOperator)
Debug.Assert(binOp.Left.IsNothingLiteral() OrElse binOp.Left.Type.SpecialType = SpecialType.System_Object OrElse binOp.WasCompilerGenerated)
Debug.Assert(binOp.Right.IsNothingLiteral() OrElse binOp.Right.Type.SpecialType = SpecialType.System_Object OrElse binOp.WasCompilerGenerated)
End Sub
'TODO: is this to fold value? Same in C#?
Private Sub EmitSequenceCondBranch(sequence As BoundSequence, ByRef lazyDest As Object, sense As Boolean)
Dim hasLocals As Boolean = Not sequence.Locals.IsEmpty
If hasLocals Then
_builder.OpenLocalScope()
For Each local In sequence.Locals
Me.DefineLocal(local, sequence.Syntax)
Next
End If
Me.EmitSideEffects(sequence.SideEffects)
Debug.Assert(sequence.ValueOpt IsNot Nothing)
Me.EmitCondBranch(sequence.ValueOpt, lazyDest, sense)
If hasLocals Then
_builder.CloseLocalScope()
For Each local In sequence.Locals
Me.FreeLocal(local)
Next
End If
End Sub
Private Sub EmitLabelStatement(boundLabelStatement As BoundLabelStatement)
_builder.MarkLabel(boundLabelStatement.Label)
End Sub
Private Sub EmitGotoStatement(boundGotoStatement As BoundGotoStatement)
' if branch leaves current Catch block we need to emit ClearProjectError()
If ShouldNoteProjectErrors() Then
If _currentCatchBlock IsNot Nothing AndAlso
(_currentCatchBlock.ExceptionFilterOpt Is Nothing OrElse _currentCatchBlock.ExceptionFilterOpt.Kind <> BoundKind.UnstructuredExceptionHandlingCatchFilter) AndAlso
Not LabelFinder.NodeContainsLabel(_currentCatchBlock, boundGotoStatement.Label) Then
EmitClearProjectError(boundGotoStatement.Syntax)
End If
End If
_builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label)
End Sub
''' <summary>
''' tells if given node contains a label statement that defines given label symbol
''' </summary>
Private Class LabelFinder
Inherits StatementWalker
Private ReadOnly _label As LabelSymbol
Private _found As Boolean = False
Private Sub New(label As LabelSymbol)
Me._label = label
End Sub
Public Overrides Function Visit(node As BoundNode) As BoundNode
If Not _found AndAlso TypeOf node IsNot BoundExpression Then
Return MyBase.Visit(node)
End If
Return Nothing
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
If node.Label Is Me._label Then
_found = True
End If
Return MyBase.VisitLabelStatement(node)
End Function
Public Shared Function NodeContainsLabel(node As BoundNode, label As LabelSymbol) As Boolean
Dim finder = New LabelFinder(label)
finder.Visit(node)
Return finder._found
End Function
End Class
Private Sub EmitReturnStatement(boundReturnStatement As BoundReturnStatement)
Me.EmitExpression(boundReturnStatement.ExpressionOpt, True)
_builder.EmitRet(boundReturnStatement.ExpressionOpt Is Nothing)
End Sub
Private Sub EmitThrowStatement(boundThrowStatement As BoundThrowStatement)
Dim operand = boundThrowStatement.ExpressionOpt
If operand IsNot Nothing Then
EmitExpression(operand, used:=True)
Dim operandType = operand.Type
' "Throw Nothing" is not supported by the language
' so operand.Type should always be set.
Debug.Assert(operandType IsNot Nothing)
If (operandType IsNot Nothing) AndAlso (operandType.TypeKind = TypeKind.TypeParameter) Then
EmitBox(operandType, operand.Syntax)
End If
End If
_builder.EmitThrow(operand Is Nothing)
End Sub
Private Sub EmitSelectStatement(boundSelectStatement As BoundSelectStatement)
Debug.Assert(boundSelectStatement.RecommendSwitchTable)
Dim selectExpression = boundSelectStatement.ExpressionStatement.Expression
Dim caseBlocks = boundSelectStatement.CaseBlocks
Dim exitLabel = boundSelectStatement.ExitLabel
Dim fallThroughLabel = exitLabel
Debug.Assert(selectExpression.Type IsNot Nothing)
Debug.Assert(caseBlocks.Any())
' Create labels for case blocks
Dim caseBlockLabels As ImmutableArray(Of GeneratedLabelSymbol) = CreateCaseBlockLabels(caseBlocks)
' Create an array of key value pairs (key: case clause constant value, value: case block label)
' for emitting switch table based header.
' This function also ensures the correct fallThroughLabel is set, i.e. case else block label if one exists, otherwise exit label.
Dim caseLabelsForEmit As KeyValuePair(Of ConstantValue, Object)() = GetCaseLabelsForEmitSwitchHeader(caseBlocks, caseBlockLabels, fallThroughLabel)
' Emit switch table header
EmitSwitchTableHeader(selectExpression, caseLabelsForEmit, fallThroughLabel)
' Emit case blocks
EmitCaseBlocks(caseBlocks, caseBlockLabels, exitLabel)
' Emit exit label
_builder.MarkLabel(exitLabel)
End Sub
' Create a label for each case block
Private Function CreateCaseBlockLabels(caseBlocks As ImmutableArray(Of BoundCaseBlock)) As ImmutableArray(Of GeneratedLabelSymbol)
Debug.Assert(Not caseBlocks.IsEmpty)
Dim caseBlockLabels = ArrayBuilder(Of GeneratedLabelSymbol).GetInstance(caseBlocks.Length)
Dim cur As Integer = 0
For Each caseBlock In caseBlocks
cur = cur + 1
caseBlockLabels.Add(New GeneratedLabelSymbol("Case Block " + cur.ToString()))
Next
Return caseBlockLabels.ToImmutableAndFree()
End Function
' Creates an array of key value pairs (key: case clause constant value, value: case block label)
' for emitting switch table based header.
' This function also ensures the correct fallThroughLabel is set, i.e. case else block label if one exists, otherwise exit label.
Private Function GetCaseLabelsForEmitSwitchHeader(
caseBlocks As ImmutableArray(Of BoundCaseBlock),
caseBlockLabels As ImmutableArray(Of GeneratedLabelSymbol),
ByRef fallThroughLabel As LabelSymbol
) As KeyValuePair(Of ConstantValue, Object)()
Debug.Assert(Not caseBlocks.IsEmpty)
Debug.Assert(Not caseBlockLabels.IsEmpty)
Debug.Assert(caseBlocks.Length = caseBlockLabels.Length)
Dim labelsBuilder = ArrayBuilder(Of KeyValuePair(Of ConstantValue, Object)).GetInstance()
Dim constantsSet = New HashSet(Of ConstantValue)(New SwitchConstantValueHelper.SwitchLabelsComparer())
Dim cur As Integer = 0
For Each caseBlock In caseBlocks
Dim caseBlockLabel = caseBlockLabels(cur)
Dim caseClauses = caseBlock.CaseStatement.CaseClauses
If caseClauses.Any() Then
For Each caseClause In caseClauses
Dim constant As ConstantValue
Select Case caseClause.Kind
Case BoundKind.SimpleCaseClause
Dim simpleCaseClause = DirectCast(caseClause, BoundSimpleCaseClause)
Debug.Assert(simpleCaseClause.ValueOpt IsNot Nothing)
Debug.Assert(simpleCaseClause.ConditionOpt Is Nothing)
constant = simpleCaseClause.ValueOpt.ConstantValueOpt
Case BoundKind.RelationalCaseClause
Dim relationalCaseClause = DirectCast(caseClause, BoundRelationalCaseClause)
Debug.Assert(relationalCaseClause.OperatorKind = BinaryOperatorKind.Equals)
Debug.Assert(relationalCaseClause.ValueOpt IsNot Nothing)
Debug.Assert(relationalCaseClause.ConditionOpt Is Nothing)
constant = relationalCaseClause.ValueOpt.ConstantValueOpt
Case BoundKind.RangeCaseClause
' TODO: For now we use IF lists if we encounter
' TODO: BoundRangeCaseClause, we should not reach here.
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
End Select
Debug.Assert(constant IsNot Nothing)
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant))
' If we have duplicate case value constants, use the lexically first case constant.
If Not constantsSet.Contains(constant) Then
labelsBuilder.Add(New KeyValuePair(Of ConstantValue, Object)(constant, caseBlockLabel))
constantsSet.Add(constant)
End If
Next
Else
Debug.Assert(caseBlock.Syntax.Kind = SyntaxKind.CaseElseBlock)
' We have a case else block, update the fallThroughLabel to the corresponding caseBlockLabel
fallThroughLabel = caseBlockLabel
End If
cur = cur + 1
Next
Return labelsBuilder.ToArrayAndFree()
End Function
Private Sub EmitSwitchTableHeader(selectExpression As BoundExpression, caseLabels As KeyValuePair(Of ConstantValue, Object)(), fallThroughLabel As LabelSymbol)
Debug.Assert(selectExpression.Type IsNot Nothing)
Debug.Assert(caseLabels IsNot Nothing)
If Not caseLabels.Any() Then
' No case labels, emit branch to fallThroughLabel
_builder.EmitBranch(ILOpCode.Br, fallThroughLabel)
Else
Dim exprType = selectExpression.Type
Dim temp As LocalDefinition = Nothing
If exprType.SpecialType <> SpecialType.System_String Then
If selectExpression.Kind = BoundKind.Local AndAlso Not DirectCast(selectExpression, BoundLocal).LocalSymbol.IsByRef Then
_builder.EmitIntegerSwitchJumpTable(caseLabels, fallThroughLabel, GetLocal(DirectCast(selectExpression, BoundLocal)), keyTypeCode:=exprType.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode)
ElseIf selectExpression.Kind = BoundKind.Parameter AndAlso Not DirectCast(selectExpression, BoundParameter).ParameterSymbol.IsByRef Then
_builder.EmitIntegerSwitchJumpTable(caseLabels, fallThroughLabel, ParameterSlot(DirectCast(selectExpression, BoundParameter)), keyTypeCode:=exprType.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode)
Else
EmitExpression(selectExpression, True)
temp = AllocateTemp(exprType, selectExpression.Syntax)
_builder.EmitLocalStore(temp)
_builder.EmitIntegerSwitchJumpTable(caseLabels, fallThroughLabel, temp, keyTypeCode:=exprType.GetEnumUnderlyingTypeOrSelf.PrimitiveTypeCode)
End If
Else
If selectExpression.Kind = BoundKind.Local AndAlso Not DirectCast(selectExpression, BoundLocal).LocalSymbol.IsByRef Then
EmitStringSwitchJumpTable(caseLabels, fallThroughLabel, GetLocal(DirectCast(selectExpression, BoundLocal)), selectExpression.Syntax)
Else
EmitExpression(selectExpression, True)
temp = AllocateTemp(exprType, selectExpression.Syntax)
_builder.EmitLocalStore(temp)
EmitStringSwitchJumpTable(caseLabels, fallThroughLabel, temp, selectExpression.Syntax)
End If
End If
If temp IsNot Nothing Then
FreeTemp(temp)
End If
End If
End Sub
Private Sub EmitStringSwitchJumpTable(caseLabels As KeyValuePair(Of ConstantValue, Object)(), fallThroughLabel As LabelSymbol, key As LocalDefinition, syntaxNode As SyntaxNode)
Dim genHashTableSwitch As Boolean = SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, caseLabels.Length)
Dim keyHash As LocalDefinition = Nothing
If genHashTableSwitch Then
Debug.Assert(_module.SupportsPrivateImplClass)
Dim privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics)
Dim stringHashMethodRef As Microsoft.Cci.IReference = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName)
Debug.Assert(stringHashMethodRef IsNot Nothing)
' static uint ComputeStringHash(string s)
' pop 1 (s)
' push 1 (uint return value)
' stackAdjustment = (pushCount - popCount) = 0
_builder.EmitLocalLoad(key)
_builder.EmitOpCode(ILOpCode.[Call], stackAdjustment:=0)
_builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics)
Dim UInt32Type = DirectCast(_module.GetSpecialType(SpecialType.System_UInt32, syntaxNode, _diagnostics).GetInternalSymbol(), TypeSymbol)
keyHash = AllocateTemp(UInt32Type, syntaxNode)
_builder.EmitLocalStore(keyHash)
End If
' Prefer embedded version of the member if present
Dim embeddedOperatorsType As NamedTypeSymbol = Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators)
Dim compareStringMember As WellKnownMember =
If(embeddedOperatorsType.IsErrorType AndAlso TypeOf embeddedOperatorsType Is MissingMetadataTypeSymbol,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean)
Dim stringCompareMethod = DirectCast(Me._module.Compilation.GetWellKnownTypeMember(compareStringMember), MethodSymbol)
Dim stringCompareMethodRef As Cci.IReference = Me._module.Translate(stringCompareMethod, needDeclaration:=False, syntaxNodeOpt:=syntaxNode, diagnostics:=_diagnostics)
Dim compareDelegate As SwitchStringJumpTableEmitter.EmitStringCompareAndBranch =
Sub(keyArg, stringConstant, targetLabel)
EmitStringCompareAndBranch(keyArg, syntaxNode, stringConstant, targetLabel, stringCompareMethodRef)
End Sub
_builder.EmitStringSwitchJumpTable(
caseLabels,
fallThroughLabel,
key,
keyHash,
compareDelegate,
AddressOf SynthesizedStringSwitchHashMethod.ComputeStringHash)
If keyHash IsNot Nothing Then
FreeTemp(keyHash)
End If
End Sub
''' <summary>
''' Delegate to emit string compare call and conditional branch based on the compare result.
''' </summary>
''' <param name="key">Key to compare</param>
''' <param name="syntaxNode">Node for diagnostics</param>
''' <param name="stringConstant">Case constant to compare the key against</param>
''' <param name="targetLabel">Target label to branch to if key = stringConstant</param>
''' <param name="stringCompareMethodRef">String equality method</param>
Private Sub EmitStringCompareAndBranch(key As LocalOrParameter, syntaxNode As SyntaxNode, stringConstant As ConstantValue, targetLabel As Object, stringCompareMethodRef As Microsoft.Cci.IReference)
' Emit compare and branch:
' If key = stringConstant Then
' Goto targetLabel
' End If
Debug.Assert(stringCompareMethodRef IsNot Nothing)
#If DEBUG Then
Dim assertDiagnostics = DiagnosticBag.GetInstance()
Debug.Assert(stringCompareMethodRef Is Me._module.Translate(DirectCast(
If(TypeOf Me._module.Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators) Is MissingMetadataTypeSymbol,
Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean),
Me._module.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean)), MethodSymbol), needDeclaration:=False,
syntaxNodeOpt:=DirectCast(syntaxNode, VisualBasicSyntaxNode), diagnostics:=assertDiagnostics))
assertDiagnostics.Free()
#End If
' Public Shared Function CompareString(Left As String, Right As String, TextCompare As Boolean) As Integer
' pop 3 (Left, Right, TextCompare)
' push 1 (Integer return value)
' stackAdjustment = (pushCount - popCount) = -2
' NOTE: We generate string switch table only for Option Compare Binary, i.e. TextCompare = False
_builder.EmitLoad(key)
_builder.EmitConstantValue(stringConstant)
_builder.EmitConstantValue(ConstantValue.False)
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment:=-2)
_builder.EmitToken(stringCompareMethodRef, syntaxNode, _diagnostics)
' CompareString returns 0 if Left and Right strings are equal.
' Branch to targetLabel if CompareString returned 0.
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue)
End Sub
Private Sub EmitCaseBlocks(caseBlocks As ImmutableArray(Of BoundCaseBlock), caseBlockLabels As ImmutableArray(Of GeneratedLabelSymbol), exitLabel As LabelSymbol)
Debug.Assert(Not caseBlocks.IsEmpty)
Debug.Assert(Not caseBlockLabels.IsEmpty)
Debug.Assert(caseBlocks.Length = caseBlockLabels.Length)
Dim cur As Integer = 0
For Each caseBlock In caseBlocks
' Emit case block label
_builder.MarkLabel(caseBlockLabels(cur))
cur = cur + 1
' Emit case statement sequence point
Dim caseStatement = caseBlock.CaseStatement
If Not caseStatement.WasCompilerGenerated Then
Debug.Assert(caseStatement.Syntax IsNot Nothing)
If _emitPdbSequencePoints Then
EmitSequencePoint(caseStatement.Syntax)
End If
If _ilEmitStyle = ILEmitStyle.Debug Then
' Emit nop for the case statement otherwise the above sequence point
' will get associated with the first statement in subsequent case block.
' This matches the native compiler codegen.
_builder.EmitOpCode(ILOpCode.Nop)
End If
End If
' Emit case block body
EmitBlock(caseBlock.Body)
' Emit a branch to exit label
_builder.EmitBranch(ILOpCode.Br, exitLabel)
Next
End Sub
Private Sub EmitBlock(scope As BoundBlock)
Dim hasLocals As Boolean = Not scope.Locals.IsEmpty
If hasLocals Then
_builder.OpenLocalScope()
For Each local In scope.Locals
Dim declNodes = local.DeclaringSyntaxReferences
Me.DefineLocal(local, If(declNodes.IsEmpty, scope.Syntax, declNodes(0).GetVisualBasicSyntax()))
Next
End If
For Each statement In scope.Statements
EmitStatement(statement)
Next
If hasLocals Then
_builder.CloseLocalScope()
'TODO: can we free any locals here? Perhaps nameless temps?
End If
End Sub
Private Function DefineLocal(local As LocalSymbol, syntaxNode As SyntaxNode) As LocalDefinition
Dim dynamicTransformFlags = ImmutableArray(Of Boolean).Empty
Dim tupleElementNames = If(Not local.IsCompilerGenerated AndAlso local.Type.ContainsTupleNames(),
VisualBasicCompilation.TupleNamesEncoder.Encode(local.Type),
ImmutableArray(Of String).Empty)
' We're treating constants of type Decimal and DateTime as local here to not create a new instance for each time
' the value is accessed. This means there will be one local in the scope for this constant.
' This has the side effect that this constant will later on appear in the PDB file as a common local and one is able
' to modify the value in the debugger (which is a regression from Dev10).
' To fix this while keeping the behavior of having just one local for the const, one would need to preserve the
' information that this local is a ConstantButNotMetadataConstant (update ScopeManager.DeclareLocal & LocalDefinition)
' and modify PEWriter.Initialize to DefineLocalConstant instead of DefineLocalVariable if the local is
' ConstantButNotMetadataConstant.
' See bug #11047
If local.HasConstantValue Then
Dim compileTimeValue As MetadataConstant = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics)
Dim localConstantDef = New LocalConstantDefinition(
local.Name,
If(local.Locations.FirstOrDefault(), Location.None),
compileTimeValue,
dynamicTransformFlags:=dynamicTransformFlags,
tupleElementNames:=tupleElementNames)
' Reference in the scope for debugging purpose
_builder.AddLocalConstantToScope(localConstantDef)
Return Nothing
End If
If Me.IsStackLocal(local) Then
Return Nothing
End If
Dim translatedType = _module.Translate(local.Type, syntaxNodeOpt:=syntaxNode, diagnostics:=_diagnostics)
' Even though we don't need the token immediately, we will need it later when signature for the local is emitted.
' Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc).
_module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics)
Dim constraints = If(local.IsByRef, LocalSlotConstraints.ByRef, LocalSlotConstraints.None) Or
If(local.IsPinned, LocalSlotConstraints.Pinned, LocalSlotConstraints.None)
Dim localId As LocalDebugId = Nothing
Dim name As String = GetLocalDebugName(local, localId)
Dim synthesizedKind = local.SynthesizedKind
Dim localDef = _builder.LocalSlotManager.DeclareLocal(
type:=translatedType,
symbol:=local,
name:=name,
kind:=synthesizedKind,
id:=localId,
pdbAttributes:=synthesizedKind.PdbAttributes(),
constraints:=constraints,
dynamicTransformFlags:=dynamicTransformFlags,
tupleElementNames:=tupleElementNames,
isSlotReusable:=synthesizedKind.IsSlotReusable(_ilEmitStyle <> ILEmitStyle.Release))
' If named, add it to the local debug scope.
If localDef.Name IsNot Nothing Then
_builder.AddLocalToScope(localDef)
End If
Return localDef
End Function
''' <summary>
''' Gets the name And id of the local that are going to be generated into the debug metadata.
''' </summary>
Private Function GetLocalDebugName(local As LocalSymbol, <Out> ByRef localId As LocalDebugId) As String
localId = LocalDebugId.None
If local.IsImportedFromMetadata Then
Return local.Name
End If
' We include function value locals in async and iterator methods so that appropriate
' errors can be reported when users attempt to refer to them. However, there's no
' reason to actually emit them into the resulting MoveNext method, because they will
' never be accessed. Unfortunately, for implementation-specific reasons, dropping them
' would be non-trivial. Instead, we drop their names so that they do not appear while
' debugging (esp in the Locals window).
If local.DeclarationKind = LocalDeclarationKind.FunctionValue AndAlso
TypeOf _method Is SynthesizedStateMachineMethod Then
Return Nothing
End If
Dim localKind = local.SynthesizedKind
' only user-defined locals should be named during lowering:
Debug.Assert((local.Name Is Nothing) = (localKind <> SynthesizedLocalKind.UserDefined))
If Not localKind.IsLongLived() Then
Return Nothing
End If
If _ilEmitStyle = ILEmitStyle.Debug Then
Dim syntax = local.GetDeclaratorSyntax()
Dim syntaxOffset = _method.CalculateLocalSyntaxOffset(syntax.SpanStart, syntax.SyntaxTree)
Dim ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset)
' user-defined locals should have 0 ordinal
Debug.Assert(ordinal = 0 OrElse localKind <> SynthesizedLocalKind.UserDefined)
localId = New LocalDebugId(syntaxOffset, ordinal)
End If
If local.Name IsNot Nothing Then
Return local.Name
End If
Return GeneratedNames.MakeSynthesizedLocalName(localKind, _uniqueNameId)
End Function
Private Function IsSlotReusable(local As LocalSymbol) As Boolean
Return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle <> ILEmitStyle.Release)
End Function
Private Sub FreeLocal(local As LocalSymbol)
'TODO: releasing locals with name NYI.
'NOTE: VB considers named local's extent to be whole method
' so releasing them may just not be possible.
If local.Name Is Nothing AndAlso IsSlotReusable(local) AndAlso Not IsStackLocal(local) Then
_builder.LocalSlotManager.FreeLocal(local)
End If
End Sub
''' <summary>
''' Gets already declared and initialized local.
''' </summary>
Private Function GetLocal(localExpression As BoundLocal) As LocalDefinition
Dim symbol = localExpression.LocalSymbol
Return GetLocal(symbol)
End Function
Private Function GetLocal(symbol As LocalSymbol) As LocalDefinition
Return _builder.LocalSlotManager.GetLocal(symbol)
End Function
''' <summary>
''' Allocates a temp without identity.
''' </summary>
Private Function AllocateTemp(type As TypeSymbol, syntaxNode As SyntaxNode) As LocalDefinition
Return _builder.LocalSlotManager.AllocateSlot(
Me._module.Translate(type, syntaxNodeOpt:=syntaxNode, diagnostics:=_diagnostics),
LocalSlotConstraints.None)
End Function
''' <summary>
''' Frees a temp without identity.
''' </summary>
Private Sub FreeTemp(temp As LocalDefinition)
_builder.LocalSlotManager.FreeSlot(temp)
End Sub
''' <summary>
''' Frees an optional temp.
''' </summary>
Private Sub FreeOptTemp(temp As LocalDefinition)
If temp IsNot Nothing Then
FreeTemp(temp)
End If
End Sub
Private Sub EmitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch)
EmitExpression(node.Value, used:=True)
EmitSwitch(node.Jumps)
End Sub
Private Sub EmitSwitch(jumps As ImmutableArray(Of BoundGotoStatement))
Dim labels(jumps.Length - 1) As Object
For i As Integer = 0 To jumps.Length - 1
labels(i) = jumps(i).Label
Next
_builder.EmitSwitch(labels)
End Sub
Private Sub EmitStateMachineScope(scope As BoundStateMachineScope)
_builder.OpenLocalScope(ScopeType.StateMachineVariable)
For Each field In scope.Fields
Dim stateMachineField = DirectCast(field, StateMachineFieldSymbol)
If stateMachineField.SlotIndex >= 0 Then
DefineUserDefinedStateMachineHoistedLocal(stateMachineField)
End If
Next
EmitStatement(scope.Statement)
_builder.CloseLocalScope()
End Sub
Private Sub DefineUserDefinedStateMachineHoistedLocal(field As StateMachineFieldSymbol)
Debug.Assert(field.SlotIndex >= 0)
If _module.debugInformationFormat = DebugInformationFormat.Pdb Then
'Native PDBs: VB EE uses name mangling to match up original locals and the fields where they are hoisted
'The scoping information is passed by recording PDB scopes of "fake" locals named the same
'as the fields. These locals are not emitted to IL.
' vb\language\debugger\procedurecontext.cpp
' 813 // Since state machines lift (almost) all locals of a method, the lifted fields should
' 814 // only be shown in the debugger when the original local variable was in scope. So
' 815 // we first check if there's a local by the given name and attempt to remove it from
' 816 // m_localVariableMap. If it was present, we decode the original local's name, otherwise
' 817 // we skip loading this lifted field since it is out of scope.
_builder.AddLocalToScope(New LocalDefinition(
symbolOpt:=Nothing,
nameOpt:=field.Name,
type:=Nothing,
slot:=field.SlotIndex,
synthesizedKind:=SynthesizedLocalKind.EmitterTemp,
id:=Nothing,
pdbAttributes:=LocalVariableAttributes.None,
constraints:=LocalSlotConstraints.None,
dynamicTransformFlags:=Nothing,
tupleElementNames:=Nothing))
Else
_builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex)
End If
End Sub
Private Sub EmitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch)
' Resume statements will branch here. Just load the resume local and
' branch to the switch table
EmitLabelStatement(node.ResumeLabel)
EmitExpression(node.ResumeTargetTemporary, used:=True)
Dim switchLabel As New Object()
_builder.EmitBranch(ILOpCode.Br_s, switchLabel)
_builder.AdjustStack(-1)
' Resume Next statements will branch here. Increment the resume local and
' fall through to the switch table
EmitLabelStatement(node.ResumeNextLabel)
EmitExpression(node.ResumeTargetTemporary, used:=True)
_builder.EmitIntConstant(1)
_builder.EmitOpCode(ILOpCode.Add)
' now start generating the resume switch table
_builder.MarkLabel(switchLabel)
' but first clear the resume local
_builder.EmitIntConstant(0)
_builder.EmitLocalStore(GetLocal(node.ResumeTargetTemporary))
EmitSwitch(node.Jumps)
End Sub
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/Features/CSharp/Portable/EditAndContinue/SyntaxComparer.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.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Differencing;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue
{
internal sealed class SyntaxComparer : AbstractSyntaxComparer
{
internal static readonly SyntaxComparer TopLevel = new(null, null, null, null, compareStatementSyntax: false);
internal static readonly SyntaxComparer Statement = new(null, null, null, null, compareStatementSyntax: true);
/// <summary>
/// Creates a syntax comparer
/// </summary>
/// <param name="oldRoot">The root node to start comparisons from</param>
/// <param name="newRoot">The new root node to compare against</param>
/// <param name="oldRootChildren">Child nodes that should always be compared</param>
/// <param name="newRootChildren">New child nodes to compare against</param>
/// <param name="compareStatementSyntax">Whether this comparer is in "statement mode"</param>
public SyntaxComparer(
SyntaxNode? oldRoot,
SyntaxNode? newRoot,
IEnumerable<SyntaxNode>? oldRootChildren,
IEnumerable<SyntaxNode>? newRootChildren,
bool compareStatementSyntax)
: base(oldRoot, newRoot, oldRootChildren, newRootChildren, compareStatementSyntax)
{
}
protected override bool IsLambdaBodyStatementOrExpression(SyntaxNode node)
=> LambdaUtilities.IsLambdaBodyStatementOrExpression(node);
#region Labels
// Assumptions:
// - Each listed label corresponds to one or more syntax kinds.
// - Nodes with same labels might produce Update edits, nodes with different labels don't.
// - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label.
// (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label).
// - All descendants of a node whose kind is listed here will be ignored regardless of their labels
internal enum Label
{
// Top level syntax kinds
CompilationUnit,
GlobalStatement,
NamespaceDeclaration,
ExternAliasDirective, // tied to parent
UsingDirective, // tied to parent
TypeDeclaration,
EnumDeclaration,
DelegateDeclaration,
FieldDeclaration, // tied to parent
FieldVariableDeclaration, // tied to parent
FieldVariableDeclarator, // tied to parent
MethodDeclaration, // tied to parent
OperatorDeclaration, // tied to parent
ConversionOperatorDeclaration, // tied to parent
ConstructorDeclaration, // tied to parent
DestructorDeclaration, // tied to parent
PropertyDeclaration, // tied to parent
IndexerDeclaration, // tied to parent
EventDeclaration, // tied to parent
EnumMemberDeclaration, // tied to parent
AccessorList, // tied to parent
AccessorDeclaration, // tied to parent
// Statement syntax kinds
Block,
CheckedStatement,
UnsafeStatement,
TryStatement,
CatchClause, // tied to parent
CatchDeclaration, // tied to parent
CatchFilterClause, // tied to parent
FinallyClause, // tied to parent
ForStatement,
ForStatementPart, // tied to parent
ForEachStatement,
UsingStatement,
FixedStatement,
LockStatement,
WhileStatement,
DoStatement,
IfStatement,
ElseClause, // tied to parent
SwitchStatement,
SwitchSection,
CasePatternSwitchLabel, // tied to parent
SwitchExpression,
SwitchExpressionArm, // tied to parent
WhenClause, // tied to parent
YieldStatement, // tied to parent
GotoStatement,
GotoCaseStatement,
BreakContinueStatement,
ReturnThrowStatement,
ExpressionStatement,
LabeledStatement,
// TODO:
// Ideally we could declare LocalVariableDeclarator tied to the first enclosing node that defines local scope (block, foreach, etc.)
// Also consider handling LocalDeclarationStatement as just a bag of variable declarators,
// so that variable declarators contained in one can be matched with variable declarators contained in the other.
LocalDeclarationStatement, // tied to parent
LocalVariableDeclaration, // tied to parent
LocalVariableDeclarator, // tied to parent
SingleVariableDesignation,
AwaitExpression,
NestedFunction,
FromClause,
QueryBody,
FromClauseLambda, // tied to parent
LetClauseLambda, // tied to parent
WhereClauseLambda, // tied to parent
OrderByClause, // tied to parent
OrderingLambda, // tied to parent
SelectClauseLambda, // tied to parent
JoinClauseLambda, // tied to parent
JoinIntoClause, // tied to parent
GroupClauseLambda, // tied to parent
QueryContinuation, // tied to parent
// Syntax kinds that are common to both statement and top level
TypeParameterList, // tied to parent
TypeParameterConstraintClause, // tied to parent
TypeParameter, // tied to parent
ParameterList, // tied to parent
BracketedParameterList, // tied to parent
Parameter, // tied to parent
AttributeList, // tied to parent
Attribute, // tied to parent
// helpers:
Count,
Ignored = IgnoredNode
}
/// <summary>
/// Return 1 if it is desirable to report two edits (delete and insert) rather than a move edit
/// when the node changes its parent.
/// </summary>
private static int TiedToAncestor(Label label)
{
switch (label)
{
// Top level syntax
case Label.ExternAliasDirective:
case Label.UsingDirective:
case Label.FieldDeclaration:
case Label.FieldVariableDeclaration:
case Label.FieldVariableDeclarator:
case Label.MethodDeclaration:
case Label.OperatorDeclaration:
case Label.ConversionOperatorDeclaration:
case Label.ConstructorDeclaration:
case Label.DestructorDeclaration:
case Label.PropertyDeclaration:
case Label.IndexerDeclaration:
case Label.EventDeclaration:
case Label.EnumMemberDeclaration:
case Label.AccessorDeclaration:
case Label.AccessorList:
case Label.TypeParameterList:
case Label.TypeParameter:
case Label.TypeParameterConstraintClause:
case Label.ParameterList:
case Label.BracketedParameterList:
case Label.Parameter:
case Label.AttributeList:
case Label.Attribute:
return 1;
// Statement syntax
case Label.LocalDeclarationStatement:
case Label.LocalVariableDeclaration:
case Label.LocalVariableDeclarator:
case Label.GotoCaseStatement:
case Label.BreakContinueStatement:
case Label.ElseClause:
case Label.CatchClause:
case Label.CatchDeclaration:
case Label.CatchFilterClause:
case Label.FinallyClause:
case Label.ForStatementPart:
case Label.YieldStatement:
case Label.FromClauseLambda:
case Label.LetClauseLambda:
case Label.WhereClauseLambda:
case Label.OrderByClause:
case Label.OrderingLambda:
case Label.SelectClauseLambda:
case Label.JoinClauseLambda:
case Label.JoinIntoClause:
case Label.GroupClauseLambda:
case Label.QueryContinuation:
case Label.CasePatternSwitchLabel:
case Label.WhenClause:
case Label.SwitchExpressionArm:
return 1;
default:
return 0;
}
}
internal override int Classify(int kind, SyntaxNode? node, out bool isLeaf)
=> (int)Classify((SyntaxKind)kind, node, out isLeaf);
internal Label Classify(SyntaxKind kind, SyntaxNode? node, out bool isLeaf)
{
isLeaf = false;
// If the node is a for loop Initializer, Condition, or Incrementor expression we label it as "ForStatementPart".
// We need to capture it in the match since these expressions can be "active statements" and as such we need to map them.
//
// The parent is not available only when comparing nodes for value equality.
if (node != null && node.Parent.IsKind(SyntaxKind.ForStatement) && node is ExpressionSyntax)
{
return Label.ForStatementPart;
}
// ************************************
// Top and statement syntax
// ************************************
// These nodes can appear during top level and statement processing, so we put them in this first
// switch for simplicity. Statement specific, and top level specific cases are handled below.
switch (kind)
{
case SyntaxKind.CompilationUnit:
return Label.CompilationUnit;
case SyntaxKind.TypeParameterList:
return Label.TypeParameterList;
case SyntaxKind.TypeParameterConstraintClause:
return Label.TypeParameterConstraintClause;
case SyntaxKind.TypeParameter:
// not a leaf because an attribute may be applied
return Label.TypeParameter;
case SyntaxKind.BracketedParameterList:
return Label.BracketedParameterList;
case SyntaxKind.ParameterList:
return Label.ParameterList;
case SyntaxKind.Parameter:
return Label.Parameter;
case SyntaxKind.ConstructorDeclaration:
// Root when matching constructor bodies.
return Label.ConstructorDeclaration;
}
if (_compareStatementSyntax)
{
return ClassifyStatementSyntax(kind, node, out isLeaf);
}
return ClassifyTopSyntax(kind, node, out isLeaf);
}
private static Label ClassifyStatementSyntax(SyntaxKind kind, SyntaxNode? node, out bool isLeaf)
{
isLeaf = false;
// ************************************
// Statement syntax
// ************************************
// These nodes could potentially be seen as top level syntax, but we only want them labelled
// during statement syntax so they have to be kept separate.
//
// For example when top level sees something like this:
//
// private int X => new Func(() => { return 1 })();
//
// It needs to go through the entire lambda to know if that property def has changed
// but if we start labelling things, like ReturnStatement in the above example, then
// it will stop. Given that a block bodied lambda can have any statements a user likes
// the whole set has to be dealt with separately.
switch (kind)
{
// Notes:
// A descendant of a leaf node may be a labeled node that we don't want to visit if
// we are comparing its parent node (used for lambda bodies).
//
// Expressions are ignored but they may contain nodes that should be matched by tree comparer.
// (e.g. lambdas, declaration expressions). Descending to these nodes is handled in EnumerateChildren.
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
// These declarations can come after global statements so we want to stop statement matching
// because no global statements can come after them
isLeaf = true;
return Label.Ignored;
case SyntaxKind.LocalDeclarationStatement:
return Label.LocalDeclarationStatement;
case SyntaxKind.SingleVariableDesignation:
return Label.SingleVariableDesignation;
case SyntaxKind.LabeledStatement:
return Label.LabeledStatement;
case SyntaxKind.EmptyStatement:
isLeaf = true;
return Label.ExpressionStatement;
case SyntaxKind.GotoStatement:
isLeaf = true;
return Label.GotoStatement;
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.GotoDefaultStatement:
isLeaf = true;
return Label.GotoCaseStatement;
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
isLeaf = true;
return Label.BreakContinueStatement;
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
return Label.ReturnThrowStatement;
case SyntaxKind.ExpressionStatement:
return Label.ExpressionStatement;
case SyntaxKind.YieldBreakStatement:
case SyntaxKind.YieldReturnStatement:
return Label.YieldStatement;
case SyntaxKind.DoStatement:
return Label.DoStatement;
case SyntaxKind.WhileStatement:
return Label.WhileStatement;
case SyntaxKind.ForStatement:
return Label.ForStatement;
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.ForEachStatement:
return Label.ForEachStatement;
case SyntaxKind.UsingStatement:
return Label.UsingStatement;
case SyntaxKind.FixedStatement:
return Label.FixedStatement;
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return Label.CheckedStatement;
case SyntaxKind.UnsafeStatement:
return Label.UnsafeStatement;
case SyntaxKind.LockStatement:
return Label.LockStatement;
case SyntaxKind.IfStatement:
return Label.IfStatement;
case SyntaxKind.ElseClause:
return Label.ElseClause;
case SyntaxKind.SwitchStatement:
return Label.SwitchStatement;
case SyntaxKind.SwitchSection:
return Label.SwitchSection;
case SyntaxKind.CaseSwitchLabel:
case SyntaxKind.DefaultSwitchLabel:
// Switch labels are included in the "value" of the containing switch section.
// We don't need to analyze case expressions.
isLeaf = true;
return Label.Ignored;
case SyntaxKind.WhenClause:
return Label.WhenClause;
case SyntaxKind.CasePatternSwitchLabel:
return Label.CasePatternSwitchLabel;
case SyntaxKind.SwitchExpression:
return Label.SwitchExpression;
case SyntaxKind.SwitchExpressionArm:
return Label.SwitchExpressionArm;
case SyntaxKind.TryStatement:
return Label.TryStatement;
case SyntaxKind.CatchClause:
return Label.CatchClause;
case SyntaxKind.CatchDeclaration:
// the declarator of the exception variable
return Label.CatchDeclaration;
case SyntaxKind.CatchFilterClause:
return Label.CatchFilterClause;
case SyntaxKind.FinallyClause:
return Label.FinallyClause;
case SyntaxKind.FromClause:
// The first from clause of a query is not a lambda.
// We have to assign it a label different from "FromClauseLambda"
// so that we won't match lambda-from to non-lambda-from.
//
// Since FromClause declares range variables we need to include it in the map,
// so that we are able to map range variable declarations.
// Therefore we assign it a dedicated label.
//
// The parent is not available only when comparing nodes for value equality.
// In that case it doesn't matter what label the node has as long as it has some.
if (node == null || node.Parent.IsKind(SyntaxKind.QueryExpression))
{
return Label.FromClause;
}
return Label.FromClauseLambda;
case SyntaxKind.QueryBody:
return Label.QueryBody;
case SyntaxKind.QueryContinuation:
return Label.QueryContinuation;
case SyntaxKind.LetClause:
return Label.LetClauseLambda;
case SyntaxKind.WhereClause:
return Label.WhereClauseLambda;
case SyntaxKind.OrderByClause:
return Label.OrderByClause;
case SyntaxKind.AscendingOrdering:
case SyntaxKind.DescendingOrdering:
return Label.OrderingLambda;
case SyntaxKind.SelectClause:
return Label.SelectClauseLambda;
case SyntaxKind.JoinClause:
return Label.JoinClauseLambda;
case SyntaxKind.JoinIntoClause:
return Label.JoinIntoClause;
case SyntaxKind.GroupClause:
return Label.GroupClauseLambda;
case SyntaxKind.IdentifierName:
case SyntaxKind.QualifiedName:
case SyntaxKind.GenericName:
case SyntaxKind.TypeArgumentList:
case SyntaxKind.AliasQualifiedName:
case SyntaxKind.PredefinedType:
case SyntaxKind.PointerType:
case SyntaxKind.NullableType:
case SyntaxKind.TupleType:
case SyntaxKind.RefType:
case SyntaxKind.OmittedTypeArgument:
case SyntaxKind.NameColon:
case SyntaxKind.OmittedArraySizeExpression:
case SyntaxKind.ThisExpression:
case SyntaxKind.BaseExpression:
case SyntaxKind.ArgListExpression:
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
case SyntaxKind.TypeOfExpression:
case SyntaxKind.SizeOfExpression:
case SyntaxKind.DefaultExpression:
case SyntaxKind.ConstantPattern:
case SyntaxKind.DiscardDesignation:
// can't contain a lambda/await/anonymous type:
isLeaf = true;
return Label.Ignored;
case SyntaxKind.AwaitExpression:
return Label.AwaitExpression;
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.LocalFunctionStatement:
return Label.NestedFunction;
case SyntaxKind.VariableDeclaration:
return Label.LocalVariableDeclaration;
case SyntaxKind.VariableDeclarator:
return Label.LocalVariableDeclarator;
case SyntaxKind.Block:
return Label.Block;
}
// If we got this far, its an unlabelled node. Since just about any node can
// contain a lambda, isLeaf must be false for statement syntax.
return Label.Ignored;
}
private static Label ClassifyTopSyntax(SyntaxKind kind, SyntaxNode? node, out bool isLeaf)
{
isLeaf = false;
// ************************************
// Top syntax
// ************************************
// More the most part these nodes will only appear in top syntax but its easier to
// keep them separate so we can more easily discern was is shared, above.
switch (kind)
{
case SyntaxKind.GlobalStatement:
isLeaf = true;
return Label.GlobalStatement;
case SyntaxKind.ExternAliasDirective:
isLeaf = true;
return Label.ExternAliasDirective;
case SyntaxKind.UsingDirective:
isLeaf = true;
return Label.UsingDirective;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return Label.NamespaceDeclaration;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return Label.TypeDeclaration;
case SyntaxKind.MethodDeclaration:
return Label.MethodDeclaration;
case SyntaxKind.EnumDeclaration:
return Label.EnumDeclaration;
case SyntaxKind.DelegateDeclaration:
return Label.DelegateDeclaration;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
return Label.FieldDeclaration;
case SyntaxKind.ConversionOperatorDeclaration:
return Label.ConversionOperatorDeclaration;
case SyntaxKind.OperatorDeclaration:
return Label.OperatorDeclaration;
case SyntaxKind.DestructorDeclaration:
isLeaf = true;
return Label.DestructorDeclaration;
case SyntaxKind.PropertyDeclaration:
return Label.PropertyDeclaration;
case SyntaxKind.IndexerDeclaration:
return Label.IndexerDeclaration;
case SyntaxKind.EventDeclaration:
return Label.EventDeclaration;
case SyntaxKind.EnumMemberDeclaration:
// not a leaf because an attribute may be applied
return Label.EnumMemberDeclaration;
case SyntaxKind.AccessorList:
return Label.AccessorList;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
isLeaf = true;
return Label.AccessorDeclaration;
// Note: These last two do actually appear as statement syntax, but mean something
// different and hence have a different label
case SyntaxKind.VariableDeclaration:
return Label.FieldVariableDeclaration;
case SyntaxKind.VariableDeclarator:
// For top syntax, a variable declarator is a leaf node
isLeaf = true;
return Label.FieldVariableDeclarator;
case SyntaxKind.AttributeList:
// Only module/assembly attributes are labelled
if (node is not null && node.IsParentKind(SyntaxKind.CompilationUnit))
{
return Label.AttributeList;
}
break;
case SyntaxKind.Attribute:
// Only module/assembly attributes are labelled
if (node is { Parent: { } parent } && parent.IsParentKind(SyntaxKind.CompilationUnit))
{
isLeaf = true;
return Label.Attribute;
}
break;
}
// If we got this far, its an unlabelled node. For top
// syntax, we don't need to descend into any ignored nodes
isLeaf = true;
return Label.Ignored;
}
// internal for testing
internal bool HasLabel(SyntaxKind kind)
=> Classify(kind, node: null, out _) != Label.Ignored;
protected internal override int LabelCount
=> (int)Label.Count;
protected internal override int TiedToAncestor(int label)
=> TiedToAncestor((Label)label);
#endregion
#region Comparisons
public override bool ValuesEqual(SyntaxNode left, SyntaxNode right)
{
Func<SyntaxKind, bool>? ignoreChildFunction;
switch (left.Kind())
{
// all syntax kinds with a method body child:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
// When comparing method bodies we need to NOT ignore VariableDeclaration and VariableDeclarator children,
// but when comparing field definitions we should ignore VariableDeclarations children.
var leftBody = GetBody(left);
var rightBody = GetBody(right);
if (!SyntaxFactory.AreEquivalent(leftBody, rightBody, null))
{
return false;
}
ignoreChildFunction = childKind => childKind == SyntaxKind.Block || childKind == SyntaxKind.ArrowExpressionClause || HasLabel(childKind);
break;
case SyntaxKind.SwitchSection:
return Equal((SwitchSectionSyntax)left, (SwitchSectionSyntax)right);
case SyntaxKind.ForStatement:
// The only children of ForStatement are labeled nodes and punctuation.
return true;
default:
if (HasChildren(left))
{
ignoreChildFunction = childKind => HasLabel(childKind);
}
else
{
ignoreChildFunction = null;
}
break;
}
return SyntaxFactory.AreEquivalent(left, right, ignoreChildFunction);
}
private bool Equal(SwitchSectionSyntax left, SwitchSectionSyntax right)
{
return SyntaxFactory.AreEquivalent(left.Labels, right.Labels, null)
&& SyntaxFactory.AreEquivalent(left.Statements, right.Statements, ignoreChildNode: HasLabel);
}
private static SyntaxNode? GetBody(SyntaxNode node)
{
switch (node)
{
case BaseMethodDeclarationSyntax baseMethodDeclarationSyntax: return baseMethodDeclarationSyntax.Body ?? (SyntaxNode?)baseMethodDeclarationSyntax.ExpressionBody?.Expression;
case AccessorDeclarationSyntax accessorDeclarationSyntax: return accessorDeclarationSyntax.Body ?? (SyntaxNode?)accessorDeclarationSyntax.ExpressionBody?.Expression;
default: throw ExceptionUtilities.UnexpectedValue(node);
}
}
protected override bool TryComputeWeightedDistance(SyntaxNode leftNode, SyntaxNode rightNode, out double distance)
{
switch (leftNode.Kind())
{
case SyntaxKind.VariableDeclarator:
distance = ComputeDistance(
((VariableDeclaratorSyntax)leftNode).Identifier,
((VariableDeclaratorSyntax)rightNode).Identifier);
return true;
case SyntaxKind.ForStatement:
var leftFor = (ForStatementSyntax)leftNode;
var rightFor = (ForStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftFor, rightFor);
return true;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
{
var leftForEach = (CommonForEachStatementSyntax)leftNode;
var rightForEach = (CommonForEachStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftForEach, rightForEach);
return true;
}
case SyntaxKind.UsingStatement:
var leftUsing = (UsingStatementSyntax)leftNode;
var rightUsing = (UsingStatementSyntax)rightNode;
if (leftUsing.Declaration != null && rightUsing.Declaration != null)
{
distance = ComputeWeightedDistance(
leftUsing.Declaration,
leftUsing.Statement,
rightUsing.Declaration,
rightUsing.Statement);
}
else
{
distance = ComputeWeightedDistance(
(SyntaxNode?)leftUsing.Expression ?? leftUsing.Declaration!,
leftUsing.Statement,
(SyntaxNode?)rightUsing.Expression ?? rightUsing.Declaration!,
rightUsing.Statement);
}
return true;
case SyntaxKind.LockStatement:
var leftLock = (LockStatementSyntax)leftNode;
var rightLock = (LockStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftLock.Expression, leftLock.Statement, rightLock.Expression, rightLock.Statement);
return true;
case SyntaxKind.FixedStatement:
var leftFixed = (FixedStatementSyntax)leftNode;
var rightFixed = (FixedStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftFixed.Declaration, leftFixed.Statement, rightFixed.Declaration, rightFixed.Statement);
return true;
case SyntaxKind.WhileStatement:
var leftWhile = (WhileStatementSyntax)leftNode;
var rightWhile = (WhileStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftWhile.Condition, leftWhile.Statement, rightWhile.Condition, rightWhile.Statement);
return true;
case SyntaxKind.DoStatement:
var leftDo = (DoStatementSyntax)leftNode;
var rightDo = (DoStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftDo.Condition, leftDo.Statement, rightDo.Condition, rightDo.Statement);
return true;
case SyntaxKind.IfStatement:
var leftIf = (IfStatementSyntax)leftNode;
var rightIf = (IfStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statement, rightIf.Condition, rightIf.Statement);
return true;
case SyntaxKind.Block:
var leftBlock = (BlockSyntax)leftNode;
var rightBlock = (BlockSyntax)rightNode;
return TryComputeWeightedDistance(leftBlock, rightBlock, out distance);
case SyntaxKind.CatchClause:
distance = ComputeWeightedDistance((CatchClauseSyntax)leftNode, (CatchClauseSyntax)rightNode);
return true;
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.LocalFunctionStatement:
distance = ComputeWeightedDistanceOfNestedFunctions(leftNode, rightNode);
return true;
case SyntaxKind.YieldBreakStatement:
case SyntaxKind.YieldReturnStatement:
// Ignore the expression of yield return. The structure of the state machine is more important than the yielded values.
distance = (leftNode.RawKind == rightNode.RawKind) ? 0.0 : 0.1;
return true;
case SyntaxKind.SingleVariableDesignation:
distance = ComputeWeightedDistance((SingleVariableDesignationSyntax)leftNode, (SingleVariableDesignationSyntax)rightNode);
return true;
case SyntaxKind.TypeParameterConstraintClause:
distance = ComputeDistance((TypeParameterConstraintClauseSyntax)leftNode, (TypeParameterConstraintClauseSyntax)rightNode);
return true;
case SyntaxKind.TypeParameter:
distance = ComputeDistance((TypeParameterSyntax)leftNode, (TypeParameterSyntax)rightNode);
return true;
case SyntaxKind.Parameter:
distance = ComputeDistance((ParameterSyntax)leftNode, (ParameterSyntax)rightNode);
return true;
case SyntaxKind.AttributeList:
distance = ComputeDistance((AttributeListSyntax)leftNode, (AttributeListSyntax)rightNode);
return true;
case SyntaxKind.Attribute:
distance = ComputeDistance((AttributeSyntax)leftNode, (AttributeSyntax)rightNode);
return true;
default:
var leftName = TryGetName(leftNode);
var rightName = TryGetName(rightNode);
Contract.ThrowIfFalse(rightName.HasValue == leftName.HasValue);
if (leftName.HasValue)
{
distance = ComputeDistance(leftName.Value, rightName!.Value);
return true;
}
else
{
distance = 0;
return false;
}
}
}
private static double ComputeWeightedDistanceOfNestedFunctions(SyntaxNode leftNode, SyntaxNode rightNode)
{
GetNestedFunctionsParts(leftNode, out var leftParameters, out var leftAsync, out var leftBody, out var leftModifiers, out var leftReturnType, out var leftIdentifier, out var leftTypeParameters);
GetNestedFunctionsParts(rightNode, out var rightParameters, out var rightAsync, out var rightBody, out var rightModifiers, out var rightReturnType, out var rightIdentifier, out var rightTypeParameters);
if ((leftAsync.Kind() == SyntaxKind.AsyncKeyword) != (rightAsync.Kind() == SyntaxKind.AsyncKeyword))
{
return 1.0;
}
var modifierDistance = ComputeDistance(leftModifiers, rightModifiers);
var returnTypeDistance = ComputeDistance(leftReturnType, rightReturnType);
var identifierDistance = ComputeDistance(leftIdentifier, rightIdentifier);
var typeParameterDistance = ComputeDistance(leftTypeParameters, rightTypeParameters);
var parameterDistance = ComputeDistance(leftParameters, rightParameters);
var bodyDistance = ComputeDistance(leftBody, rightBody);
return
modifierDistance * 0.1 +
returnTypeDistance * 0.1 +
identifierDistance * 0.2 +
typeParameterDistance * 0.2 +
parameterDistance * 0.2 +
bodyDistance * 0.2;
}
private static void GetNestedFunctionsParts(
SyntaxNode nestedFunction,
out IEnumerable<SyntaxToken> parameters,
out SyntaxToken asyncKeyword,
out SyntaxNode body,
out SyntaxTokenList modifiers,
out TypeSyntax? returnType,
out SyntaxToken identifier,
out TypeParameterListSyntax? typeParameters)
{
switch (nestedFunction.Kind())
{
case SyntaxKind.SimpleLambdaExpression:
var simple = (SimpleLambdaExpressionSyntax)nestedFunction;
parameters = simple.Parameter.DescendantTokens();
asyncKeyword = simple.AsyncKeyword;
body = simple.Body;
modifiers = default;
returnType = null;
identifier = default;
typeParameters = null;
break;
case SyntaxKind.ParenthesizedLambdaExpression:
var parenthesized = (ParenthesizedLambdaExpressionSyntax)nestedFunction;
parameters = GetDescendantTokensIgnoringSeparators(parenthesized.ParameterList.Parameters);
asyncKeyword = parenthesized.AsyncKeyword;
body = parenthesized.Body;
modifiers = default;
returnType = null;
identifier = default;
typeParameters = null;
break;
case SyntaxKind.AnonymousMethodExpression:
var anonymous = (AnonymousMethodExpressionSyntax)nestedFunction;
if (anonymous.ParameterList != null)
{
parameters = GetDescendantTokensIgnoringSeparators(anonymous.ParameterList.Parameters);
}
else
{
parameters = SpecializedCollections.EmptyEnumerable<SyntaxToken>();
}
asyncKeyword = anonymous.AsyncKeyword;
body = anonymous.Block;
modifiers = default;
returnType = null;
identifier = default;
typeParameters = null;
break;
case SyntaxKind.LocalFunctionStatement:
var localFunction = (LocalFunctionStatementSyntax)nestedFunction;
parameters = GetDescendantTokensIgnoringSeparators(localFunction.ParameterList.Parameters);
asyncKeyword = default;
body = (SyntaxNode?)localFunction.Body ?? localFunction.ExpressionBody!;
modifiers = localFunction.Modifiers;
returnType = localFunction.ReturnType;
identifier = localFunction.Identifier;
typeParameters = localFunction.TypeParameterList;
break;
default:
throw ExceptionUtilities.UnexpectedValue(nestedFunction.Kind());
}
}
private bool TryComputeWeightedDistance(BlockSyntax leftBlock, BlockSyntax rightBlock, out double distance)
{
// No block can be matched with the root block.
// Note that in constructors the root is the constructor declaration, since we need to include
// the constructor initializer in the match.
if (leftBlock.Parent == null ||
rightBlock.Parent == null ||
leftBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration) ||
rightBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration))
{
distance = 0.0;
return true;
}
if (GetLabel(leftBlock.Parent) != GetLabel(rightBlock.Parent))
{
distance = 0.2 + 0.8 * ComputeWeightedBlockDistance(leftBlock, rightBlock);
return true;
}
switch (leftBlock.Parent.Kind())
{
case SyntaxKind.IfStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.FixedStatement:
case SyntaxKind.LockStatement:
case SyntaxKind.UsingStatement:
case SyntaxKind.SwitchSection:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.LocalFunctionStatement:
// value distance of the block body is included:
distance = GetDistance(leftBlock.Parent, rightBlock.Parent);
return true;
case SyntaxKind.CatchClause:
var leftCatch = (CatchClauseSyntax)leftBlock.Parent;
var rightCatch = (CatchClauseSyntax)rightBlock.Parent;
if (leftCatch.Declaration == null && leftCatch.Filter == null &&
rightCatch.Declaration == null && rightCatch.Filter == null)
{
var leftTry = (TryStatementSyntax)leftCatch.Parent!;
var rightTry = (TryStatementSyntax)rightCatch.Parent!;
distance = 0.5 * ComputeValueDistance(leftTry.Block, rightTry.Block) +
0.5 * ComputeValueDistance(leftBlock, rightBlock);
}
else
{
// value distance of the block body is included:
distance = GetDistance(leftBlock.Parent, rightBlock.Parent);
}
return true;
case SyntaxKind.Block:
case SyntaxKind.LabeledStatement:
distance = ComputeWeightedBlockDistance(leftBlock, rightBlock);
return true;
case SyntaxKind.UnsafeStatement:
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
case SyntaxKind.ElseClause:
case SyntaxKind.FinallyClause:
case SyntaxKind.TryStatement:
distance = 0.2 * ComputeValueDistance(leftBlock, rightBlock);
return true;
default:
throw ExceptionUtilities.UnexpectedValue(leftBlock.Parent.Kind());
}
}
private double ComputeWeightedDistance(SingleVariableDesignationSyntax leftNode, SingleVariableDesignationSyntax rightNode)
{
var distance = ComputeDistance(leftNode, rightNode);
double parentDistance;
if (leftNode.Parent != null &&
rightNode.Parent != null &&
GetLabel(leftNode.Parent) == GetLabel(rightNode.Parent))
{
parentDistance = ComputeDistance(leftNode.Parent, rightNode.Parent);
}
else
{
parentDistance = 1;
}
return 0.5 * parentDistance + 0.5 * distance;
}
private static double ComputeWeightedBlockDistance(BlockSyntax leftBlock, BlockSyntax rightBlock)
{
if (TryComputeLocalsDistance(leftBlock, rightBlock, out var distance))
{
return distance;
}
return ComputeValueDistance(leftBlock, rightBlock);
}
private static double ComputeWeightedDistance(CatchClauseSyntax left, CatchClauseSyntax right)
{
var blockDistance = ComputeDistance(left.Block, right.Block);
var distance = CombineOptional(blockDistance, left.Declaration, right.Declaration, left.Filter, right.Filter);
return AdjustForLocalsInBlock(distance, left.Block, right.Block, localsWeight: 0.3);
}
private static double ComputeWeightedDistance(
CommonForEachStatementSyntax leftCommonForEach,
CommonForEachStatementSyntax rightCommonForEach)
{
var statementDistance = ComputeDistance(leftCommonForEach.Statement, rightCommonForEach.Statement);
var expressionDistance = ComputeDistance(leftCommonForEach.Expression, rightCommonForEach.Expression);
List<SyntaxToken>? leftLocals = null;
List<SyntaxToken>? rightLocals = null;
GetLocalNames(leftCommonForEach, ref leftLocals);
GetLocalNames(rightCommonForEach, ref rightLocals);
var localNamesDistance = ComputeDistance(leftLocals, rightLocals);
var distance = localNamesDistance * 0.6 + expressionDistance * 0.2 + statementDistance * 0.2;
return AdjustForLocalsInBlock(distance, leftCommonForEach.Statement, rightCommonForEach.Statement, localsWeight: 0.6);
}
private static double ComputeWeightedDistance(ForStatementSyntax left, ForStatementSyntax right)
{
var statementDistance = ComputeDistance(left.Statement, right.Statement);
var conditionDistance = ComputeDistance(left.Condition, right.Condition);
var incDistance = ComputeDistance(
GetDescendantTokensIgnoringSeparators(left.Incrementors), GetDescendantTokensIgnoringSeparators(right.Incrementors));
var distance = conditionDistance * 0.3 + incDistance * 0.3 + statementDistance * 0.4;
if (TryComputeLocalsDistance(left.Declaration, right.Declaration, out var localsDistance))
{
distance = distance * 0.4 + localsDistance * 0.6;
}
return distance;
}
private static double ComputeWeightedDistance(
VariableDeclarationSyntax leftVariables,
StatementSyntax leftStatement,
VariableDeclarationSyntax rightVariables,
StatementSyntax rightStatement)
{
var distance = ComputeDistance(leftStatement, rightStatement);
// Put maximum weight behind the variables declared in the header of the statement.
if (TryComputeLocalsDistance(leftVariables, rightVariables, out var localsDistance))
{
distance = distance * 0.4 + localsDistance * 0.6;
}
// If the statement is a block that declares local variables,
// weight them more than the rest of the statement.
return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.2);
}
private static double ComputeWeightedDistance(
SyntaxNode? leftHeader,
StatementSyntax leftStatement,
SyntaxNode? rightHeader,
StatementSyntax rightStatement)
{
var headerDistance = ComputeDistance(leftHeader, rightHeader);
var statementDistance = ComputeDistance(leftStatement, rightStatement);
var distance = headerDistance * 0.6 + statementDistance * 0.4;
return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.5);
}
private static double AdjustForLocalsInBlock(
double distance,
StatementSyntax leftStatement,
StatementSyntax rightStatement,
double localsWeight)
{
// If the statement is a block that declares local variables,
// weight them more than the rest of the statement.
if (leftStatement.Kind() == SyntaxKind.Block && rightStatement.Kind() == SyntaxKind.Block)
{
if (TryComputeLocalsDistance((BlockSyntax)leftStatement, (BlockSyntax)rightStatement, out var localsDistance))
{
return localsDistance * localsWeight + distance * (1 - localsWeight);
}
}
return distance;
}
private static bool TryComputeLocalsDistance(VariableDeclarationSyntax? left, VariableDeclarationSyntax? right, out double distance)
{
List<SyntaxToken>? leftLocals = null;
List<SyntaxToken>? rightLocals = null;
if (left != null)
{
GetLocalNames(left, ref leftLocals);
}
if (right != null)
{
GetLocalNames(right, ref rightLocals);
}
if (leftLocals == null || rightLocals == null)
{
distance = 0;
return false;
}
distance = ComputeDistance(leftLocals, rightLocals);
return true;
}
private static bool TryComputeLocalsDistance(BlockSyntax left, BlockSyntax right, out double distance)
{
List<SyntaxToken>? leftLocals = null;
List<SyntaxToken>? rightLocals = null;
GetLocalNames(left, ref leftLocals);
GetLocalNames(right, ref rightLocals);
if (leftLocals == null || rightLocals == null)
{
distance = 0;
return false;
}
distance = ComputeDistance(leftLocals, rightLocals);
return true;
}
// Doesn't include variables declared in declaration expressions
// Consider including them (https://github.com/dotnet/roslyn/issues/37460).
private static void GetLocalNames(BlockSyntax block, ref List<SyntaxToken>? result)
{
foreach (var child in block.ChildNodes())
{
if (child.IsKind(SyntaxKind.LocalDeclarationStatement, out LocalDeclarationStatementSyntax? localDecl))
{
GetLocalNames(localDecl.Declaration, ref result);
}
}
}
// Doesn't include variables declared in declaration expressions
// Consider including them (https://github.com/dotnet/roslyn/issues/37460).
private static void GetLocalNames(VariableDeclarationSyntax localDeclaration, ref List<SyntaxToken>? result)
{
foreach (var local in localDeclaration.Variables)
{
GetLocalNames(local.Identifier, ref result);
}
}
internal static void GetLocalNames(CommonForEachStatementSyntax commonForEach, ref List<SyntaxToken>? result)
{
switch (commonForEach.Kind())
{
case SyntaxKind.ForEachStatement:
GetLocalNames(((ForEachStatementSyntax)commonForEach).Identifier, ref result);
return;
case SyntaxKind.ForEachVariableStatement:
var forEachVariable = (ForEachVariableStatementSyntax)commonForEach;
GetLocalNames(forEachVariable.Variable, ref result);
return;
default:
throw ExceptionUtilities.UnexpectedValue(commonForEach.Kind());
}
}
private static void GetLocalNames(ExpressionSyntax expression, ref List<SyntaxToken>? result)
{
switch (expression.Kind())
{
case SyntaxKind.DeclarationExpression:
var declarationExpression = (DeclarationExpressionSyntax)expression;
var localDeclaration = declarationExpression.Designation;
GetLocalNames(localDeclaration, ref result);
return;
case SyntaxKind.TupleExpression:
var tupleExpression = (TupleExpressionSyntax)expression;
foreach (var argument in tupleExpression.Arguments)
{
GetLocalNames(argument.Expression, ref result);
}
return;
default:
// Do nothing for node that cannot have variable declarations inside.
return;
}
}
private static void GetLocalNames(VariableDesignationSyntax designation, ref List<SyntaxToken>? result)
{
switch (designation.Kind())
{
case SyntaxKind.SingleVariableDesignation:
GetLocalNames(((SingleVariableDesignationSyntax)designation).Identifier, ref result);
return;
case SyntaxKind.ParenthesizedVariableDesignation:
var parenthesizedVariableDesignation = (ParenthesizedVariableDesignationSyntax)designation;
foreach (var variableDesignation in parenthesizedVariableDesignation.Variables)
{
GetLocalNames(variableDesignation, ref result);
}
return;
case SyntaxKind.DiscardDesignation:
return;
default:
throw ExceptionUtilities.UnexpectedValue(designation.Kind());
}
}
private static void GetLocalNames(SyntaxToken syntaxToken, [NotNull] ref List<SyntaxToken>? result)
{
result ??= new List<SyntaxToken>();
result.Add(syntaxToken);
}
private static double CombineOptional(
double distance0,
SyntaxNode? left1,
SyntaxNode? right1,
SyntaxNode? left2,
SyntaxNode? right2,
double weight0 = 0.8,
double weight1 = 0.5)
{
var one = left1 != null || right1 != null;
var two = left2 != null || right2 != null;
if (!one && !two)
{
return distance0;
}
var distance1 = ComputeDistance(left1, right1);
var distance2 = ComputeDistance(left2, right2);
double d;
if (one && two)
{
d = distance1 * weight1 + distance2 * (1 - weight1);
}
else if (one)
{
d = distance1;
}
else
{
d = distance2;
}
return distance0 * weight0 + d * (1 - weight0);
}
private static SyntaxNodeOrToken? TryGetName(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ExternAliasDirective:
return ((ExternAliasDirectiveSyntax)node).Identifier;
case SyntaxKind.UsingDirective:
return ((UsingDirectiveSyntax)node).Name;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return ((BaseNamespaceDeclarationSyntax)node).Name;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return ((TypeDeclarationSyntax)node).Identifier;
case SyntaxKind.EnumDeclaration:
return ((EnumDeclarationSyntax)node).Identifier;
case SyntaxKind.DelegateDeclaration:
return ((DelegateDeclarationSyntax)node).Identifier;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.VariableDeclaration:
return null;
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)node).Identifier;
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)node).Identifier;
case SyntaxKind.ConversionOperatorDeclaration:
return ((ConversionOperatorDeclarationSyntax)node).Type;
case SyntaxKind.OperatorDeclaration:
return ((OperatorDeclarationSyntax)node).OperatorToken;
case SyntaxKind.ConstructorDeclaration:
return ((ConstructorDeclarationSyntax)node).Identifier;
case SyntaxKind.DestructorDeclaration:
return ((DestructorDeclarationSyntax)node).Identifier;
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)node).Identifier;
case SyntaxKind.IndexerDeclaration:
return null;
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)node).Identifier;
case SyntaxKind.EnumMemberDeclaration:
return ((EnumMemberDeclarationSyntax)node).Identifier;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
return null;
case SyntaxKind.TypeParameterConstraintClause:
return ((TypeParameterConstraintClauseSyntax)node).Name.Identifier;
case SyntaxKind.TypeParameter:
return ((TypeParameterSyntax)node).Identifier;
case SyntaxKind.TypeParameterList:
case SyntaxKind.ParameterList:
case SyntaxKind.BracketedParameterList:
return null;
case SyntaxKind.Parameter:
return ((ParameterSyntax)node).Identifier;
case SyntaxKind.AttributeList:
return ((AttributeListSyntax)node).Target;
case SyntaxKind.Attribute:
return ((AttributeSyntax)node).Name;
default:
return null;
}
}
public sealed override double GetDistance(SyntaxNode oldNode, SyntaxNode newNode)
{
Debug.Assert(GetLabel(oldNode) == GetLabel(newNode) && GetLabel(oldNode) != IgnoredNode);
if (oldNode == newNode)
{
return ExactMatchDist;
}
if (TryComputeWeightedDistance(oldNode, newNode, out var weightedDistance))
{
if (weightedDistance == ExactMatchDist && !SyntaxFactory.AreEquivalent(oldNode, newNode))
{
weightedDistance = EpsilonDist;
}
return weightedDistance;
}
return ComputeValueDistance(oldNode, newNode);
}
internal static double ComputeValueDistance(SyntaxNode? oldNode, SyntaxNode? newNode)
{
if (SyntaxFactory.AreEquivalent(oldNode, newNode))
{
return ExactMatchDist;
}
var distance = ComputeDistance(oldNode, newNode);
// We don't want to return an exact match, because there
// must be something different, since we got here
return (distance == ExactMatchDist) ? EpsilonDist : distance;
}
internal static double ComputeDistance(SyntaxNodeOrToken oldNodeOrToken, SyntaxNodeOrToken newNodeOrToken)
{
Debug.Assert(newNodeOrToken.IsToken == oldNodeOrToken.IsToken);
double distance;
if (oldNodeOrToken.IsToken)
{
var leftToken = oldNodeOrToken.AsToken();
var rightToken = newNodeOrToken.AsToken();
distance = ComputeDistance(leftToken, rightToken);
Debug.Assert(!SyntaxFactory.AreEquivalent(leftToken, rightToken) || distance == ExactMatchDist);
}
else
{
var leftNode = oldNodeOrToken.AsNode();
var rightNode = newNodeOrToken.AsNode();
distance = ComputeDistance(leftNode, rightNode);
Debug.Assert(!SyntaxFactory.AreEquivalent(leftNode, rightNode) || distance == ExactMatchDist);
}
return distance;
}
/// <summary>
/// Enumerates tokens of all nodes in the list. Doesn't include separators.
/// </summary>
internal static IEnumerable<SyntaxToken> GetDescendantTokensIgnoringSeparators<TSyntaxNode>(SeparatedSyntaxList<TSyntaxNode> list)
where TSyntaxNode : SyntaxNode
{
foreach (var node in list)
{
foreach (var token in node.DescendantTokens())
{
yield return token;
}
}
}
/// <summary>
/// Calculates the distance between two syntax nodes, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the nodes are.
/// </remarks>
public static double ComputeDistance(SyntaxNode? oldNode, SyntaxNode? newNode)
{
if (oldNode == null || newNode == null)
{
return (oldNode == newNode) ? 0.0 : 1.0;
}
return ComputeDistance(oldNode.DescendantTokens(), newNode.DescendantTokens());
}
/// <summary>
/// Calculates the distance between two syntax tokens, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the tokens are.
/// </remarks>
public static double ComputeDistance(SyntaxToken oldToken, SyntaxToken newToken)
=> LongestCommonSubstring.ComputeDistance(oldToken.Text, newToken.Text);
/// <summary>
/// Calculates the distance between two sequences of syntax tokens, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the sequences are.
/// </remarks>
public static double ComputeDistance(IEnumerable<SyntaxToken>? oldTokens, IEnumerable<SyntaxToken>? newTokens)
=> LcsTokens.Instance.ComputeDistance(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty());
/// <summary>
/// Calculates the distance between two sequences of syntax tokens, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the sequences are.
/// </remarks>
public static double ComputeDistance(ImmutableArray<SyntaxToken> oldTokens, ImmutableArray<SyntaxToken> newTokens)
=> LcsTokens.Instance.ComputeDistance(oldTokens.NullToEmpty(), newTokens.NullToEmpty());
/// <summary>
/// Calculates the distance between two sequences of syntax nodes, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the sequences are.
/// </remarks>
public static double ComputeDistance(IEnumerable<SyntaxNode>? oldNodes, IEnumerable<SyntaxNode>? newNodes)
=> LcsNodes.Instance.ComputeDistance(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty());
/// <summary>
/// Calculates the distance between two sequences of syntax tokens, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the sequences are.
/// </remarks>
public static double ComputeDistance(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes)
=> LcsNodes.Instance.ComputeDistance(oldNodes.NullToEmpty(), newNodes.NullToEmpty());
/// <summary>
/// Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia.
/// </summary>
public static IEnumerable<SequenceEdit> GetSequenceEdits(IEnumerable<SyntaxNode>? oldNodes, IEnumerable<SyntaxNode>? newNodes)
=> LcsNodes.Instance.GetEdits(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty());
/// <summary>
/// Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia.
/// </summary>
public static IEnumerable<SequenceEdit> GetSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes)
=> LcsNodes.Instance.GetEdits(oldNodes.NullToEmpty(), newNodes.NullToEmpty());
/// <summary>
/// Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia.
/// </summary>
public static IEnumerable<SequenceEdit> GetSequenceEdits(IEnumerable<SyntaxToken>? oldTokens, IEnumerable<SyntaxToken>? newTokens)
=> LcsTokens.Instance.GetEdits(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty());
/// <summary>
/// Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia.
/// </summary>
public static IEnumerable<SequenceEdit> GetSequenceEdits(ImmutableArray<SyntaxToken> oldTokens, ImmutableArray<SyntaxToken> newTokens)
=> LcsTokens.Instance.GetEdits(oldTokens.NullToEmpty(), newTokens.NullToEmpty());
private sealed class LcsTokens : LongestCommonImmutableArraySubsequence<SyntaxToken>
{
internal static readonly LcsTokens Instance = new LcsTokens();
protected override bool Equals(SyntaxToken oldElement, SyntaxToken newElement)
=> SyntaxFactory.AreEquivalent(oldElement, newElement);
}
private sealed class LcsNodes : LongestCommonImmutableArraySubsequence<SyntaxNode>
{
internal static readonly LcsNodes Instance = new LcsNodes();
protected override bool Equals(SyntaxNode oldElement, SyntaxNode newElement)
=> SyntaxFactory.AreEquivalent(oldElement, newElement);
}
#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.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Differencing;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue
{
internal sealed class SyntaxComparer : AbstractSyntaxComparer
{
internal static readonly SyntaxComparer TopLevel = new(null, null, null, null, compareStatementSyntax: false);
internal static readonly SyntaxComparer Statement = new(null, null, null, null, compareStatementSyntax: true);
/// <summary>
/// Creates a syntax comparer
/// </summary>
/// <param name="oldRoot">The root node to start comparisons from</param>
/// <param name="newRoot">The new root node to compare against</param>
/// <param name="oldRootChildren">Child nodes that should always be compared</param>
/// <param name="newRootChildren">New child nodes to compare against</param>
/// <param name="compareStatementSyntax">Whether this comparer is in "statement mode"</param>
public SyntaxComparer(
SyntaxNode? oldRoot,
SyntaxNode? newRoot,
IEnumerable<SyntaxNode>? oldRootChildren,
IEnumerable<SyntaxNode>? newRootChildren,
bool compareStatementSyntax)
: base(oldRoot, newRoot, oldRootChildren, newRootChildren, compareStatementSyntax)
{
}
protected override bool IsLambdaBodyStatementOrExpression(SyntaxNode node)
=> LambdaUtilities.IsLambdaBodyStatementOrExpression(node);
#region Labels
// Assumptions:
// - Each listed label corresponds to one or more syntax kinds.
// - Nodes with same labels might produce Update edits, nodes with different labels don't.
// - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label.
// (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label).
// - All descendants of a node whose kind is listed here will be ignored regardless of their labels
internal enum Label
{
// Top level syntax kinds
CompilationUnit,
GlobalStatement,
NamespaceDeclaration,
ExternAliasDirective, // tied to parent
UsingDirective, // tied to parent
TypeDeclaration,
EnumDeclaration,
DelegateDeclaration,
FieldDeclaration, // tied to parent
FieldVariableDeclaration, // tied to parent
FieldVariableDeclarator, // tied to parent
MethodDeclaration, // tied to parent
OperatorDeclaration, // tied to parent
ConversionOperatorDeclaration, // tied to parent
ConstructorDeclaration, // tied to parent
DestructorDeclaration, // tied to parent
PropertyDeclaration, // tied to parent
IndexerDeclaration, // tied to parent
EventDeclaration, // tied to parent
EnumMemberDeclaration, // tied to parent
AccessorList, // tied to parent
AccessorDeclaration, // tied to parent
// Statement syntax kinds
Block,
CheckedStatement,
UnsafeStatement,
TryStatement,
CatchClause, // tied to parent
CatchDeclaration, // tied to parent
CatchFilterClause, // tied to parent
FinallyClause, // tied to parent
ForStatement,
ForStatementPart, // tied to parent
ForEachStatement,
UsingStatement,
FixedStatement,
LockStatement,
WhileStatement,
DoStatement,
IfStatement,
ElseClause, // tied to parent
SwitchStatement,
SwitchSection,
CasePatternSwitchLabel, // tied to parent
SwitchExpression,
SwitchExpressionArm, // tied to parent
WhenClause, // tied to parent
YieldStatement, // tied to parent
GotoStatement,
GotoCaseStatement,
BreakContinueStatement,
ReturnThrowStatement,
ExpressionStatement,
LabeledStatement,
// TODO:
// Ideally we could declare LocalVariableDeclarator tied to the first enclosing node that defines local scope (block, foreach, etc.)
// Also consider handling LocalDeclarationStatement as just a bag of variable declarators,
// so that variable declarators contained in one can be matched with variable declarators contained in the other.
LocalDeclarationStatement, // tied to parent
LocalVariableDeclaration, // tied to parent
LocalVariableDeclarator, // tied to parent
SingleVariableDesignation,
AwaitExpression,
NestedFunction,
FromClause,
QueryBody,
FromClauseLambda, // tied to parent
LetClauseLambda, // tied to parent
WhereClauseLambda, // tied to parent
OrderByClause, // tied to parent
OrderingLambda, // tied to parent
SelectClauseLambda, // tied to parent
JoinClauseLambda, // tied to parent
JoinIntoClause, // tied to parent
GroupClauseLambda, // tied to parent
QueryContinuation, // tied to parent
// Syntax kinds that are common to both statement and top level
TypeParameterList, // tied to parent
TypeParameterConstraintClause, // tied to parent
TypeParameter, // tied to parent
ParameterList, // tied to parent
BracketedParameterList, // tied to parent
Parameter, // tied to parent
AttributeList, // tied to parent
Attribute, // tied to parent
// helpers:
Count,
Ignored = IgnoredNode
}
/// <summary>
/// Return 1 if it is desirable to report two edits (delete and insert) rather than a move edit
/// when the node changes its parent.
/// </summary>
private static int TiedToAncestor(Label label)
{
switch (label)
{
// Top level syntax
case Label.ExternAliasDirective:
case Label.UsingDirective:
case Label.FieldDeclaration:
case Label.FieldVariableDeclaration:
case Label.FieldVariableDeclarator:
case Label.MethodDeclaration:
case Label.OperatorDeclaration:
case Label.ConversionOperatorDeclaration:
case Label.ConstructorDeclaration:
case Label.DestructorDeclaration:
case Label.PropertyDeclaration:
case Label.IndexerDeclaration:
case Label.EventDeclaration:
case Label.EnumMemberDeclaration:
case Label.AccessorDeclaration:
case Label.AccessorList:
case Label.TypeParameterList:
case Label.TypeParameter:
case Label.TypeParameterConstraintClause:
case Label.ParameterList:
case Label.BracketedParameterList:
case Label.Parameter:
case Label.AttributeList:
case Label.Attribute:
return 1;
// Statement syntax
case Label.LocalDeclarationStatement:
case Label.LocalVariableDeclaration:
case Label.LocalVariableDeclarator:
case Label.GotoCaseStatement:
case Label.BreakContinueStatement:
case Label.ElseClause:
case Label.CatchClause:
case Label.CatchDeclaration:
case Label.CatchFilterClause:
case Label.FinallyClause:
case Label.ForStatementPart:
case Label.YieldStatement:
case Label.FromClauseLambda:
case Label.LetClauseLambda:
case Label.WhereClauseLambda:
case Label.OrderByClause:
case Label.OrderingLambda:
case Label.SelectClauseLambda:
case Label.JoinClauseLambda:
case Label.JoinIntoClause:
case Label.GroupClauseLambda:
case Label.QueryContinuation:
case Label.CasePatternSwitchLabel:
case Label.WhenClause:
case Label.SwitchExpressionArm:
return 1;
default:
return 0;
}
}
internal override int Classify(int kind, SyntaxNode? node, out bool isLeaf)
=> (int)Classify((SyntaxKind)kind, node, out isLeaf);
internal Label Classify(SyntaxKind kind, SyntaxNode? node, out bool isLeaf)
{
isLeaf = false;
// If the node is a for loop Initializer, Condition, or Incrementor expression we label it as "ForStatementPart".
// We need to capture it in the match since these expressions can be "active statements" and as such we need to map them.
//
// The parent is not available only when comparing nodes for value equality.
if (node != null && node.Parent.IsKind(SyntaxKind.ForStatement) && node is ExpressionSyntax)
{
return Label.ForStatementPart;
}
// ************************************
// Top and statement syntax
// ************************************
// These nodes can appear during top level and statement processing, so we put them in this first
// switch for simplicity. Statement specific, and top level specific cases are handled below.
switch (kind)
{
case SyntaxKind.CompilationUnit:
return Label.CompilationUnit;
case SyntaxKind.TypeParameterList:
return Label.TypeParameterList;
case SyntaxKind.TypeParameterConstraintClause:
return Label.TypeParameterConstraintClause;
case SyntaxKind.TypeParameter:
// not a leaf because an attribute may be applied
return Label.TypeParameter;
case SyntaxKind.BracketedParameterList:
return Label.BracketedParameterList;
case SyntaxKind.ParameterList:
return Label.ParameterList;
case SyntaxKind.Parameter:
return Label.Parameter;
case SyntaxKind.ConstructorDeclaration:
// Root when matching constructor bodies.
return Label.ConstructorDeclaration;
}
if (_compareStatementSyntax)
{
return ClassifyStatementSyntax(kind, node, out isLeaf);
}
return ClassifyTopSyntax(kind, node, out isLeaf);
}
private static Label ClassifyStatementSyntax(SyntaxKind kind, SyntaxNode? node, out bool isLeaf)
{
isLeaf = false;
// ************************************
// Statement syntax
// ************************************
// These nodes could potentially be seen as top level syntax, but we only want them labelled
// during statement syntax so they have to be kept separate.
//
// For example when top level sees something like this:
//
// private int X => new Func(() => { return 1 })();
//
// It needs to go through the entire lambda to know if that property def has changed
// but if we start labelling things, like ReturnStatement in the above example, then
// it will stop. Given that a block bodied lambda can have any statements a user likes
// the whole set has to be dealt with separately.
switch (kind)
{
// Notes:
// A descendant of a leaf node may be a labeled node that we don't want to visit if
// we are comparing its parent node (used for lambda bodies).
//
// Expressions are ignored but they may contain nodes that should be matched by tree comparer.
// (e.g. lambdas, declaration expressions). Descending to these nodes is handled in EnumerateChildren.
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
// These declarations can come after global statements so we want to stop statement matching
// because no global statements can come after them
isLeaf = true;
return Label.Ignored;
case SyntaxKind.LocalDeclarationStatement:
return Label.LocalDeclarationStatement;
case SyntaxKind.SingleVariableDesignation:
return Label.SingleVariableDesignation;
case SyntaxKind.LabeledStatement:
return Label.LabeledStatement;
case SyntaxKind.EmptyStatement:
isLeaf = true;
return Label.ExpressionStatement;
case SyntaxKind.GotoStatement:
isLeaf = true;
return Label.GotoStatement;
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.GotoDefaultStatement:
isLeaf = true;
return Label.GotoCaseStatement;
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
isLeaf = true;
return Label.BreakContinueStatement;
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
return Label.ReturnThrowStatement;
case SyntaxKind.ExpressionStatement:
return Label.ExpressionStatement;
case SyntaxKind.YieldBreakStatement:
case SyntaxKind.YieldReturnStatement:
return Label.YieldStatement;
case SyntaxKind.DoStatement:
return Label.DoStatement;
case SyntaxKind.WhileStatement:
return Label.WhileStatement;
case SyntaxKind.ForStatement:
return Label.ForStatement;
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.ForEachStatement:
return Label.ForEachStatement;
case SyntaxKind.UsingStatement:
return Label.UsingStatement;
case SyntaxKind.FixedStatement:
return Label.FixedStatement;
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return Label.CheckedStatement;
case SyntaxKind.UnsafeStatement:
return Label.UnsafeStatement;
case SyntaxKind.LockStatement:
return Label.LockStatement;
case SyntaxKind.IfStatement:
return Label.IfStatement;
case SyntaxKind.ElseClause:
return Label.ElseClause;
case SyntaxKind.SwitchStatement:
return Label.SwitchStatement;
case SyntaxKind.SwitchSection:
return Label.SwitchSection;
case SyntaxKind.CaseSwitchLabel:
case SyntaxKind.DefaultSwitchLabel:
// Switch labels are included in the "value" of the containing switch section.
// We don't need to analyze case expressions.
isLeaf = true;
return Label.Ignored;
case SyntaxKind.WhenClause:
return Label.WhenClause;
case SyntaxKind.CasePatternSwitchLabel:
return Label.CasePatternSwitchLabel;
case SyntaxKind.SwitchExpression:
return Label.SwitchExpression;
case SyntaxKind.SwitchExpressionArm:
return Label.SwitchExpressionArm;
case SyntaxKind.TryStatement:
return Label.TryStatement;
case SyntaxKind.CatchClause:
return Label.CatchClause;
case SyntaxKind.CatchDeclaration:
// the declarator of the exception variable
return Label.CatchDeclaration;
case SyntaxKind.CatchFilterClause:
return Label.CatchFilterClause;
case SyntaxKind.FinallyClause:
return Label.FinallyClause;
case SyntaxKind.FromClause:
// The first from clause of a query is not a lambda.
// We have to assign it a label different from "FromClauseLambda"
// so that we won't match lambda-from to non-lambda-from.
//
// Since FromClause declares range variables we need to include it in the map,
// so that we are able to map range variable declarations.
// Therefore we assign it a dedicated label.
//
// The parent is not available only when comparing nodes for value equality.
// In that case it doesn't matter what label the node has as long as it has some.
if (node == null || node.Parent.IsKind(SyntaxKind.QueryExpression))
{
return Label.FromClause;
}
return Label.FromClauseLambda;
case SyntaxKind.QueryBody:
return Label.QueryBody;
case SyntaxKind.QueryContinuation:
return Label.QueryContinuation;
case SyntaxKind.LetClause:
return Label.LetClauseLambda;
case SyntaxKind.WhereClause:
return Label.WhereClauseLambda;
case SyntaxKind.OrderByClause:
return Label.OrderByClause;
case SyntaxKind.AscendingOrdering:
case SyntaxKind.DescendingOrdering:
return Label.OrderingLambda;
case SyntaxKind.SelectClause:
return Label.SelectClauseLambda;
case SyntaxKind.JoinClause:
return Label.JoinClauseLambda;
case SyntaxKind.JoinIntoClause:
return Label.JoinIntoClause;
case SyntaxKind.GroupClause:
return Label.GroupClauseLambda;
case SyntaxKind.IdentifierName:
case SyntaxKind.QualifiedName:
case SyntaxKind.GenericName:
case SyntaxKind.TypeArgumentList:
case SyntaxKind.AliasQualifiedName:
case SyntaxKind.PredefinedType:
case SyntaxKind.PointerType:
case SyntaxKind.NullableType:
case SyntaxKind.TupleType:
case SyntaxKind.RefType:
case SyntaxKind.OmittedTypeArgument:
case SyntaxKind.NameColon:
case SyntaxKind.OmittedArraySizeExpression:
case SyntaxKind.ThisExpression:
case SyntaxKind.BaseExpression:
case SyntaxKind.ArgListExpression:
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
case SyntaxKind.TypeOfExpression:
case SyntaxKind.SizeOfExpression:
case SyntaxKind.DefaultExpression:
case SyntaxKind.ConstantPattern:
case SyntaxKind.DiscardDesignation:
// can't contain a lambda/await/anonymous type:
isLeaf = true;
return Label.Ignored;
case SyntaxKind.AwaitExpression:
return Label.AwaitExpression;
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.LocalFunctionStatement:
return Label.NestedFunction;
case SyntaxKind.VariableDeclaration:
return Label.LocalVariableDeclaration;
case SyntaxKind.VariableDeclarator:
return Label.LocalVariableDeclarator;
case SyntaxKind.Block:
return Label.Block;
}
// If we got this far, its an unlabelled node. Since just about any node can
// contain a lambda, isLeaf must be false for statement syntax.
return Label.Ignored;
}
private static Label ClassifyTopSyntax(SyntaxKind kind, SyntaxNode? node, out bool isLeaf)
{
isLeaf = false;
// ************************************
// Top syntax
// ************************************
// More the most part these nodes will only appear in top syntax but its easier to
// keep them separate so we can more easily discern was is shared, above.
switch (kind)
{
case SyntaxKind.GlobalStatement:
isLeaf = true;
return Label.GlobalStatement;
case SyntaxKind.ExternAliasDirective:
isLeaf = true;
return Label.ExternAliasDirective;
case SyntaxKind.UsingDirective:
isLeaf = true;
return Label.UsingDirective;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return Label.NamespaceDeclaration;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return Label.TypeDeclaration;
case SyntaxKind.MethodDeclaration:
return Label.MethodDeclaration;
case SyntaxKind.EnumDeclaration:
return Label.EnumDeclaration;
case SyntaxKind.DelegateDeclaration:
return Label.DelegateDeclaration;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
return Label.FieldDeclaration;
case SyntaxKind.ConversionOperatorDeclaration:
return Label.ConversionOperatorDeclaration;
case SyntaxKind.OperatorDeclaration:
return Label.OperatorDeclaration;
case SyntaxKind.DestructorDeclaration:
isLeaf = true;
return Label.DestructorDeclaration;
case SyntaxKind.PropertyDeclaration:
return Label.PropertyDeclaration;
case SyntaxKind.IndexerDeclaration:
return Label.IndexerDeclaration;
case SyntaxKind.EventDeclaration:
return Label.EventDeclaration;
case SyntaxKind.EnumMemberDeclaration:
// not a leaf because an attribute may be applied
return Label.EnumMemberDeclaration;
case SyntaxKind.AccessorList:
return Label.AccessorList;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
isLeaf = true;
return Label.AccessorDeclaration;
// Note: These last two do actually appear as statement syntax, but mean something
// different and hence have a different label
case SyntaxKind.VariableDeclaration:
return Label.FieldVariableDeclaration;
case SyntaxKind.VariableDeclarator:
// For top syntax, a variable declarator is a leaf node
isLeaf = true;
return Label.FieldVariableDeclarator;
case SyntaxKind.AttributeList:
// Only module/assembly attributes are labelled
if (node is not null && node.IsParentKind(SyntaxKind.CompilationUnit))
{
return Label.AttributeList;
}
break;
case SyntaxKind.Attribute:
// Only module/assembly attributes are labelled
if (node is { Parent: { } parent } && parent.IsParentKind(SyntaxKind.CompilationUnit))
{
isLeaf = true;
return Label.Attribute;
}
break;
}
// If we got this far, its an unlabelled node. For top
// syntax, we don't need to descend into any ignored nodes
isLeaf = true;
return Label.Ignored;
}
// internal for testing
internal bool HasLabel(SyntaxKind kind)
=> Classify(kind, node: null, out _) != Label.Ignored;
protected internal override int LabelCount
=> (int)Label.Count;
protected internal override int TiedToAncestor(int label)
=> TiedToAncestor((Label)label);
#endregion
#region Comparisons
public override bool ValuesEqual(SyntaxNode left, SyntaxNode right)
{
Func<SyntaxKind, bool>? ignoreChildFunction;
switch (left.Kind())
{
// all syntax kinds with a method body child:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
// When comparing method bodies we need to NOT ignore VariableDeclaration and VariableDeclarator children,
// but when comparing field definitions we should ignore VariableDeclarations children.
var leftBody = GetBody(left);
var rightBody = GetBody(right);
if (!SyntaxFactory.AreEquivalent(leftBody, rightBody, null))
{
return false;
}
ignoreChildFunction = childKind => childKind == SyntaxKind.Block || childKind == SyntaxKind.ArrowExpressionClause || HasLabel(childKind);
break;
case SyntaxKind.SwitchSection:
return Equal((SwitchSectionSyntax)left, (SwitchSectionSyntax)right);
case SyntaxKind.ForStatement:
// The only children of ForStatement are labeled nodes and punctuation.
return true;
default:
if (HasChildren(left))
{
ignoreChildFunction = childKind => HasLabel(childKind);
}
else
{
ignoreChildFunction = null;
}
break;
}
return SyntaxFactory.AreEquivalent(left, right, ignoreChildFunction);
}
private bool Equal(SwitchSectionSyntax left, SwitchSectionSyntax right)
{
return SyntaxFactory.AreEquivalent(left.Labels, right.Labels, null)
&& SyntaxFactory.AreEquivalent(left.Statements, right.Statements, ignoreChildNode: HasLabel);
}
private static SyntaxNode? GetBody(SyntaxNode node)
{
switch (node)
{
case BaseMethodDeclarationSyntax baseMethodDeclarationSyntax: return baseMethodDeclarationSyntax.Body ?? (SyntaxNode?)baseMethodDeclarationSyntax.ExpressionBody?.Expression;
case AccessorDeclarationSyntax accessorDeclarationSyntax: return accessorDeclarationSyntax.Body ?? (SyntaxNode?)accessorDeclarationSyntax.ExpressionBody?.Expression;
default: throw ExceptionUtilities.UnexpectedValue(node);
}
}
protected override bool TryComputeWeightedDistance(SyntaxNode leftNode, SyntaxNode rightNode, out double distance)
{
switch (leftNode.Kind())
{
case SyntaxKind.VariableDeclarator:
distance = ComputeDistance(
((VariableDeclaratorSyntax)leftNode).Identifier,
((VariableDeclaratorSyntax)rightNode).Identifier);
return true;
case SyntaxKind.ForStatement:
var leftFor = (ForStatementSyntax)leftNode;
var rightFor = (ForStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftFor, rightFor);
return true;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
{
var leftForEach = (CommonForEachStatementSyntax)leftNode;
var rightForEach = (CommonForEachStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftForEach, rightForEach);
return true;
}
case SyntaxKind.UsingStatement:
var leftUsing = (UsingStatementSyntax)leftNode;
var rightUsing = (UsingStatementSyntax)rightNode;
if (leftUsing.Declaration != null && rightUsing.Declaration != null)
{
distance = ComputeWeightedDistance(
leftUsing.Declaration,
leftUsing.Statement,
rightUsing.Declaration,
rightUsing.Statement);
}
else
{
distance = ComputeWeightedDistance(
(SyntaxNode?)leftUsing.Expression ?? leftUsing.Declaration!,
leftUsing.Statement,
(SyntaxNode?)rightUsing.Expression ?? rightUsing.Declaration!,
rightUsing.Statement);
}
return true;
case SyntaxKind.LockStatement:
var leftLock = (LockStatementSyntax)leftNode;
var rightLock = (LockStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftLock.Expression, leftLock.Statement, rightLock.Expression, rightLock.Statement);
return true;
case SyntaxKind.FixedStatement:
var leftFixed = (FixedStatementSyntax)leftNode;
var rightFixed = (FixedStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftFixed.Declaration, leftFixed.Statement, rightFixed.Declaration, rightFixed.Statement);
return true;
case SyntaxKind.WhileStatement:
var leftWhile = (WhileStatementSyntax)leftNode;
var rightWhile = (WhileStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftWhile.Condition, leftWhile.Statement, rightWhile.Condition, rightWhile.Statement);
return true;
case SyntaxKind.DoStatement:
var leftDo = (DoStatementSyntax)leftNode;
var rightDo = (DoStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftDo.Condition, leftDo.Statement, rightDo.Condition, rightDo.Statement);
return true;
case SyntaxKind.IfStatement:
var leftIf = (IfStatementSyntax)leftNode;
var rightIf = (IfStatementSyntax)rightNode;
distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statement, rightIf.Condition, rightIf.Statement);
return true;
case SyntaxKind.Block:
var leftBlock = (BlockSyntax)leftNode;
var rightBlock = (BlockSyntax)rightNode;
return TryComputeWeightedDistance(leftBlock, rightBlock, out distance);
case SyntaxKind.CatchClause:
distance = ComputeWeightedDistance((CatchClauseSyntax)leftNode, (CatchClauseSyntax)rightNode);
return true;
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.LocalFunctionStatement:
distance = ComputeWeightedDistanceOfNestedFunctions(leftNode, rightNode);
return true;
case SyntaxKind.YieldBreakStatement:
case SyntaxKind.YieldReturnStatement:
// Ignore the expression of yield return. The structure of the state machine is more important than the yielded values.
distance = (leftNode.RawKind == rightNode.RawKind) ? 0.0 : 0.1;
return true;
case SyntaxKind.SingleVariableDesignation:
distance = ComputeWeightedDistance((SingleVariableDesignationSyntax)leftNode, (SingleVariableDesignationSyntax)rightNode);
return true;
case SyntaxKind.TypeParameterConstraintClause:
distance = ComputeDistance((TypeParameterConstraintClauseSyntax)leftNode, (TypeParameterConstraintClauseSyntax)rightNode);
return true;
case SyntaxKind.TypeParameter:
distance = ComputeDistance((TypeParameterSyntax)leftNode, (TypeParameterSyntax)rightNode);
return true;
case SyntaxKind.Parameter:
distance = ComputeDistance((ParameterSyntax)leftNode, (ParameterSyntax)rightNode);
return true;
case SyntaxKind.AttributeList:
distance = ComputeDistance((AttributeListSyntax)leftNode, (AttributeListSyntax)rightNode);
return true;
case SyntaxKind.Attribute:
distance = ComputeDistance((AttributeSyntax)leftNode, (AttributeSyntax)rightNode);
return true;
default:
var leftName = TryGetName(leftNode);
var rightName = TryGetName(rightNode);
Contract.ThrowIfFalse(rightName.HasValue == leftName.HasValue);
if (leftName.HasValue)
{
distance = ComputeDistance(leftName.Value, rightName!.Value);
return true;
}
else
{
distance = 0;
return false;
}
}
}
private static double ComputeWeightedDistanceOfNestedFunctions(SyntaxNode leftNode, SyntaxNode rightNode)
{
GetNestedFunctionsParts(leftNode, out var leftParameters, out var leftAsync, out var leftBody, out var leftModifiers, out var leftReturnType, out var leftIdentifier, out var leftTypeParameters);
GetNestedFunctionsParts(rightNode, out var rightParameters, out var rightAsync, out var rightBody, out var rightModifiers, out var rightReturnType, out var rightIdentifier, out var rightTypeParameters);
if ((leftAsync.Kind() == SyntaxKind.AsyncKeyword) != (rightAsync.Kind() == SyntaxKind.AsyncKeyword))
{
return 1.0;
}
var modifierDistance = ComputeDistance(leftModifiers, rightModifiers);
var returnTypeDistance = ComputeDistance(leftReturnType, rightReturnType);
var identifierDistance = ComputeDistance(leftIdentifier, rightIdentifier);
var typeParameterDistance = ComputeDistance(leftTypeParameters, rightTypeParameters);
var parameterDistance = ComputeDistance(leftParameters, rightParameters);
var bodyDistance = ComputeDistance(leftBody, rightBody);
return
modifierDistance * 0.1 +
returnTypeDistance * 0.1 +
identifierDistance * 0.2 +
typeParameterDistance * 0.2 +
parameterDistance * 0.2 +
bodyDistance * 0.2;
}
private static void GetNestedFunctionsParts(
SyntaxNode nestedFunction,
out IEnumerable<SyntaxToken> parameters,
out SyntaxToken asyncKeyword,
out SyntaxNode body,
out SyntaxTokenList modifiers,
out TypeSyntax? returnType,
out SyntaxToken identifier,
out TypeParameterListSyntax? typeParameters)
{
switch (nestedFunction.Kind())
{
case SyntaxKind.SimpleLambdaExpression:
var simple = (SimpleLambdaExpressionSyntax)nestedFunction;
parameters = simple.Parameter.DescendantTokens();
asyncKeyword = simple.AsyncKeyword;
body = simple.Body;
modifiers = default;
returnType = null;
identifier = default;
typeParameters = null;
break;
case SyntaxKind.ParenthesizedLambdaExpression:
var parenthesized = (ParenthesizedLambdaExpressionSyntax)nestedFunction;
parameters = GetDescendantTokensIgnoringSeparators(parenthesized.ParameterList.Parameters);
asyncKeyword = parenthesized.AsyncKeyword;
body = parenthesized.Body;
modifiers = default;
returnType = null;
identifier = default;
typeParameters = null;
break;
case SyntaxKind.AnonymousMethodExpression:
var anonymous = (AnonymousMethodExpressionSyntax)nestedFunction;
if (anonymous.ParameterList != null)
{
parameters = GetDescendantTokensIgnoringSeparators(anonymous.ParameterList.Parameters);
}
else
{
parameters = SpecializedCollections.EmptyEnumerable<SyntaxToken>();
}
asyncKeyword = anonymous.AsyncKeyword;
body = anonymous.Block;
modifiers = default;
returnType = null;
identifier = default;
typeParameters = null;
break;
case SyntaxKind.LocalFunctionStatement:
var localFunction = (LocalFunctionStatementSyntax)nestedFunction;
parameters = GetDescendantTokensIgnoringSeparators(localFunction.ParameterList.Parameters);
asyncKeyword = default;
body = (SyntaxNode?)localFunction.Body ?? localFunction.ExpressionBody!;
modifiers = localFunction.Modifiers;
returnType = localFunction.ReturnType;
identifier = localFunction.Identifier;
typeParameters = localFunction.TypeParameterList;
break;
default:
throw ExceptionUtilities.UnexpectedValue(nestedFunction.Kind());
}
}
private bool TryComputeWeightedDistance(BlockSyntax leftBlock, BlockSyntax rightBlock, out double distance)
{
// No block can be matched with the root block.
// Note that in constructors the root is the constructor declaration, since we need to include
// the constructor initializer in the match.
if (leftBlock.Parent == null ||
rightBlock.Parent == null ||
leftBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration) ||
rightBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration))
{
distance = 0.0;
return true;
}
if (GetLabel(leftBlock.Parent) != GetLabel(rightBlock.Parent))
{
distance = 0.2 + 0.8 * ComputeWeightedBlockDistance(leftBlock, rightBlock);
return true;
}
switch (leftBlock.Parent.Kind())
{
case SyntaxKind.IfStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.FixedStatement:
case SyntaxKind.LockStatement:
case SyntaxKind.UsingStatement:
case SyntaxKind.SwitchSection:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.LocalFunctionStatement:
// value distance of the block body is included:
distance = GetDistance(leftBlock.Parent, rightBlock.Parent);
return true;
case SyntaxKind.CatchClause:
var leftCatch = (CatchClauseSyntax)leftBlock.Parent;
var rightCatch = (CatchClauseSyntax)rightBlock.Parent;
if (leftCatch.Declaration == null && leftCatch.Filter == null &&
rightCatch.Declaration == null && rightCatch.Filter == null)
{
var leftTry = (TryStatementSyntax)leftCatch.Parent!;
var rightTry = (TryStatementSyntax)rightCatch.Parent!;
distance = 0.5 * ComputeValueDistance(leftTry.Block, rightTry.Block) +
0.5 * ComputeValueDistance(leftBlock, rightBlock);
}
else
{
// value distance of the block body is included:
distance = GetDistance(leftBlock.Parent, rightBlock.Parent);
}
return true;
case SyntaxKind.Block:
case SyntaxKind.LabeledStatement:
distance = ComputeWeightedBlockDistance(leftBlock, rightBlock);
return true;
case SyntaxKind.UnsafeStatement:
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
case SyntaxKind.ElseClause:
case SyntaxKind.FinallyClause:
case SyntaxKind.TryStatement:
distance = 0.2 * ComputeValueDistance(leftBlock, rightBlock);
return true;
default:
throw ExceptionUtilities.UnexpectedValue(leftBlock.Parent.Kind());
}
}
private double ComputeWeightedDistance(SingleVariableDesignationSyntax leftNode, SingleVariableDesignationSyntax rightNode)
{
var distance = ComputeDistance(leftNode, rightNode);
double parentDistance;
if (leftNode.Parent != null &&
rightNode.Parent != null &&
GetLabel(leftNode.Parent) == GetLabel(rightNode.Parent))
{
parentDistance = ComputeDistance(leftNode.Parent, rightNode.Parent);
}
else
{
parentDistance = 1;
}
return 0.5 * parentDistance + 0.5 * distance;
}
private static double ComputeWeightedBlockDistance(BlockSyntax leftBlock, BlockSyntax rightBlock)
{
if (TryComputeLocalsDistance(leftBlock, rightBlock, out var distance))
{
return distance;
}
return ComputeValueDistance(leftBlock, rightBlock);
}
private static double ComputeWeightedDistance(CatchClauseSyntax left, CatchClauseSyntax right)
{
var blockDistance = ComputeDistance(left.Block, right.Block);
var distance = CombineOptional(blockDistance, left.Declaration, right.Declaration, left.Filter, right.Filter);
return AdjustForLocalsInBlock(distance, left.Block, right.Block, localsWeight: 0.3);
}
private static double ComputeWeightedDistance(
CommonForEachStatementSyntax leftCommonForEach,
CommonForEachStatementSyntax rightCommonForEach)
{
var statementDistance = ComputeDistance(leftCommonForEach.Statement, rightCommonForEach.Statement);
var expressionDistance = ComputeDistance(leftCommonForEach.Expression, rightCommonForEach.Expression);
List<SyntaxToken>? leftLocals = null;
List<SyntaxToken>? rightLocals = null;
GetLocalNames(leftCommonForEach, ref leftLocals);
GetLocalNames(rightCommonForEach, ref rightLocals);
var localNamesDistance = ComputeDistance(leftLocals, rightLocals);
var distance = localNamesDistance * 0.6 + expressionDistance * 0.2 + statementDistance * 0.2;
return AdjustForLocalsInBlock(distance, leftCommonForEach.Statement, rightCommonForEach.Statement, localsWeight: 0.6);
}
private static double ComputeWeightedDistance(ForStatementSyntax left, ForStatementSyntax right)
{
var statementDistance = ComputeDistance(left.Statement, right.Statement);
var conditionDistance = ComputeDistance(left.Condition, right.Condition);
var incDistance = ComputeDistance(
GetDescendantTokensIgnoringSeparators(left.Incrementors), GetDescendantTokensIgnoringSeparators(right.Incrementors));
var distance = conditionDistance * 0.3 + incDistance * 0.3 + statementDistance * 0.4;
if (TryComputeLocalsDistance(left.Declaration, right.Declaration, out var localsDistance))
{
distance = distance * 0.4 + localsDistance * 0.6;
}
return distance;
}
private static double ComputeWeightedDistance(
VariableDeclarationSyntax leftVariables,
StatementSyntax leftStatement,
VariableDeclarationSyntax rightVariables,
StatementSyntax rightStatement)
{
var distance = ComputeDistance(leftStatement, rightStatement);
// Put maximum weight behind the variables declared in the header of the statement.
if (TryComputeLocalsDistance(leftVariables, rightVariables, out var localsDistance))
{
distance = distance * 0.4 + localsDistance * 0.6;
}
// If the statement is a block that declares local variables,
// weight them more than the rest of the statement.
return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.2);
}
private static double ComputeWeightedDistance(
SyntaxNode? leftHeader,
StatementSyntax leftStatement,
SyntaxNode? rightHeader,
StatementSyntax rightStatement)
{
var headerDistance = ComputeDistance(leftHeader, rightHeader);
var statementDistance = ComputeDistance(leftStatement, rightStatement);
var distance = headerDistance * 0.6 + statementDistance * 0.4;
return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.5);
}
private static double AdjustForLocalsInBlock(
double distance,
StatementSyntax leftStatement,
StatementSyntax rightStatement,
double localsWeight)
{
// If the statement is a block that declares local variables,
// weight them more than the rest of the statement.
if (leftStatement.Kind() == SyntaxKind.Block && rightStatement.Kind() == SyntaxKind.Block)
{
if (TryComputeLocalsDistance((BlockSyntax)leftStatement, (BlockSyntax)rightStatement, out var localsDistance))
{
return localsDistance * localsWeight + distance * (1 - localsWeight);
}
}
return distance;
}
private static bool TryComputeLocalsDistance(VariableDeclarationSyntax? left, VariableDeclarationSyntax? right, out double distance)
{
List<SyntaxToken>? leftLocals = null;
List<SyntaxToken>? rightLocals = null;
if (left != null)
{
GetLocalNames(left, ref leftLocals);
}
if (right != null)
{
GetLocalNames(right, ref rightLocals);
}
if (leftLocals == null || rightLocals == null)
{
distance = 0;
return false;
}
distance = ComputeDistance(leftLocals, rightLocals);
return true;
}
private static bool TryComputeLocalsDistance(BlockSyntax left, BlockSyntax right, out double distance)
{
List<SyntaxToken>? leftLocals = null;
List<SyntaxToken>? rightLocals = null;
GetLocalNames(left, ref leftLocals);
GetLocalNames(right, ref rightLocals);
if (leftLocals == null || rightLocals == null)
{
distance = 0;
return false;
}
distance = ComputeDistance(leftLocals, rightLocals);
return true;
}
// Doesn't include variables declared in declaration expressions
// Consider including them (https://github.com/dotnet/roslyn/issues/37460).
private static void GetLocalNames(BlockSyntax block, ref List<SyntaxToken>? result)
{
foreach (var child in block.ChildNodes())
{
if (child.IsKind(SyntaxKind.LocalDeclarationStatement, out LocalDeclarationStatementSyntax? localDecl))
{
GetLocalNames(localDecl.Declaration, ref result);
}
}
}
// Doesn't include variables declared in declaration expressions
// Consider including them (https://github.com/dotnet/roslyn/issues/37460).
private static void GetLocalNames(VariableDeclarationSyntax localDeclaration, ref List<SyntaxToken>? result)
{
foreach (var local in localDeclaration.Variables)
{
GetLocalNames(local.Identifier, ref result);
}
}
internal static void GetLocalNames(CommonForEachStatementSyntax commonForEach, ref List<SyntaxToken>? result)
{
switch (commonForEach.Kind())
{
case SyntaxKind.ForEachStatement:
GetLocalNames(((ForEachStatementSyntax)commonForEach).Identifier, ref result);
return;
case SyntaxKind.ForEachVariableStatement:
var forEachVariable = (ForEachVariableStatementSyntax)commonForEach;
GetLocalNames(forEachVariable.Variable, ref result);
return;
default:
throw ExceptionUtilities.UnexpectedValue(commonForEach.Kind());
}
}
private static void GetLocalNames(ExpressionSyntax expression, ref List<SyntaxToken>? result)
{
switch (expression.Kind())
{
case SyntaxKind.DeclarationExpression:
var declarationExpression = (DeclarationExpressionSyntax)expression;
var localDeclaration = declarationExpression.Designation;
GetLocalNames(localDeclaration, ref result);
return;
case SyntaxKind.TupleExpression:
var tupleExpression = (TupleExpressionSyntax)expression;
foreach (var argument in tupleExpression.Arguments)
{
GetLocalNames(argument.Expression, ref result);
}
return;
default:
// Do nothing for node that cannot have variable declarations inside.
return;
}
}
private static void GetLocalNames(VariableDesignationSyntax designation, ref List<SyntaxToken>? result)
{
switch (designation.Kind())
{
case SyntaxKind.SingleVariableDesignation:
GetLocalNames(((SingleVariableDesignationSyntax)designation).Identifier, ref result);
return;
case SyntaxKind.ParenthesizedVariableDesignation:
var parenthesizedVariableDesignation = (ParenthesizedVariableDesignationSyntax)designation;
foreach (var variableDesignation in parenthesizedVariableDesignation.Variables)
{
GetLocalNames(variableDesignation, ref result);
}
return;
case SyntaxKind.DiscardDesignation:
return;
default:
throw ExceptionUtilities.UnexpectedValue(designation.Kind());
}
}
private static void GetLocalNames(SyntaxToken syntaxToken, [NotNull] ref List<SyntaxToken>? result)
{
result ??= new List<SyntaxToken>();
result.Add(syntaxToken);
}
private static double CombineOptional(
double distance0,
SyntaxNode? left1,
SyntaxNode? right1,
SyntaxNode? left2,
SyntaxNode? right2,
double weight0 = 0.8,
double weight1 = 0.5)
{
var one = left1 != null || right1 != null;
var two = left2 != null || right2 != null;
if (!one && !two)
{
return distance0;
}
var distance1 = ComputeDistance(left1, right1);
var distance2 = ComputeDistance(left2, right2);
double d;
if (one && two)
{
d = distance1 * weight1 + distance2 * (1 - weight1);
}
else if (one)
{
d = distance1;
}
else
{
d = distance2;
}
return distance0 * weight0 + d * (1 - weight0);
}
private static SyntaxNodeOrToken? TryGetName(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ExternAliasDirective:
return ((ExternAliasDirectiveSyntax)node).Identifier;
case SyntaxKind.UsingDirective:
return ((UsingDirectiveSyntax)node).Name;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return ((BaseNamespaceDeclarationSyntax)node).Name;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return ((TypeDeclarationSyntax)node).Identifier;
case SyntaxKind.EnumDeclaration:
return ((EnumDeclarationSyntax)node).Identifier;
case SyntaxKind.DelegateDeclaration:
return ((DelegateDeclarationSyntax)node).Identifier;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.VariableDeclaration:
return null;
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)node).Identifier;
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)node).Identifier;
case SyntaxKind.ConversionOperatorDeclaration:
return ((ConversionOperatorDeclarationSyntax)node).Type;
case SyntaxKind.OperatorDeclaration:
return ((OperatorDeclarationSyntax)node).OperatorToken;
case SyntaxKind.ConstructorDeclaration:
return ((ConstructorDeclarationSyntax)node).Identifier;
case SyntaxKind.DestructorDeclaration:
return ((DestructorDeclarationSyntax)node).Identifier;
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)node).Identifier;
case SyntaxKind.IndexerDeclaration:
return null;
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)node).Identifier;
case SyntaxKind.EnumMemberDeclaration:
return ((EnumMemberDeclarationSyntax)node).Identifier;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
return null;
case SyntaxKind.TypeParameterConstraintClause:
return ((TypeParameterConstraintClauseSyntax)node).Name.Identifier;
case SyntaxKind.TypeParameter:
return ((TypeParameterSyntax)node).Identifier;
case SyntaxKind.TypeParameterList:
case SyntaxKind.ParameterList:
case SyntaxKind.BracketedParameterList:
return null;
case SyntaxKind.Parameter:
return ((ParameterSyntax)node).Identifier;
case SyntaxKind.AttributeList:
return ((AttributeListSyntax)node).Target;
case SyntaxKind.Attribute:
return ((AttributeSyntax)node).Name;
default:
return null;
}
}
public sealed override double GetDistance(SyntaxNode oldNode, SyntaxNode newNode)
{
Debug.Assert(GetLabel(oldNode) == GetLabel(newNode) && GetLabel(oldNode) != IgnoredNode);
if (oldNode == newNode)
{
return ExactMatchDist;
}
if (TryComputeWeightedDistance(oldNode, newNode, out var weightedDistance))
{
if (weightedDistance == ExactMatchDist && !SyntaxFactory.AreEquivalent(oldNode, newNode))
{
weightedDistance = EpsilonDist;
}
return weightedDistance;
}
return ComputeValueDistance(oldNode, newNode);
}
internal static double ComputeValueDistance(SyntaxNode? oldNode, SyntaxNode? newNode)
{
if (SyntaxFactory.AreEquivalent(oldNode, newNode))
{
return ExactMatchDist;
}
var distance = ComputeDistance(oldNode, newNode);
// We don't want to return an exact match, because there
// must be something different, since we got here
return (distance == ExactMatchDist) ? EpsilonDist : distance;
}
internal static double ComputeDistance(SyntaxNodeOrToken oldNodeOrToken, SyntaxNodeOrToken newNodeOrToken)
{
Debug.Assert(newNodeOrToken.IsToken == oldNodeOrToken.IsToken);
double distance;
if (oldNodeOrToken.IsToken)
{
var leftToken = oldNodeOrToken.AsToken();
var rightToken = newNodeOrToken.AsToken();
distance = ComputeDistance(leftToken, rightToken);
Debug.Assert(!SyntaxFactory.AreEquivalent(leftToken, rightToken) || distance == ExactMatchDist);
}
else
{
var leftNode = oldNodeOrToken.AsNode();
var rightNode = newNodeOrToken.AsNode();
distance = ComputeDistance(leftNode, rightNode);
Debug.Assert(!SyntaxFactory.AreEquivalent(leftNode, rightNode) || distance == ExactMatchDist);
}
return distance;
}
/// <summary>
/// Enumerates tokens of all nodes in the list. Doesn't include separators.
/// </summary>
internal static IEnumerable<SyntaxToken> GetDescendantTokensIgnoringSeparators<TSyntaxNode>(SeparatedSyntaxList<TSyntaxNode> list)
where TSyntaxNode : SyntaxNode
{
foreach (var node in list)
{
foreach (var token in node.DescendantTokens())
{
yield return token;
}
}
}
/// <summary>
/// Calculates the distance between two syntax nodes, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the nodes are.
/// </remarks>
public static double ComputeDistance(SyntaxNode? oldNode, SyntaxNode? newNode)
{
if (oldNode == null || newNode == null)
{
return (oldNode == newNode) ? 0.0 : 1.0;
}
return ComputeDistance(oldNode.DescendantTokens(), newNode.DescendantTokens());
}
/// <summary>
/// Calculates the distance between two syntax tokens, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the tokens are.
/// </remarks>
public static double ComputeDistance(SyntaxToken oldToken, SyntaxToken newToken)
=> LongestCommonSubstring.ComputeDistance(oldToken.Text, newToken.Text);
/// <summary>
/// Calculates the distance between two sequences of syntax tokens, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the sequences are.
/// </remarks>
public static double ComputeDistance(IEnumerable<SyntaxToken>? oldTokens, IEnumerable<SyntaxToken>? newTokens)
=> LcsTokens.Instance.ComputeDistance(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty());
/// <summary>
/// Calculates the distance between two sequences of syntax tokens, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the sequences are.
/// </remarks>
public static double ComputeDistance(ImmutableArray<SyntaxToken> oldTokens, ImmutableArray<SyntaxToken> newTokens)
=> LcsTokens.Instance.ComputeDistance(oldTokens.NullToEmpty(), newTokens.NullToEmpty());
/// <summary>
/// Calculates the distance between two sequences of syntax nodes, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the sequences are.
/// </remarks>
public static double ComputeDistance(IEnumerable<SyntaxNode>? oldNodes, IEnumerable<SyntaxNode>? newNodes)
=> LcsNodes.Instance.ComputeDistance(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty());
/// <summary>
/// Calculates the distance between two sequences of syntax tokens, disregarding trivia.
/// </summary>
/// <remarks>
/// Distance is a number within [0, 1], the smaller the more similar the sequences are.
/// </remarks>
public static double ComputeDistance(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes)
=> LcsNodes.Instance.ComputeDistance(oldNodes.NullToEmpty(), newNodes.NullToEmpty());
/// <summary>
/// Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia.
/// </summary>
public static IEnumerable<SequenceEdit> GetSequenceEdits(IEnumerable<SyntaxNode>? oldNodes, IEnumerable<SyntaxNode>? newNodes)
=> LcsNodes.Instance.GetEdits(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty());
/// <summary>
/// Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia.
/// </summary>
public static IEnumerable<SequenceEdit> GetSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes)
=> LcsNodes.Instance.GetEdits(oldNodes.NullToEmpty(), newNodes.NullToEmpty());
/// <summary>
/// Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia.
/// </summary>
public static IEnumerable<SequenceEdit> GetSequenceEdits(IEnumerable<SyntaxToken>? oldTokens, IEnumerable<SyntaxToken>? newTokens)
=> LcsTokens.Instance.GetEdits(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty());
/// <summary>
/// Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia.
/// </summary>
public static IEnumerable<SequenceEdit> GetSequenceEdits(ImmutableArray<SyntaxToken> oldTokens, ImmutableArray<SyntaxToken> newTokens)
=> LcsTokens.Instance.GetEdits(oldTokens.NullToEmpty(), newTokens.NullToEmpty());
private sealed class LcsTokens : LongestCommonImmutableArraySubsequence<SyntaxToken>
{
internal static readonly LcsTokens Instance = new LcsTokens();
protected override bool Equals(SyntaxToken oldElement, SyntaxToken newElement)
=> SyntaxFactory.AreEquivalent(oldElement, newElement);
}
private sealed class LcsNodes : LongestCommonImmutableArraySubsequence<SyntaxNode>
{
internal static readonly LcsNodes Instance = new LcsNodes();
protected override bool Equals(SyntaxNode oldElement, SyntaxNode newElement)
=> SyntaxFactory.AreEquivalent(oldElement, newElement);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/VisualStudio/Core/Test/ChangeSignature/AddParameterViewModelTests.vb | ' 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.
Imports System.Windows
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ChangeSignature
<UseExportProvider, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Class AddParameterViewModelTests
<WpfFact>
Public Sub AddParameter_SubmittingRequiresTypeAndNameAndCallsiteValue()
Dim markup = <Text><![CDATA[
class MyClass
{
public void M($$) { }
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
viewModel.VerbatimTypeName = "int"
Dim message As String = Nothing
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.A_type_and_name_must_be_provided, message)
viewModel.VerbatimTypeName = ""
viewModel.ParameterName = "x"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.A_type_and_name_must_be_provided, message)
viewModel.VerbatimTypeName = "int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Enter_a_call_site_value_or_choose_a_different_value_injection_kind, message)
viewModel.CallSiteValue = "7"
Assert.True(viewModel.TrySubmit())
End Sub
<WpfFact>
Public Sub AddParameter_TypeNameTextBoxInteractions()
Dim markup = <Text><![CDATA[
class MyClass<T>
{
public void M($$) { }
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
Dim monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = "M"
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeDoesNotBindImage), ServicesVSResources.Type_name_is_not_recognized)
monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = "MyClass"
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeDoesNotBindImage), ServicesVSResources.Type_name_is_not_recognized)
monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = "MyClass<i"
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeDoesNotParseImage), ServicesVSResources.Type_name_has_a_syntax_error)
monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = "MyClass<int>"
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeBindsImage), ServicesVSResources.Type_name_is_recognized)
monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = ""
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeIsEmptyImage), ServicesVSResources.Please_enter_a_type_name)
End Sub
<WpfTheory>
<InlineData("int")>
<InlineData("MyClass")>
<InlineData("NS1.NS2.DifferentClass")>
Public Sub AddParameter_NoExistingParameters_TypeBinds(typeName As String)
Dim markup = <Text><![CDATA[
namespace NS1
{
namespace NS2
{
class DifferentClass { }
}
}
class MyClass
{
public void M($$)
{
M();
}
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
Dim monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = typeName
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeBindsImage), ServicesVSResources.Type_name_is_recognized)
viewModel.ParameterName = "x"
viewModel.CallSiteValue = "0"
Assert.True(viewModel.TrySubmit())
End Sub
<WpfFact>
Public Sub AddParameter_CannotBeBothRequiredAndOmit()
Dim markup = <Text><![CDATA[
class MyClass<T>
{
public void M($$) { }
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
Dim monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.IsOptional)
monitor.AddExpectation(Function() viewModel.IsRequired)
monitor.AddExpectation(Function() viewModel.IsCallsiteRegularValue)
monitor.AddExpectation(Function() viewModel.IsCallsiteOmitted)
viewModel.IsOptional = True
viewModel.IsCallsiteOmitted = True
viewModel.IsRequired = True
monitor.VerifyExpectations()
monitor.Detach()
Assert.True(viewModel.IsCallsiteRegularValue)
Assert.False(viewModel.IsCallsiteOmitted)
End Sub
<WpfTheory>
<InlineData("int")>
<InlineData("MyClass")>
<InlineData("NS1.NS2.DifferentClass")>
Public Sub AddParameter_ExistingParameters_TypeBinds(typeName As String)
Dim markup = <Text><![CDATA[
namespace NS1
{
namespace NS2
{
class DifferentClass { }
}
}
class MyClass
{
public void M(int x$$)
{
M(3);
}
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
Dim monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = typeName
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeBindsImage), ServicesVSResources.Type_name_is_recognized)
viewModel.ParameterName = "x"
viewModel.CallSiteValue = "0"
Assert.True(viewModel.TrySubmit())
End Sub
Private Sub AssertTypeBindingIconAndTextIs(viewModel As AddParameterDialogViewModel, currentIcon As String, expectedMessage As String)
Assert.True(viewModel.TypeIsEmptyImage = If(NameOf(viewModel.TypeIsEmptyImage) = currentIcon, Visibility.Visible, Visibility.Collapsed))
Assert.True(viewModel.TypeDoesNotParseImage = If(NameOf(viewModel.TypeDoesNotParseImage) = currentIcon, Visibility.Visible, Visibility.Collapsed))
Assert.True(viewModel.TypeDoesNotBindImage = If(NameOf(viewModel.TypeDoesNotBindImage) = currentIcon, Visibility.Visible, Visibility.Collapsed))
Assert.True(viewModel.TypeBindsImage = If(NameOf(viewModel.TypeBindsImage) = currentIcon, Visibility.Visible, Visibility.Collapsed))
Assert.Equal(expectedMessage, viewModel.TypeBindsDynamicStatus)
End Sub
Private Sub VerifyOpeningState(viewModel As AddParameterDialogViewModel)
Assert.True(viewModel.TypeBindsDynamicStatus = ServicesVSResources.Please_enter_a_type_name)
Assert.True(viewModel.TypeIsEmptyImage = Visibility.Visible)
Assert.True(viewModel.TypeDoesNotParseImage = Visibility.Collapsed)
Assert.True(viewModel.TypeDoesNotBindImage = Visibility.Collapsed)
Assert.True(viewModel.TypeBindsImage = Visibility.Collapsed)
Assert.True(viewModel.IsRequired)
Assert.False(viewModel.IsOptional)
Assert.Equal(String.Empty, viewModel.DefaultValue)
Assert.True(viewModel.IsCallsiteRegularValue)
Assert.Equal(String.Empty, viewModel.CallSiteValue)
Assert.False(viewModel.UseNamedArguments)
Assert.False(viewModel.IsCallsiteTodo)
Assert.False(viewModel.IsCallsiteOmitted)
Dim message As String = Nothing
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.A_type_and_name_must_be_provided, message)
End Sub
Private Function GetViewModelTestStateAsync(
markup As XElement,
languageName As String) As AddParameterViewModelTestState
Dim workspaceXml =
<Workspace>
<Project Language=<%= languageName %> CommonReferences="true">
<Document><%= markup.NormalizedValue.Replace(vbCrLf, vbLf) %></Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id)
If Not doc.CursorPosition.HasValue Then
Assert.True(False, "Missing caret location in document.")
End If
Dim viewModel = New AddParameterDialogViewModel(workspaceDoc, doc.CursorPosition.Value)
Return New AddParameterViewModelTestState(viewModel)
End Using
End Function
<WorkItem(44958, "https://github.com/dotnet/roslyn/issues/44958")>
<WpfFact>
Public Sub AddParameter_SubmittingTypeWithModifiersIsInvalid()
Dim markup = <Text><![CDATA[
class MyClass
{
public void M($$) { }
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
viewModel.ParameterName = "x"
viewModel.CallSiteValue = "1"
viewModel.TypeSymbol = Nothing
Dim message As String = Nothing
viewModel.VerbatimTypeName = "ref int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
viewModel.VerbatimTypeName = "this int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
viewModel.VerbatimTypeName = "this ref int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
viewModel.VerbatimTypeName = "out int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
viewModel.VerbatimTypeName = "params int[]"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
End Sub
End Class
End Namespace
| ' 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.
Imports System.Windows
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ChangeSignature
<UseExportProvider, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Class AddParameterViewModelTests
<WpfFact>
Public Sub AddParameter_SubmittingRequiresTypeAndNameAndCallsiteValue()
Dim markup = <Text><![CDATA[
class MyClass
{
public void M($$) { }
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
viewModel.VerbatimTypeName = "int"
Dim message As String = Nothing
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.A_type_and_name_must_be_provided, message)
viewModel.VerbatimTypeName = ""
viewModel.ParameterName = "x"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.A_type_and_name_must_be_provided, message)
viewModel.VerbatimTypeName = "int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Enter_a_call_site_value_or_choose_a_different_value_injection_kind, message)
viewModel.CallSiteValue = "7"
Assert.True(viewModel.TrySubmit())
End Sub
<WpfFact>
Public Sub AddParameter_TypeNameTextBoxInteractions()
Dim markup = <Text><![CDATA[
class MyClass<T>
{
public void M($$) { }
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
Dim monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = "M"
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeDoesNotBindImage), ServicesVSResources.Type_name_is_not_recognized)
monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = "MyClass"
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeDoesNotBindImage), ServicesVSResources.Type_name_is_not_recognized)
monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = "MyClass<i"
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeDoesNotParseImage), ServicesVSResources.Type_name_has_a_syntax_error)
monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = "MyClass<int>"
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeBindsImage), ServicesVSResources.Type_name_is_recognized)
monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = ""
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeIsEmptyImage), ServicesVSResources.Please_enter_a_type_name)
End Sub
<WpfTheory>
<InlineData("int")>
<InlineData("MyClass")>
<InlineData("NS1.NS2.DifferentClass")>
Public Sub AddParameter_NoExistingParameters_TypeBinds(typeName As String)
Dim markup = <Text><![CDATA[
namespace NS1
{
namespace NS2
{
class DifferentClass { }
}
}
class MyClass
{
public void M($$)
{
M();
}
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
Dim monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = typeName
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeBindsImage), ServicesVSResources.Type_name_is_recognized)
viewModel.ParameterName = "x"
viewModel.CallSiteValue = "0"
Assert.True(viewModel.TrySubmit())
End Sub
<WpfFact>
Public Sub AddParameter_CannotBeBothRequiredAndOmit()
Dim markup = <Text><![CDATA[
class MyClass<T>
{
public void M($$) { }
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
Dim monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.IsOptional)
monitor.AddExpectation(Function() viewModel.IsRequired)
monitor.AddExpectation(Function() viewModel.IsCallsiteRegularValue)
monitor.AddExpectation(Function() viewModel.IsCallsiteOmitted)
viewModel.IsOptional = True
viewModel.IsCallsiteOmitted = True
viewModel.IsRequired = True
monitor.VerifyExpectations()
monitor.Detach()
Assert.True(viewModel.IsCallsiteRegularValue)
Assert.False(viewModel.IsCallsiteOmitted)
End Sub
<WpfTheory>
<InlineData("int")>
<InlineData("MyClass")>
<InlineData("NS1.NS2.DifferentClass")>
Public Sub AddParameter_ExistingParameters_TypeBinds(typeName As String)
Dim markup = <Text><![CDATA[
namespace NS1
{
namespace NS2
{
class DifferentClass { }
}
}
class MyClass
{
public void M(int x$$)
{
M(3);
}
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
Dim monitor = New PropertyChangedTestMonitor(viewModel)
monitor.AddExpectation(Function() viewModel.TypeBindsDynamicStatus)
monitor.AddExpectation(Function() viewModel.TypeIsEmptyImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotParseImage)
monitor.AddExpectation(Function() viewModel.TypeDoesNotBindImage)
monitor.AddExpectation(Function() viewModel.TypeBindsImage)
viewModel.VerbatimTypeName = typeName
monitor.VerifyExpectations()
monitor.Detach()
AssertTypeBindingIconAndTextIs(viewModel, NameOf(viewModel.TypeBindsImage), ServicesVSResources.Type_name_is_recognized)
viewModel.ParameterName = "x"
viewModel.CallSiteValue = "0"
Assert.True(viewModel.TrySubmit())
End Sub
Private Sub AssertTypeBindingIconAndTextIs(viewModel As AddParameterDialogViewModel, currentIcon As String, expectedMessage As String)
Assert.True(viewModel.TypeIsEmptyImage = If(NameOf(viewModel.TypeIsEmptyImage) = currentIcon, Visibility.Visible, Visibility.Collapsed))
Assert.True(viewModel.TypeDoesNotParseImage = If(NameOf(viewModel.TypeDoesNotParseImage) = currentIcon, Visibility.Visible, Visibility.Collapsed))
Assert.True(viewModel.TypeDoesNotBindImage = If(NameOf(viewModel.TypeDoesNotBindImage) = currentIcon, Visibility.Visible, Visibility.Collapsed))
Assert.True(viewModel.TypeBindsImage = If(NameOf(viewModel.TypeBindsImage) = currentIcon, Visibility.Visible, Visibility.Collapsed))
Assert.Equal(expectedMessage, viewModel.TypeBindsDynamicStatus)
End Sub
Private Sub VerifyOpeningState(viewModel As AddParameterDialogViewModel)
Assert.True(viewModel.TypeBindsDynamicStatus = ServicesVSResources.Please_enter_a_type_name)
Assert.True(viewModel.TypeIsEmptyImage = Visibility.Visible)
Assert.True(viewModel.TypeDoesNotParseImage = Visibility.Collapsed)
Assert.True(viewModel.TypeDoesNotBindImage = Visibility.Collapsed)
Assert.True(viewModel.TypeBindsImage = Visibility.Collapsed)
Assert.True(viewModel.IsRequired)
Assert.False(viewModel.IsOptional)
Assert.Equal(String.Empty, viewModel.DefaultValue)
Assert.True(viewModel.IsCallsiteRegularValue)
Assert.Equal(String.Empty, viewModel.CallSiteValue)
Assert.False(viewModel.UseNamedArguments)
Assert.False(viewModel.IsCallsiteTodo)
Assert.False(viewModel.IsCallsiteOmitted)
Dim message As String = Nothing
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.A_type_and_name_must_be_provided, message)
End Sub
Private Function GetViewModelTestStateAsync(
markup As XElement,
languageName As String) As AddParameterViewModelTestState
Dim workspaceXml =
<Workspace>
<Project Language=<%= languageName %> CommonReferences="true">
<Document><%= markup.NormalizedValue.Replace(vbCrLf, vbLf) %></Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim workspaceDoc = workspace.CurrentSolution.GetDocument(doc.Id)
If Not doc.CursorPosition.HasValue Then
Assert.True(False, "Missing caret location in document.")
End If
Dim viewModel = New AddParameterDialogViewModel(workspaceDoc, doc.CursorPosition.Value)
Return New AddParameterViewModelTestState(viewModel)
End Using
End Function
<WorkItem(44958, "https://github.com/dotnet/roslyn/issues/44958")>
<WpfFact>
Public Sub AddParameter_SubmittingTypeWithModifiersIsInvalid()
Dim markup = <Text><![CDATA[
class MyClass
{
public void M($$) { }
}"]]></Text>
Dim viewModelTestState = GetViewModelTestStateAsync(markup, LanguageNames.CSharp)
Dim viewModel = viewModelTestState.ViewModel
VerifyOpeningState(viewModel)
viewModel.ParameterName = "x"
viewModel.CallSiteValue = "1"
viewModel.TypeSymbol = Nothing
Dim message As String = Nothing
viewModel.VerbatimTypeName = "ref int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
viewModel.VerbatimTypeName = "this int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
viewModel.VerbatimTypeName = "this ref int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
viewModel.VerbatimTypeName = "out int"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
viewModel.VerbatimTypeName = "params int[]"
Assert.False(viewModel.CanSubmit(message))
Assert.Equal(ServicesVSResources.Parameter_type_contains_invalid_characters, message)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/Workspaces/VisualBasicTest/VisualBasicExtensionsTests.vb | ' 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.
Imports System.Text
Imports Roslyn.Test.Utilities
Imports Xunit
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.SyntaxTreeExtensions
Imports System.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class VisualBasicExtensionsTests
<WorkItem(6536, "https://github.com/dotnet/roslyn/issues/6536")>
<Fact>
Public Sub TestFindTrivia_NoStackOverflowOnLargeExpression()
Dim code As New StringBuilder()
code.Append(<![CDATA[
Module Module1
Sub Test()
Dim c = ]]>.Value)
For i = 0 To 3000
code.Append("""asdf"" + ")
Next
code.AppendLine(<![CDATA["last"
End Sub
End Module]]>.Value)
Dim tree = VisualBasicSyntaxTree.ParseText(code.ToString())
Dim trivia = tree.FindTriviaToLeft(4000, CancellationToken.None)
' no stack overflow
End Sub
End Class
End Namespace
| ' 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.
Imports System.Text
Imports Roslyn.Test.Utilities
Imports Xunit
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.SyntaxTreeExtensions
Imports System.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class VisualBasicExtensionsTests
<WorkItem(6536, "https://github.com/dotnet/roslyn/issues/6536")>
<Fact>
Public Sub TestFindTrivia_NoStackOverflowOnLargeExpression()
Dim code As New StringBuilder()
code.Append(<![CDATA[
Module Module1
Sub Test()
Dim c = ]]>.Value)
For i = 0 To 3000
code.Append("""asdf"" + ")
Next
code.AppendLine(<![CDATA["last"
End Sub
End Module]]>.Value)
Dim tree = VisualBasicSyntaxTree.ParseText(code.ToString())
Dim trivia = tree.FindTriviaToLeft(4000, CancellationToken.None)
' no stack overflow
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/Dependencies/PooledObjects/ArrayBuilder.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;
namespace Microsoft.CodeAnalysis.PooledObjects
{
[DebuggerDisplay("Count = {Count,nq}")]
[DebuggerTypeProxy(typeof(ArrayBuilder<>.DebuggerProxy))]
internal sealed partial class ArrayBuilder<T> : IReadOnlyCollection<T>, IReadOnlyList<T>
{
#region DebuggerProxy
private sealed class DebuggerProxy
{
private readonly ArrayBuilder<T> _builder;
public DebuggerProxy(ArrayBuilder<T> builder)
{
_builder = builder;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
var result = new T[_builder.Count];
for (var i = 0; i < result.Length; i++)
{
result[i] = _builder[i];
}
return result;
}
}
}
#endregion
private readonly ImmutableArray<T>.Builder _builder;
private readonly ObjectPool<ArrayBuilder<T>>? _pool;
public ArrayBuilder(int size)
{
_builder = ImmutableArray.CreateBuilder<T>(size);
}
public ArrayBuilder()
: this(8)
{ }
private ArrayBuilder(ObjectPool<ArrayBuilder<T>> pool)
: this()
{
_pool = pool;
}
/// <summary>
/// Realizes the array.
/// </summary>
public ImmutableArray<T> ToImmutable()
{
return _builder.ToImmutable();
}
/// <summary>
/// Realizes the array and clears the collection.
/// </summary>
public ImmutableArray<T> ToImmutableAndClear()
{
ImmutableArray<T> result;
if (Count == 0)
{
result = ImmutableArray<T>.Empty;
}
else if (_builder.Capacity == Count)
{
result = _builder.MoveToImmutable();
}
else
{
result = ToImmutable();
Clear();
}
return result;
}
public int Count
{
get
{
return _builder.Count;
}
set
{
_builder.Count = value;
}
}
public T this[int index]
{
get
{
return _builder[index];
}
set
{
_builder[index] = value;
}
}
/// <summary>
/// Write <paramref name="value"/> to slot <paramref name="index"/>.
/// Fills in unallocated slots preceding the <paramref name="index"/>, if any.
/// </summary>
public void SetItem(int index, T value)
{
while (index > _builder.Count)
{
_builder.Add(default!);
}
if (index == _builder.Count)
{
_builder.Add(value);
}
else
{
_builder[index] = value;
}
}
public void Add(T item)
{
_builder.Add(item);
}
public void Insert(int index, T item)
{
_builder.Insert(index, item);
}
public void EnsureCapacity(int capacity)
{
if (_builder.Capacity < capacity)
{
_builder.Capacity = capacity;
}
}
public void Clear()
{
_builder.Clear();
}
public bool Contains(T item)
{
return _builder.Contains(item);
}
public int IndexOf(T item)
{
return _builder.IndexOf(item);
}
public int IndexOf(T item, IEqualityComparer<T> equalityComparer)
{
return _builder.IndexOf(item, 0, _builder.Count, equalityComparer);
}
public int IndexOf(T item, int startIndex, int count)
{
return _builder.IndexOf(item, startIndex, count);
}
public int FindIndex(Predicate<T> match)
=> FindIndex(0, this.Count, match);
public int FindIndex(int startIndex, Predicate<T> match)
=> FindIndex(startIndex, this.Count - startIndex, match);
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
var endIndex = startIndex + count;
for (var i = startIndex; i < endIndex; i++)
{
if (match(_builder[i]))
{
return i;
}
}
return -1;
}
public int FindIndex<TArg>(Func<T, TArg, bool> match, TArg arg)
=> FindIndex(0, Count, match, arg);
public int FindIndex<TArg>(int startIndex, Func<T, TArg, bool> match, TArg arg)
=> FindIndex(startIndex, Count - startIndex, match, arg);
public int FindIndex<TArg>(int startIndex, int count, Func<T, TArg, bool> match, TArg arg)
{
var endIndex = startIndex + count;
for (var i = startIndex; i < endIndex; i++)
{
if (match(_builder[i], arg))
{
return i;
}
}
return -1;
}
public bool Remove(T element)
{
return _builder.Remove(element);
}
public void RemoveAt(int index)
{
_builder.RemoveAt(index);
}
public void RemoveLast()
{
_builder.RemoveAt(_builder.Count - 1);
}
public void ReverseContents()
{
_builder.Reverse();
}
public void Sort()
{
_builder.Sort();
}
public void Sort(IComparer<T> comparer)
{
_builder.Sort(comparer);
}
public void Sort(Comparison<T> compare)
=> Sort(Comparer<T>.Create(compare));
public void Sort(int startIndex, IComparer<T> comparer)
{
_builder.Sort(startIndex, _builder.Count - startIndex, comparer);
}
public T[] ToArray()
{
return _builder.ToArray();
}
public void CopyTo(T[] array, int start)
{
_builder.CopyTo(array, start);
}
public T Last()
{
return _builder[_builder.Count - 1];
}
public T First()
{
return _builder[0];
}
public bool Any()
{
return _builder.Count > 0;
}
/// <summary>
/// Realizes the array.
/// </summary>
public ImmutableArray<T> ToImmutableOrNull()
{
if (Count == 0)
{
return default;
}
return this.ToImmutable();
}
/// <summary>
/// Realizes the array, downcasting each element to a derived type.
/// </summary>
public ImmutableArray<U> ToDowncastedImmutable<U>()
where U : T
{
if (Count == 0)
{
return ImmutableArray<U>.Empty;
}
var tmp = ArrayBuilder<U>.GetInstance(Count);
foreach (var i in this)
{
tmp.Add((U)i!);
}
return tmp.ToImmutableAndFree();
}
/// <summary>
/// Realizes the array and disposes the builder in one operation.
/// </summary>
public ImmutableArray<T> ToImmutableAndFree()
{
// This is mostly the same as 'MoveToImmutable', but avoids delegating to that method since 'Free' contains
// fast paths to avoid caling 'Clear' in some cases.
ImmutableArray<T> result;
if (Count == 0)
{
result = ImmutableArray<T>.Empty;
}
else if (_builder.Capacity == Count)
{
result = _builder.MoveToImmutable();
}
else
{
result = ToImmutable();
}
this.Free();
return result;
}
public T[] ToArrayAndFree()
{
var result = this.ToArray();
this.Free();
return result;
}
#region Poolable
// To implement Poolable, you need two things:
// 1) Expose Freeing primitive.
public void Free()
{
var pool = _pool;
if (pool != null)
{
// According to the statistics of a C# compiler self-build, the most commonly used builder size is 0. (808003 uses).
// The distant second is the Count == 1 (455619), then 2 (106362) ...
// After about 50 (just 67) we have a long tail of infrequently used builder sizes.
// However we have builders with size up to 50K (just one such thing)
//
// We do not want to retain (potentially indefinitely) very large builders
// while the chance that we will need their size is diminishingly small.
// It makes sense to constrain the size to some "not too small" number.
// Overall perf does not seem to be very sensitive to this number, so I picked 128 as a limit.
if (_builder.Capacity < 128)
{
if (this.Count != 0)
{
this.Clear();
}
pool.Free(this);
return;
}
else
{
pool.ForgetTrackedObject(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<ArrayBuilder<T>> s_poolInstance = CreatePool();
public static ArrayBuilder<T> GetInstance()
{
var builder = s_poolInstance.Allocate();
Debug.Assert(builder.Count == 0);
return builder;
}
public static ArrayBuilder<T> GetInstance(int capacity)
{
var builder = GetInstance();
builder.EnsureCapacity(capacity);
return builder;
}
public static ArrayBuilder<T> GetInstance(int capacity, T fillWithValue)
{
var builder = GetInstance();
builder.EnsureCapacity(capacity);
for (var i = 0; i < capacity; i++)
{
builder.Add(fillWithValue);
}
return builder;
}
public static ObjectPool<ArrayBuilder<T>> CreatePool()
{
return CreatePool(128); // we rarely need more than 10
}
public static ObjectPool<ArrayBuilder<T>> CreatePool(int size)
{
ObjectPool<ArrayBuilder<T>>? pool = null;
pool = new ObjectPool<ArrayBuilder<T>>(() => new ArrayBuilder<T>(pool!), size);
return pool;
}
#endregion
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _builder.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _builder.GetEnumerator();
}
internal Dictionary<K, ImmutableArray<T>> ToDictionary<K>(Func<T, K> keySelector, IEqualityComparer<K>? comparer = null)
where K : notnull
{
if (this.Count == 1)
{
var dictionary1 = new Dictionary<K, ImmutableArray<T>>(1, comparer);
var value = this[0];
dictionary1.Add(keySelector(value), ImmutableArray.Create(value));
return dictionary1;
}
if (this.Count == 0)
{
return new Dictionary<K, ImmutableArray<T>>(comparer);
}
// bucketize
// prevent reallocation. it may not have 'count' entries, but it won't have more.
var accumulator = new Dictionary<K, ArrayBuilder<T>>(Count, comparer);
for (var i = 0; i < Count; i++)
{
var item = this[i];
var key = keySelector(item);
if (!accumulator.TryGetValue(key, out var bucket))
{
bucket = ArrayBuilder<T>.GetInstance();
accumulator.Add(key, bucket);
}
bucket.Add(item);
}
var dictionary = new Dictionary<K, ImmutableArray<T>>(accumulator.Count, comparer);
// freeze
foreach (var pair in accumulator)
{
dictionary.Add(pair.Key, pair.Value.ToImmutableAndFree());
}
return dictionary;
}
public void AddRange(ArrayBuilder<T> items)
{
_builder.AddRange(items._builder);
}
public void AddRange<U>(ArrayBuilder<U> items, Func<U, T> selector)
{
foreach (var item in items)
{
_builder.Add(selector(item));
}
}
public void AddRange<U>(ArrayBuilder<U> items) where U : T
{
_builder.AddRange(items._builder);
}
public void AddRange<U>(ArrayBuilder<U> items, int start, int length) where U : T
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Count);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange(ImmutableArray<T> items)
{
_builder.AddRange(items);
}
public void AddRange(ImmutableArray<T> items, int length)
{
_builder.AddRange(items, length);
}
public void AddRange(ImmutableArray<T> items, int start, int length)
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Length);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange<S>(ImmutableArray<S> items) where S : class, T
{
AddRange(ImmutableArray<T>.CastUp(items));
}
public void AddRange(T[] items, int start, int length)
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Length);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange(IEnumerable<T> items)
{
_builder.AddRange(items);
}
public void AddRange(params T[] items)
{
_builder.AddRange(items);
}
public void AddRange(T[] items, int length)
{
_builder.AddRange(items, length);
}
public void Clip(int limit)
{
Debug.Assert(limit <= Count);
_builder.Count = limit;
}
public void ZeroInit(int count)
{
_builder.Clear();
_builder.Count = count;
}
public void AddMany(T item, int count)
{
for (var i = 0; i < count; i++)
{
Add(item);
}
}
public void RemoveDuplicates()
{
var set = PooledHashSet<T>.GetInstance();
var j = 0;
for (var i = 0; i < Count; i++)
{
if (set.Add(this[i]))
{
this[j] = this[i];
j++;
}
}
Clip(j);
set.Free();
}
public void SortAndRemoveDuplicates(IComparer<T> comparer)
{
if (Count <= 1)
{
return;
}
Sort(comparer);
int j = 0;
for (int i = 1; i < Count; i++)
{
if (comparer.Compare(this[j], this[i]) < 0)
{
j++;
this[j] = this[i];
}
}
Clip(j + 1);
}
public ImmutableArray<S> SelectDistinct<S>(Func<T, S> selector)
{
var result = ArrayBuilder<S>.GetInstance(Count);
var set = PooledHashSet<S>.GetInstance();
foreach (var item in this)
{
var selected = selector(item);
if (set.Add(selected))
{
result.Add(selected);
}
}
set.Free();
return result.ToImmutableAndFree();
}
}
}
| // 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;
namespace Microsoft.CodeAnalysis.PooledObjects
{
[DebuggerDisplay("Count = {Count,nq}")]
[DebuggerTypeProxy(typeof(ArrayBuilder<>.DebuggerProxy))]
internal sealed partial class ArrayBuilder<T> : IReadOnlyCollection<T>, IReadOnlyList<T>
{
#region DebuggerProxy
private sealed class DebuggerProxy
{
private readonly ArrayBuilder<T> _builder;
public DebuggerProxy(ArrayBuilder<T> builder)
{
_builder = builder;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
var result = new T[_builder.Count];
for (var i = 0; i < result.Length; i++)
{
result[i] = _builder[i];
}
return result;
}
}
}
#endregion
private readonly ImmutableArray<T>.Builder _builder;
private readonly ObjectPool<ArrayBuilder<T>>? _pool;
public ArrayBuilder(int size)
{
_builder = ImmutableArray.CreateBuilder<T>(size);
}
public ArrayBuilder()
: this(8)
{ }
private ArrayBuilder(ObjectPool<ArrayBuilder<T>> pool)
: this()
{
_pool = pool;
}
/// <summary>
/// Realizes the array.
/// </summary>
public ImmutableArray<T> ToImmutable()
{
return _builder.ToImmutable();
}
/// <summary>
/// Realizes the array and clears the collection.
/// </summary>
public ImmutableArray<T> ToImmutableAndClear()
{
ImmutableArray<T> result;
if (Count == 0)
{
result = ImmutableArray<T>.Empty;
}
else if (_builder.Capacity == Count)
{
result = _builder.MoveToImmutable();
}
else
{
result = ToImmutable();
Clear();
}
return result;
}
public int Count
{
get
{
return _builder.Count;
}
set
{
_builder.Count = value;
}
}
public T this[int index]
{
get
{
return _builder[index];
}
set
{
_builder[index] = value;
}
}
/// <summary>
/// Write <paramref name="value"/> to slot <paramref name="index"/>.
/// Fills in unallocated slots preceding the <paramref name="index"/>, if any.
/// </summary>
public void SetItem(int index, T value)
{
while (index > _builder.Count)
{
_builder.Add(default!);
}
if (index == _builder.Count)
{
_builder.Add(value);
}
else
{
_builder[index] = value;
}
}
public void Add(T item)
{
_builder.Add(item);
}
public void Insert(int index, T item)
{
_builder.Insert(index, item);
}
public void EnsureCapacity(int capacity)
{
if (_builder.Capacity < capacity)
{
_builder.Capacity = capacity;
}
}
public void Clear()
{
_builder.Clear();
}
public bool Contains(T item)
{
return _builder.Contains(item);
}
public int IndexOf(T item)
{
return _builder.IndexOf(item);
}
public int IndexOf(T item, IEqualityComparer<T> equalityComparer)
{
return _builder.IndexOf(item, 0, _builder.Count, equalityComparer);
}
public int IndexOf(T item, int startIndex, int count)
{
return _builder.IndexOf(item, startIndex, count);
}
public int FindIndex(Predicate<T> match)
=> FindIndex(0, this.Count, match);
public int FindIndex(int startIndex, Predicate<T> match)
=> FindIndex(startIndex, this.Count - startIndex, match);
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
var endIndex = startIndex + count;
for (var i = startIndex; i < endIndex; i++)
{
if (match(_builder[i]))
{
return i;
}
}
return -1;
}
public int FindIndex<TArg>(Func<T, TArg, bool> match, TArg arg)
=> FindIndex(0, Count, match, arg);
public int FindIndex<TArg>(int startIndex, Func<T, TArg, bool> match, TArg arg)
=> FindIndex(startIndex, Count - startIndex, match, arg);
public int FindIndex<TArg>(int startIndex, int count, Func<T, TArg, bool> match, TArg arg)
{
var endIndex = startIndex + count;
for (var i = startIndex; i < endIndex; i++)
{
if (match(_builder[i], arg))
{
return i;
}
}
return -1;
}
public bool Remove(T element)
{
return _builder.Remove(element);
}
public void RemoveAt(int index)
{
_builder.RemoveAt(index);
}
public void RemoveLast()
{
_builder.RemoveAt(_builder.Count - 1);
}
public void ReverseContents()
{
_builder.Reverse();
}
public void Sort()
{
_builder.Sort();
}
public void Sort(IComparer<T> comparer)
{
_builder.Sort(comparer);
}
public void Sort(Comparison<T> compare)
=> Sort(Comparer<T>.Create(compare));
public void Sort(int startIndex, IComparer<T> comparer)
{
_builder.Sort(startIndex, _builder.Count - startIndex, comparer);
}
public T[] ToArray()
{
return _builder.ToArray();
}
public void CopyTo(T[] array, int start)
{
_builder.CopyTo(array, start);
}
public T Last()
{
return _builder[_builder.Count - 1];
}
public T First()
{
return _builder[0];
}
public bool Any()
{
return _builder.Count > 0;
}
/// <summary>
/// Realizes the array.
/// </summary>
public ImmutableArray<T> ToImmutableOrNull()
{
if (Count == 0)
{
return default;
}
return this.ToImmutable();
}
/// <summary>
/// Realizes the array, downcasting each element to a derived type.
/// </summary>
public ImmutableArray<U> ToDowncastedImmutable<U>()
where U : T
{
if (Count == 0)
{
return ImmutableArray<U>.Empty;
}
var tmp = ArrayBuilder<U>.GetInstance(Count);
foreach (var i in this)
{
tmp.Add((U)i!);
}
return tmp.ToImmutableAndFree();
}
/// <summary>
/// Realizes the array and disposes the builder in one operation.
/// </summary>
public ImmutableArray<T> ToImmutableAndFree()
{
// This is mostly the same as 'MoveToImmutable', but avoids delegating to that method since 'Free' contains
// fast paths to avoid caling 'Clear' in some cases.
ImmutableArray<T> result;
if (Count == 0)
{
result = ImmutableArray<T>.Empty;
}
else if (_builder.Capacity == Count)
{
result = _builder.MoveToImmutable();
}
else
{
result = ToImmutable();
}
this.Free();
return result;
}
public T[] ToArrayAndFree()
{
var result = this.ToArray();
this.Free();
return result;
}
#region Poolable
// To implement Poolable, you need two things:
// 1) Expose Freeing primitive.
public void Free()
{
var pool = _pool;
if (pool != null)
{
// According to the statistics of a C# compiler self-build, the most commonly used builder size is 0. (808003 uses).
// The distant second is the Count == 1 (455619), then 2 (106362) ...
// After about 50 (just 67) we have a long tail of infrequently used builder sizes.
// However we have builders with size up to 50K (just one such thing)
//
// We do not want to retain (potentially indefinitely) very large builders
// while the chance that we will need their size is diminishingly small.
// It makes sense to constrain the size to some "not too small" number.
// Overall perf does not seem to be very sensitive to this number, so I picked 128 as a limit.
if (_builder.Capacity < 128)
{
if (this.Count != 0)
{
this.Clear();
}
pool.Free(this);
return;
}
else
{
pool.ForgetTrackedObject(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<ArrayBuilder<T>> s_poolInstance = CreatePool();
public static ArrayBuilder<T> GetInstance()
{
var builder = s_poolInstance.Allocate();
Debug.Assert(builder.Count == 0);
return builder;
}
public static ArrayBuilder<T> GetInstance(int capacity)
{
var builder = GetInstance();
builder.EnsureCapacity(capacity);
return builder;
}
public static ArrayBuilder<T> GetInstance(int capacity, T fillWithValue)
{
var builder = GetInstance();
builder.EnsureCapacity(capacity);
for (var i = 0; i < capacity; i++)
{
builder.Add(fillWithValue);
}
return builder;
}
public static ObjectPool<ArrayBuilder<T>> CreatePool()
{
return CreatePool(128); // we rarely need more than 10
}
public static ObjectPool<ArrayBuilder<T>> CreatePool(int size)
{
ObjectPool<ArrayBuilder<T>>? pool = null;
pool = new ObjectPool<ArrayBuilder<T>>(() => new ArrayBuilder<T>(pool!), size);
return pool;
}
#endregion
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _builder.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _builder.GetEnumerator();
}
internal Dictionary<K, ImmutableArray<T>> ToDictionary<K>(Func<T, K> keySelector, IEqualityComparer<K>? comparer = null)
where K : notnull
{
if (this.Count == 1)
{
var dictionary1 = new Dictionary<K, ImmutableArray<T>>(1, comparer);
var value = this[0];
dictionary1.Add(keySelector(value), ImmutableArray.Create(value));
return dictionary1;
}
if (this.Count == 0)
{
return new Dictionary<K, ImmutableArray<T>>(comparer);
}
// bucketize
// prevent reallocation. it may not have 'count' entries, but it won't have more.
var accumulator = new Dictionary<K, ArrayBuilder<T>>(Count, comparer);
for (var i = 0; i < Count; i++)
{
var item = this[i];
var key = keySelector(item);
if (!accumulator.TryGetValue(key, out var bucket))
{
bucket = ArrayBuilder<T>.GetInstance();
accumulator.Add(key, bucket);
}
bucket.Add(item);
}
var dictionary = new Dictionary<K, ImmutableArray<T>>(accumulator.Count, comparer);
// freeze
foreach (var pair in accumulator)
{
dictionary.Add(pair.Key, pair.Value.ToImmutableAndFree());
}
return dictionary;
}
public void AddRange(ArrayBuilder<T> items)
{
_builder.AddRange(items._builder);
}
public void AddRange<U>(ArrayBuilder<U> items, Func<U, T> selector)
{
foreach (var item in items)
{
_builder.Add(selector(item));
}
}
public void AddRange<U>(ArrayBuilder<U> items) where U : T
{
_builder.AddRange(items._builder);
}
public void AddRange<U>(ArrayBuilder<U> items, int start, int length) where U : T
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Count);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange(ImmutableArray<T> items)
{
_builder.AddRange(items);
}
public void AddRange(ImmutableArray<T> items, int length)
{
_builder.AddRange(items, length);
}
public void AddRange(ImmutableArray<T> items, int start, int length)
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Length);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange<S>(ImmutableArray<S> items) where S : class, T
{
AddRange(ImmutableArray<T>.CastUp(items));
}
public void AddRange(T[] items, int start, int length)
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Length);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange(IEnumerable<T> items)
{
_builder.AddRange(items);
}
public void AddRange(params T[] items)
{
_builder.AddRange(items);
}
public void AddRange(T[] items, int length)
{
_builder.AddRange(items, length);
}
public void Clip(int limit)
{
Debug.Assert(limit <= Count);
_builder.Count = limit;
}
public void ZeroInit(int count)
{
_builder.Clear();
_builder.Count = count;
}
public void AddMany(T item, int count)
{
for (var i = 0; i < count; i++)
{
Add(item);
}
}
public void RemoveDuplicates()
{
var set = PooledHashSet<T>.GetInstance();
var j = 0;
for (var i = 0; i < Count; i++)
{
if (set.Add(this[i]))
{
this[j] = this[i];
j++;
}
}
Clip(j);
set.Free();
}
public void SortAndRemoveDuplicates(IComparer<T> comparer)
{
if (Count <= 1)
{
return;
}
Sort(comparer);
int j = 0;
for (int i = 1; i < Count; i++)
{
if (comparer.Compare(this[j], this[i]) < 0)
{
j++;
this[j] = this[i];
}
}
Clip(j + 1);
}
public ImmutableArray<S> SelectDistinct<S>(Func<T, S> selector)
{
var result = ArrayBuilder<S>.GetInstance(Count);
var set = PooledHashSet<S>.GetInstance();
foreach (var item in this)
{
var selected = selector(item);
if (set.Add(selected))
{
result.Add(selected);
}
}
set.Free();
return result.ToImmutableAndFree();
}
}
}
| -1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/Compilers/CSharp/Test/Syntax/IncrementalParsing/ChangingAsync.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.CSharp.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing
{
// These tests handle changing between asynchronous and synchronous parsing contexts as the 'async' modifier is added / removed.
public class ChangingAsync
{
[Fact]
public void AddAsync()
{
string oldText =
@"class Test
{
public static void F()
{
await t;
}
}";
ParseAndVerify(oldText, validator: oldTree =>
{
var newTree = oldTree.WithInsertBefore("public", "async ");
Assert.Equal(default(SyntaxNodeOrToken), oldTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
Assert.NotEqual(default(SyntaxNodeOrToken), newTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
});
}
[Fact]
public void RemoveAsync()
{
string oldText =
@"class Test
{
async public static void F()
{
await t;
}
}";
ParseAndVerify(oldText, validator: oldTree =>
{
var newTree = oldTree.WithRemoveFirst("async");
Assert.NotEqual(default(SyntaxNodeOrToken), oldTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
Assert.Equal(default(SyntaxNodeOrToken), newTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
});
}
#region Helpers
private static void ParseAndVerify(string text, Action<SyntaxTree> validator)
{
ParseAndValidate(text, validator, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5));
ParseAndValidate(text, validator, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp5));
}
private static void ParseAndValidate(string text, Action<SyntaxTree> validator, CSharpParseOptions options = null)
{
var oldTree = SyntaxFactory.ParseSyntaxTree(text);
validator(oldTree);
}
#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;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing
{
// These tests handle changing between asynchronous and synchronous parsing contexts as the 'async' modifier is added / removed.
public class ChangingAsync
{
[Fact]
public void AddAsync()
{
string oldText =
@"class Test
{
public static void F()
{
await t;
}
}";
ParseAndVerify(oldText, validator: oldTree =>
{
var newTree = oldTree.WithInsertBefore("public", "async ");
Assert.Equal(default(SyntaxNodeOrToken), oldTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
Assert.NotEqual(default(SyntaxNodeOrToken), newTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
});
}
[Fact]
public void RemoveAsync()
{
string oldText =
@"class Test
{
async public static void F()
{
await t;
}
}";
ParseAndVerify(oldText, validator: oldTree =>
{
var newTree = oldTree.WithRemoveFirst("async");
Assert.NotEqual(default(SyntaxNodeOrToken), oldTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
Assert.Equal(default(SyntaxNodeOrToken), newTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
});
}
#region Helpers
private static void ParseAndVerify(string text, Action<SyntaxTree> validator)
{
ParseAndValidate(text, validator, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5));
ParseAndValidate(text, validator, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp5));
}
private static void ParseAndValidate(string text, Action<SyntaxTree> validator, CSharpParseOptions options = null)
{
var oldTree = SyntaxFactory.ParseSyntaxTree(text);
validator(oldTree);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListenerProvider+NullListenerProvider.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.Shared.TestHooks
{
internal sealed partial class AsynchronousOperationListenerProvider
{
private sealed class NullListenerProvider : IAsynchronousOperationListenerProvider
{
public IAsynchronousOperationListener GetListener(string featureName) => NullListener;
}
}
}
| // 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.Shared.TestHooks
{
internal sealed partial class AsynchronousOperationListenerProvider
{
private sealed class NullListenerProvider : IAsynchronousOperationListenerProvider
{
public IAsynchronousOperationListener GetListener(string featureName) => NullListener;
}
}
}
| -1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/EditorFeatures/Core/SymbolSearch/SymbolSearchUpdateEngine.RemoteControlService.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.VisualStudio.RemoteControl;
namespace Microsoft.CodeAnalysis.SymbolSearch
{
internal partial class SymbolSearchUpdateEngine
{
private class RemoteControlService : IRemoteControlService
{
public IRemoteControlClient CreateClient(string hostId, string serverPath, int pollingMinutes)
{
// BaseUrl provided by the VS RemoteControl client team. This is URL we are supposed
// to use to publish and access data from.
const string BaseUrl = "https://az700632.vo.msecnd.net/pub";
return new RemoteControlClient(hostId, BaseUrl, serverPath, pollingMinutes);
}
}
}
}
| // 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.VisualStudio.RemoteControl;
namespace Microsoft.CodeAnalysis.SymbolSearch
{
internal partial class SymbolSearchUpdateEngine
{
private class RemoteControlService : IRemoteControlService
{
public IRemoteControlClient CreateClient(string hostId, string serverPath, int pollingMinutes)
{
// BaseUrl provided by the VS RemoteControl client team. This is URL we are supposed
// to use to publish and access data from.
const string BaseUrl = "https://az700632.vo.msecnd.net/pub";
return new RemoteControlClient(hostId, BaseUrl, serverPath, pollingMinutes);
}
}
}
}
| -1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdEventTest.vb | ' 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.
Imports System.Linq
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata
Public Class WinMdEventTest
Inherits BasicTestBase
Private ReadOnly _eventInterfaceILTemplate As String = <![CDATA[
.class interface public abstract auto ansi {0}
{{
.method public hidebysig newslot specialname abstract virtual
instance void add_Normal(class [mscorlib]System.Action 'value') cil managed
{{
}}
.method public hidebysig newslot specialname abstract virtual
instance void remove_Normal(class [mscorlib]System.Action 'value') cil managed
{{
}}
.method public hidebysig newslot specialname abstract virtual
instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken
add_WinRT([in] class [mscorlib]System.Action 'value') cil managed
{{
}}
.method public hidebysig newslot specialname abstract virtual
instance void remove_WinRT([in] valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed
{{
}}
.event class [mscorlib]System.Action Normal
{{
.addon instance void {0}::add_Normal(class [mscorlib]System.Action)
.removeon instance void {0}::remove_Normal(class [mscorlib]System.Action)
}}
.event class [mscorlib]System.Action WinRT
{{
.addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken {0}::add_WinRT(class [mscorlib]System.Action)
.removeon instance void {0}::remove_WinRT(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
}}
}} // end of class {0}
]]>.Value
Private ReadOnly _eventLibRef As MetadataReference
Private ReadOnly _dynamicCommonSrc As XElement =
<compilation>
<file name="dynamic_common.vb">
<![CDATA[
Imports System.Runtime.InteropServices.WindowsRuntime
Imports EventLibrary
Public Partial Class A
Implements I
Public Event d1 As voidVoidDelegate Implements I.d1
Public Event d2 As voidStringDelegate Implements I.d2
Public Event d3 As voidDynamicDelegate Implements I.d3
Public Event d4 As voidDelegateDelegate Implements I.d4
End Class
Public Partial Class B
Implements I
Private voidTable As New EventRegistrationTokenTable(Of voidVoidDelegate)()
Private voidStringTable As New EventRegistrationTokenTable(Of voidStringDelegate)()
Private voidDynamicTable As New EventRegistrationTokenTable(Of voidDynamicDelegate)()
Private voidDelegateTable As New EventRegistrationTokenTable(Of voidDelegateDelegate)()
Public Custom Event d1 As voidVoidDelegate Implements I.d1
AddHandler(value As voidVoidDelegate)
Return voidTable.AddEventHandler(value)
End AddHandler
RemoveHandler(value As EventRegistrationToken)
voidTable.RemoveEventHandler(value)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Public Custom Event d2 As voidStringDelegate Implements I.d2
AddHandler(value As voidStringDelegate)
Return voidStringTable.AddEventHandler(value)
End AddHandler
RemoveHandler(value As EventRegistrationToken)
voidStringTable.RemoveEventHandler(value)
End RemoveHandler
RaiseEvent(s As String)
End RaiseEvent
End Event
Public Custom Event d3 As voidDynamicDelegate Implements I.d3
AddHandler(value As voidDynamicDelegate)
Return voidDynamicTable.AddEventHandler(value)
End AddHandler
RemoveHandler(value As EventRegistrationToken)
voidDynamicTable.RemoveEventHandler(value)
End RemoveHandler
RaiseEvent(d As Object)
End RaiseEvent
End Event
Public Custom Event d4 As voidDelegateDelegate Implements I.d4
AddHandler(value As voidDelegateDelegate)
Return voidDelegateTable.AddEventHandler(value)
End AddHandler
RemoveHandler(value As EventRegistrationToken)
voidDelegateTable.RemoveEventHandler(value)
End RemoveHandler
RaiseEvent([delegate] As voidVoidDelegate)
End RaiseEvent
End Event
End Class
]]>
</file>
</compilation>
Public Sub New()
' The following two libraries are shrunk code pulled from
' corresponding files in the csharp5 legacy tests
Dim eventLibSrc =
<compilation><file name="EventLibrary.vb">
<![CDATA[
Namespace EventLibrary
Public Delegate Sub voidVoidDelegate()
Public Delegate Sub voidStringDelegate(s As String)
Public Delegate Sub voidDynamicDelegate(d As Object)
Public Delegate Sub voidDelegateDelegate([delegate] As voidVoidDelegate)
Public Interface I
Event d1 As voidVoidDelegate
Event d2 As voidStringDelegate
Event d3 As voidDynamicDelegate
Event d4 As voidDelegateDelegate
End Interface
End Namespace
]]>
</file></compilation>
_eventLibRef = CreateEmptyCompilationWithReferences(
eventLibSrc,
references:={MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929},
options:=TestOptions.ReleaseWinMD).EmitToImageReference()
End Sub
<Fact()>
Public Sub WinMdExternalEventTests()
Dim src =
<compilation><file name="c.vb">
<![CDATA[
Imports EventLibrary
Class C
Sub Main()
Dim a = new A()
Dim b = new B()
Dim void = Sub()
End Sub
Dim str = Sub(s As String)
End Sub
Dim dyn = Sub(d As Object)
End Sub
Dim del = Sub([delegate] As voidVoidDelegate)
End Sub
AddHandler a.d1, void
AddHandler a.d2, str
AddHandler a.d3, dyn
AddHandler a.d4, del
RemoveHandler a.d1, void
RemoveHandler a.d2, str
RemoveHandler a.d3, dyn
RemoveHandler a.d4, del
AddHandler b.d1, void
AddHandler b.d2, str
AddHandler b.d3, dyn
AddHandler b.d4, del
RemoveHandler b.d1, void
RemoveHandler b.d2, str
RemoveHandler b.d3, dyn
RemoveHandler b.d4, del
End Sub
End Class
]]>
</file></compilation>
Dim dynamicCommonRef As MetadataReference = CreateEmptyCompilationWithReferences(
_dynamicCommonSrc,
references:={
MscorlibRef_v4_0_30316_17626,
_eventLibRef},
options:=TestOptions.ReleaseModule).EmitToImageReference()
Dim verifier = CompileAndVerifyOnWin8Only(
src,
allReferences:={
MscorlibRef_v4_0_30316_17626,
SystemCoreRef_v4_0_30319_17929,
CSharpRef,
_eventLibRef,
dynamicCommonRef})
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 931 (0x3a3)
.maxstack 4
.locals init (A V_0, //a
B V_1, //b
VB$AnonymousDelegate_0 V_2, //void
VB$AnonymousDelegate_1(Of String) V_3, //str
VB$AnonymousDelegate_2(Of Object) V_4, //dyn
VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate) V_5, //del
VB$AnonymousDelegate_0 V_6,
VB$AnonymousDelegate_1(Of String) V_7,
VB$AnonymousDelegate_2(Of Object) V_8,
VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate) V_9)
IL_0000: newobj "Sub A..ctor()"
IL_0005: stloc.0
IL_0006: newobj "Sub B..ctor()"
IL_000b: stloc.1
IL_000c: ldsfld "C._Closure$__.$I1-0 As <generated method>"
IL_0011: brfalse.s IL_001a
IL_0013: ldsfld "C._Closure$__.$I1-0 As <generated method>"
IL_0018: br.s IL_0030
IL_001a: ldsfld "C._Closure$__.$I As C._Closure$__"
IL_001f: ldftn "Sub C._Closure$__._Lambda$__1-0()"
IL_0025: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)"
IL_002a: dup
IL_002b: stsfld "C._Closure$__.$I1-0 As <generated method>"
IL_0030: stloc.2
IL_0031: ldsfld "C._Closure$__.$I1-1 As <generated method>"
IL_0036: brfalse.s IL_003f
IL_0038: ldsfld "C._Closure$__.$I1-1 As <generated method>"
IL_003d: br.s IL_0055
IL_003f: ldsfld "C._Closure$__.$I As C._Closure$__"
IL_0044: ldftn "Sub C._Closure$__._Lambda$__1-1(String)"
IL_004a: newobj "Sub VB$AnonymousDelegate_1(Of String)..ctor(Object, System.IntPtr)"
IL_004f: dup
IL_0050: stsfld "C._Closure$__.$I1-1 As <generated method>"
IL_0055: stloc.3
IL_0056: ldsfld "C._Closure$__.$I1-2 As <generated method>"
IL_005b: brfalse.s IL_0064
IL_005d: ldsfld "C._Closure$__.$I1-2 As <generated method>"
IL_0062: br.s IL_007a
IL_0064: ldsfld "C._Closure$__.$I As C._Closure$__"
IL_0069: ldftn "Sub C._Closure$__._Lambda$__1-2(Object)"
IL_006f: newobj "Sub VB$AnonymousDelegate_2(Of Object)..ctor(Object, System.IntPtr)"
IL_0074: dup
IL_0075: stsfld "C._Closure$__.$I1-2 As <generated method>"
IL_007a: stloc.s V_4
IL_007c: ldsfld "C._Closure$__.$I1-3 As <generated method>"
IL_0081: brfalse.s IL_008a
IL_0083: ldsfld "C._Closure$__.$I1-3 As <generated method>"
IL_0088: br.s IL_00a0
IL_008a: ldsfld "C._Closure$__.$I As C._Closure$__"
IL_008f: ldftn "Sub C._Closure$__._Lambda$__1-3(EventLibrary.voidVoidDelegate)"
IL_0095: newobj "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate)..ctor(Object, System.IntPtr)"
IL_009a: dup
IL_009b: stsfld "C._Closure$__.$I1-3 As <generated method>"
IL_00a0: stloc.s V_5
IL_00a2: ldloc.0
IL_00a3: dup
IL_00a4: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00aa: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00af: ldloc.0
IL_00b0: dup
IL_00b1: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00b7: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00bc: ldloc.2
IL_00bd: stloc.s V_6
IL_00bf: ldloc.s V_6
IL_00c1: brfalse.s IL_00d2
IL_00c3: ldloc.s V_6
IL_00c5: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_00cb: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_00d0: br.s IL_00d3
IL_00d2: ldnull
IL_00d3: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_00d8: ldloc.0
IL_00d9: dup
IL_00da: ldvirtftn "Sub A.add_d2(EventLibrary.voidStringDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00e0: newobj "Sub System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00e5: ldloc.0
IL_00e6: dup
IL_00e7: ldvirtftn "Sub A.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00ed: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00f2: ldloc.3
IL_00f3: stloc.s V_7
IL_00f5: ldloc.s V_7
IL_00f7: brfalse.s IL_0108
IL_00f9: ldloc.s V_7
IL_00fb: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)"
IL_0101: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)"
IL_0106: br.s IL_0109
IL_0108: ldnull
IL_0109: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidStringDelegate)(System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)"
IL_010e: ldloc.0
IL_010f: dup
IL_0110: ldvirtftn "Sub A.add_d3(EventLibrary.voidDynamicDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0116: newobj "Sub System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_011b: ldloc.0
IL_011c: dup
IL_011d: ldvirtftn "Sub A.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0123: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0128: ldloc.s V_4
IL_012a: stloc.s V_8
IL_012c: ldloc.s V_8
IL_012e: brfalse.s IL_013f
IL_0130: ldloc.s V_8
IL_0132: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)"
IL_0138: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)"
IL_013d: br.s IL_0140
IL_013f: ldnull
IL_0140: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)"
IL_0145: ldloc.0
IL_0146: dup
IL_0147: ldvirtftn "Sub A.add_d4(EventLibrary.voidDelegateDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_014d: newobj "Sub System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0152: ldloc.0
IL_0153: dup
IL_0154: ldvirtftn "Sub A.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_015a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_015f: ldloc.s V_5
IL_0161: stloc.s V_9
IL_0163: ldloc.s V_9
IL_0165: brfalse.s IL_0176
IL_0167: ldloc.s V_9
IL_0169: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)"
IL_016f: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)"
IL_0174: br.s IL_0177
IL_0176: ldnull
IL_0177: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)"
IL_017c: ldloc.0
IL_017d: dup
IL_017e: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0184: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0189: ldloc.2
IL_018a: stloc.s V_6
IL_018c: ldloc.s V_6
IL_018e: brfalse.s IL_019f
IL_0190: ldloc.s V_6
IL_0192: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_0198: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_019d: br.s IL_01a0
IL_019f: ldnull
IL_01a0: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_01a5: ldloc.0
IL_01a6: dup
IL_01a7: ldvirtftn "Sub A.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_01ad: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_01b2: ldloc.3
IL_01b3: stloc.s V_7
IL_01b5: ldloc.s V_7
IL_01b7: brfalse.s IL_01c8
IL_01b9: ldloc.s V_7
IL_01bb: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)"
IL_01c1: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)"
IL_01c6: br.s IL_01c9
IL_01c8: ldnull
IL_01c9: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidStringDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)"
IL_01ce: ldloc.0
IL_01cf: dup
IL_01d0: ldvirtftn "Sub A.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_01d6: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_01db: ldloc.s V_4
IL_01dd: stloc.s V_8
IL_01df: ldloc.s V_8
IL_01e1: brfalse.s IL_01f2
IL_01e3: ldloc.s V_8
IL_01e5: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)"
IL_01eb: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)"
IL_01f0: br.s IL_01f3
IL_01f2: ldnull
IL_01f3: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)"
IL_01f8: ldloc.0
IL_01f9: dup
IL_01fa: ldvirtftn "Sub A.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0200: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0205: ldloc.s V_5
IL_0207: stloc.s V_9
IL_0209: ldloc.s V_9
IL_020b: brfalse.s IL_021c
IL_020d: ldloc.s V_9
IL_020f: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)"
IL_0215: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)"
IL_021a: br.s IL_021d
IL_021c: ldnull
IL_021d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)"
IL_0222: ldloc.1
IL_0223: dup
IL_0224: ldvirtftn "Sub B.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_022a: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_022f: ldloc.1
IL_0230: dup
IL_0231: ldvirtftn "Sub B.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0237: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_023c: ldloc.2
IL_023d: stloc.s V_6
IL_023f: ldloc.s V_6
IL_0241: brfalse.s IL_0252
IL_0243: ldloc.s V_6
IL_0245: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_024b: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0250: br.s IL_0253
IL_0252: ldnull
IL_0253: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_0258: ldloc.1
IL_0259: dup
IL_025a: ldvirtftn "Sub B.add_d2(EventLibrary.voidStringDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0260: newobj "Sub System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0265: ldloc.1
IL_0266: dup
IL_0267: ldvirtftn "Sub B.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_026d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0272: ldloc.3
IL_0273: stloc.s V_7
IL_0275: ldloc.s V_7
IL_0277: brfalse.s IL_0288
IL_0279: ldloc.s V_7
IL_027b: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)"
IL_0281: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)"
IL_0286: br.s IL_0289
IL_0288: ldnull
IL_0289: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidStringDelegate)(System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)"
IL_028e: ldloc.1
IL_028f: dup
IL_0290: ldvirtftn "Sub B.add_d3(EventLibrary.voidDynamicDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0296: newobj "Sub System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_029b: ldloc.1
IL_029c: dup
IL_029d: ldvirtftn "Sub B.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_02a3: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_02a8: ldloc.s V_4
IL_02aa: stloc.s V_8
IL_02ac: ldloc.s V_8
IL_02ae: brfalse.s IL_02bf
IL_02b0: ldloc.s V_8
IL_02b2: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)"
IL_02b8: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)"
IL_02bd: br.s IL_02c0
IL_02bf: ldnull
IL_02c0: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)"
IL_02c5: ldloc.1
IL_02c6: dup
IL_02c7: ldvirtftn "Sub B.add_d4(EventLibrary.voidDelegateDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_02cd: newobj "Sub System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_02d2: ldloc.1
IL_02d3: dup
IL_02d4: ldvirtftn "Sub B.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_02da: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_02df: ldloc.s V_5
IL_02e1: stloc.s V_9
IL_02e3: ldloc.s V_9
IL_02e5: brfalse.s IL_02f6
IL_02e7: ldloc.s V_9
IL_02e9: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)"
IL_02ef: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)"
IL_02f4: br.s IL_02f7
IL_02f6: ldnull
IL_02f7: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)"
IL_02fc: ldloc.1
IL_02fd: dup
IL_02fe: ldvirtftn "Sub B.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0304: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0309: ldloc.2
IL_030a: stloc.s V_6
IL_030c: ldloc.s V_6
IL_030e: brfalse.s IL_031f
IL_0310: ldloc.s V_6
IL_0312: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_0318: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_031d: br.s IL_0320
IL_031f: ldnull
IL_0320: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_0325: ldloc.1
IL_0326: dup
IL_0327: ldvirtftn "Sub B.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_032d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0332: ldloc.3
IL_0333: stloc.s V_7
IL_0335: ldloc.s V_7
IL_0337: brfalse.s IL_0348
IL_0339: ldloc.s V_7
IL_033b: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)"
IL_0341: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)"
IL_0346: br.s IL_0349
IL_0348: ldnull
IL_0349: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidStringDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)"
IL_034e: ldloc.1
IL_034f: dup
IL_0350: ldvirtftn "Sub B.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0356: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_035b: ldloc.s V_4
IL_035d: stloc.s V_8
IL_035f: ldloc.s V_8
IL_0361: brfalse.s IL_0372
IL_0363: ldloc.s V_8
IL_0365: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)"
IL_036b: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)"
IL_0370: br.s IL_0373
IL_0372: ldnull
IL_0373: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)"
IL_0378: ldloc.1
IL_0379: dup
IL_037a: ldvirtftn "Sub B.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0380: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0385: ldloc.s V_5
IL_0387: stloc.s V_9
IL_0389: ldloc.s V_9
IL_038b: brfalse.s IL_039c
IL_038d: ldloc.s V_9
IL_038f: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)"
IL_0395: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)"
IL_039a: br.s IL_039d
IL_039c: ldnull
IL_039d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)"
IL_03a2: ret
}
]]>.Value)
End Sub
<Fact()>
Public Sub WinMdEventInternalStaticAccess()
Dim src =
<compilation>
<file name="a.vb">
<![CDATA[
Imports EventLibrary
Public Partial Class A
Implements I
' Remove a delegate from inside of the class
Public Shared Function Scenario1(a As A) As Boolean
Dim testDelegate = Sub()
End Sub
' Setup
AddHandler a.d1, testDelegate
RemoveHandler a.d1, testDelegate
Return a.d1Event Is Nothing
End Function
' Remove a delegate from inside of the class
Public Function Scenario2() As Boolean
Dim b As A = Me
Dim testDelegate = Sub()
End Sub
' Setup
AddHandler b.d1, testDelegate
RemoveHandler b.d1, testDelegate
Return b.d1Event Is Nothing
End Function
End Class
]]>
</file>
<file name="b.vb">
<%= _dynamicCommonSrc %>
</file>
</compilation>
Dim verifier = CompileAndVerifyOnWin8Only(
src,
allReferences:={
MscorlibRef_v4_0_30316_17626,
SystemCoreRef_v4_0_30319_17929,
_eventLibRef})
verifier.VerifyDiagnostics()
verifier.VerifyIL("A.Scenario1", <![CDATA[
{
// Code size 136 (0x88)
.maxstack 4
.locals init (VB$AnonymousDelegate_0 V_0, //testDelegate
VB$AnonymousDelegate_0 V_1)
IL_0000: ldsfld "A._Closure$__.$I1-0 As <generated method>"
IL_0005: brfalse.s IL_000e
IL_0007: ldsfld "A._Closure$__.$I1-0 As <generated method>"
IL_000c: br.s IL_0024
IL_000e: ldsfld "A._Closure$__.$I As A._Closure$__"
IL_0013: ldftn "Sub A._Closure$__._Lambda$__1-0()"
IL_0019: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)"
IL_001e: dup
IL_001f: stsfld "A._Closure$__.$I1-0 As <generated method>"
IL_0024: stloc.0
IL_0025: ldarg.0
IL_0026: dup
IL_0027: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_002d: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0032: ldarg.0
IL_0033: dup
IL_0034: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_003f: ldloc.0
IL_0040: stloc.1
IL_0041: ldloc.1
IL_0042: brfalse.s IL_0052
IL_0044: ldloc.1
IL_0045: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_004b: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0050: br.s IL_0053
IL_0052: ldnull
IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_0058: ldarg.0
IL_0059: dup
IL_005a: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0060: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0065: ldloc.0
IL_0066: stloc.1
IL_0067: ldloc.1
IL_0068: brfalse.s IL_0078
IL_006a: ldloc.1
IL_006b: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_0071: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0076: br.s IL_0079
IL_0078: ldnull
IL_0079: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_007e: ldarg.0
IL_007f: ldfld "A.d1Event As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of EventLibrary.voidVoidDelegate)"
IL_0084: ldnull
IL_0085: ceq
IL_0087: ret
}
]]>.Value)
verifier.VerifyIL("A.Scenario2", <![CDATA[
{
// Code size 138 (0x8a)
.maxstack 4
.locals init (A V_0, //b
VB$AnonymousDelegate_0 V_1, //testDelegate
VB$AnonymousDelegate_0 V_2)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldsfld "A._Closure$__.$I2-0 As <generated method>"
IL_0007: brfalse.s IL_0010
IL_0009: ldsfld "A._Closure$__.$I2-0 As <generated method>"
IL_000e: br.s IL_0026
IL_0010: ldsfld "A._Closure$__.$I As A._Closure$__"
IL_0015: ldftn "Sub A._Closure$__._Lambda$__2-0()"
IL_001b: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)"
IL_0020: dup
IL_0021: stsfld "A._Closure$__.$I2-0 As <generated method>"
IL_0026: stloc.1
IL_0027: ldloc.0
IL_0028: dup
IL_0029: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_002f: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0034: ldloc.0
IL_0035: dup
IL_0036: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0041: ldloc.1
IL_0042: stloc.2
IL_0043: ldloc.2
IL_0044: brfalse.s IL_0054
IL_0046: ldloc.2
IL_0047: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_004d: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0052: br.s IL_0055
IL_0054: ldnull
IL_0055: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_005a: ldloc.0
IL_005b: dup
IL_005c: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0062: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0067: ldloc.1
IL_0068: stloc.2
IL_0069: ldloc.2
IL_006a: brfalse.s IL_007a
IL_006c: ldloc.2
IL_006d: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_0073: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0078: br.s IL_007b
IL_007a: ldnull
IL_007b: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_0080: ldloc.0
IL_0081: ldfld "A.d1Event As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of EventLibrary.voidVoidDelegate)"
IL_0086: ldnull
IL_0087: ceq
IL_0089: ret
}
]]>.Value)
End Sub
''' <summary>
''' Verify that WinRT events compile into the IL that we
''' would expect.
''' </summary>
<ConditionalFact(GetType(OSVersionWin8))>
<WorkItem(18092, "https://github.com/dotnet/roslyn/issues/18092")>
Public Sub WinMdEvent()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Imports Windows.ApplicationModel
Imports Windows.UI.Xaml
Public Class abcdef
Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs)
End Sub
Public Sub goo()
Dim application As Application = Nothing
AddHandler application.Suspending, AddressOf Me.OnSuspending
RemoveHandler application.Suspending, AddressOf Me.OnSuspending
End Sub
Public Shared Sub Main()
Dim abcdef As abcdef = New abcdef()
abcdef.goo()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithWinRt(source)
Dim expectedIL = <output>
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (Windows.UI.Xaml.Application V_0) //application
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: dup
IL_0004: ldvirtftn "Sub Windows.UI.Xaml.Application.add_Suspending(Windows.UI.Xaml.SuspendingEventHandler) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000a: newobj "Sub System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000f: ldloc.0
IL_0010: dup
IL_0011: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0017: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001c: ldarg.0
IL_001d: ldftn "Sub abcdef.OnSuspending(Object, Windows.ApplicationModel.SuspendingEventArgs)"
IL_0023: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)"
IL_0028: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)"
IL_002d: ldloc.0
IL_002e: dup
IL_002f: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0035: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_003a: ldarg.0
IL_003b: ldftn "Sub abcdef.OnSuspending(Object, Windows.ApplicationModel.SuspendingEventArgs)"
IL_0041: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)"
IL_0046: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)"
IL_004b: ret
}
</output>
CompileAndVerify(compilation).VerifyIL("abcdef.goo", expectedIL.Value())
End Sub
<Fact()>
Public Sub WinMdSynthesizedEventDelegate()
Dim src =
<compilation>
<file name="c.vb">
Class C
Event E(a As Integer)
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(
src,
references:={MscorlibRef_v4_0_30316_17626},
options:=TestOptions.ReleaseWinMD)
comp.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E"))
End Sub
''' <summary>
''' Verify that WinRT events compile into the IL that we
''' would expect.
''' </summary>
Public Sub WinMdEventLambda()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Imports Windows.ApplicationModel
Imports Windows.UI.Xaml
Public Class abcdef
Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs)
End Sub
Public Sub goo()
Dim application As Application = Nothing
AddHandler application.Suspending, Sub(sender as Object, e As SuspendingEventArgs)
End Sub
End Sub
Public Shared Sub Main()
Dim abcdef As abcdef = New abcdef()
abcdef.goo()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithWinRt(source)
Dim expectedIL =
<output>
{
// Code size 66 (0x42)
.maxstack 4
.locals init (Windows.UI.Xaml.Application V_0) //application
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: dup
IL_0004: ldvirtftn "Sub Windows.UI.Xaml.Application.add_Suspending(Windows.UI.Xaml.SuspendingEventHandler) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000a: newobj "Sub System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000f: ldloc.0
IL_0010: dup
IL_0011: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0017: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001c: ldsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler"
IL_0021: brfalse.s IL_002a
IL_0023: ldsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler"
IL_0028: br.s IL_003c
IL_002a: ldnull
IL_002b: ldftn "Sub abcdef._Lambda$__1(Object, Object, Windows.ApplicationModel.SuspendingEventArgs)"
IL_0031: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)"
IL_0036: dup
IL_0037: stsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler"
IL_003c: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)"
IL_0041: ret
}
</output>
CompileAndVerify(compilation, verify:=If(OSVersion.IsWin8, Verification.Passes, Verification.Skipped)).VerifyIL("abcdef.goo", expectedIL.Value())
End Sub
<Fact>
Public Sub IsWindowsRuntimeEvent_EventSymbolSubtypes()
Dim il = <![CDATA[
.class public auto ansi sealed Event
extends [mscorlib]System.MulticastDelegate
{
.method private hidebysig specialname rtspecialname
instance void .ctor(object 'object',
native int 'method') runtime managed
{
}
.method public hidebysig newslot specialname virtual
instance void Invoke() runtime managed
{
}
} // end of class Event
.class interface public abstract auto ansi Interface`1<T>
{
.method public hidebysig newslot specialname abstract virtual
instance void add_Normal(class Event 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void remove_Normal(class Event 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken
add_WinRT([in] class Event 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void remove_WinRT([in] valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed
{
}
.event Event Normal
{
.addon instance void Interface`1::add_Normal(class Event)
.removeon instance void Interface`1::remove_Normal(class Event)
} // end of event I`1::Normal
.event Event WinRT
{
.addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken Interface`1::add_WinRT(class Event)
.removeon instance void Interface`1::remove_WinRT(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
}
} // end of class Interface
]]>
Dim source =
<compilation>
<file name="a.vb">
Class C
Implements [Interface](Of Integer)
Public Event Normal() Implements [Interface](Of Integer).Normal
Public Event WinRT() Implements [Interface](Of Integer).WinRT
End Class
</file>
</compilation>
Dim ilRef = CompileIL(il.Value)
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}))
comp.VerifyDiagnostics()
Dim interfaceType = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Interface")
Dim interfaceNormalEvent = interfaceType.GetMember(Of EventSymbol)("Normal")
Dim interfaceWinRTEvent = interfaceType.GetMember(Of EventSymbol)("WinRT")
Assert.IsType(Of PEEventSymbol)(interfaceNormalEvent)
Assert.IsType(Of PEEventSymbol)(interfaceWinRTEvent)
' Only depends on accessor signatures - doesn't care if it's in a windowsruntime type.
Assert.False(interfaceNormalEvent.IsWindowsRuntimeEvent)
Assert.True(interfaceWinRTEvent.IsWindowsRuntimeEvent)
Dim implementingType = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim implementingNormalEvent = implementingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("Normal"))
Dim implementingWinRTEvent = implementingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("WinRT"))
Assert.IsType(Of SourceEventSymbol)(implementingNormalEvent)
Assert.IsType(Of SourceEventSymbol)(implementingWinRTEvent)
' Based on kind of explicitly implemented interface event (other checks to be tested separately).
Assert.False(implementingNormalEvent.IsWindowsRuntimeEvent)
Assert.True(implementingWinRTEvent.IsWindowsRuntimeEvent)
Dim substitutedNormalEvent = implementingNormalEvent.ExplicitInterfaceImplementations.Single()
Dim substitutedWinRTEvent = implementingWinRTEvent.ExplicitInterfaceImplementations.Single()
Assert.IsType(Of SubstitutedEventSymbol)(substitutedNormalEvent)
Assert.IsType(Of SubstitutedEventSymbol)(substitutedWinRTEvent)
' Based on original definition.
Assert.False(substitutedNormalEvent.IsWindowsRuntimeEvent)
Assert.True(substitutedWinRTEvent.IsWindowsRuntimeEvent)
Dim retargetingAssembly = New RetargetingAssemblySymbol(DirectCast(comp.Assembly, SourceAssemblySymbol), isLinked:=False)
retargetingAssembly.SetCorLibrary(comp.Assembly.CorLibrary)
Dim retargetingType = retargetingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim retargetingNormalEvent = retargetingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("Normal"))
Dim retargetingWinRTEvent = retargetingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("WinRT"))
Assert.IsType(Of RetargetingEventSymbol)(retargetingNormalEvent)
Assert.IsType(Of RetargetingEventSymbol)(retargetingWinRTEvent)
' Based on underlying symbol.
Assert.False(retargetingNormalEvent.IsWindowsRuntimeEvent)
Assert.True(retargetingWinRTEvent.IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub IsWindowsRuntimeEvent_Source_OutputKind()
Dim source =
<compilation>
<file name="a.vb">
Class C
Public Event E As System.Action
Shared Sub Main()
End Sub
End Class
Interface I
Event E As System.Action
End Interface
</file>
</compilation>
For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, New VisualBasicCompilationOptions(kind))
comp.VerifyDiagnostics()
Dim [class] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim classEvent = [class].GetMember(Of EventSymbol)("E")
' Specifically test interfaces because they follow a different code path.
Dim [interface] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("I")
Dim interfaceEvent = [interface].GetMember(Of EventSymbol)("E")
Assert.Equal(kind.IsWindowsRuntime(), classEvent.IsWindowsRuntimeEvent)
Assert.Equal(kind.IsWindowsRuntime(), interfaceEvent.IsWindowsRuntimeEvent)
Next
End Sub
<Fact>
Public Sub IsWindowsRuntimeEvent_Source_InterfaceImplementation()
Dim source =
<compilation>
<file name="a.vb">
Class C
Implements I
Public Event Normal Implements I.Normal
Public Event WinRT Implements I.WinRT
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I"))
For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), New VisualBasicCompilationOptions(kind))
comp.VerifyDiagnostics()
Dim [class] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim normalEvent = [class].GetMember(Of EventSymbol)("Normal")
Dim winRTEvent = [class].GetMember(Of EventSymbol)("WinRT")
Assert.False(normalEvent.IsWindowsRuntimeEvent)
Assert.True(winRTEvent.IsWindowsRuntimeEvent)
Next
End Sub
<Fact>
Public Sub ERR_MixingWinRTAndNETEvents()
Dim source =
<compilation>
<file name="a.vb">
' Fine to implement more than one interface of the same WinRT-ness
Class C1
Implements I1, I2
Public Event Normal Implements I1.Normal, I2.Normal
Public Event WinRT Implements I1.WinRT, I2.WinRT
End Class
' Error to implement two interfaces of different WinRT-ness
Class C2
Implements I1, I2
Public Event Normal Implements I1.Normal, I2.WinRT
Public Event WinRT Implements I1.WinRT, I2.Normal
End Class
</file>
</compilation>
Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I1") + String.Format(_eventInterfaceILTemplate, "I2"))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), TestOptions.ReleaseDll)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.WinRT").WithArguments("Normal", "I2.WinRT", "I1.Normal"),
Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.Normal").WithArguments("WinRT", "I1.WinRT", "I2.Normal"))
Dim c1 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C1")
Assert.False(c1.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent)
Assert.True(c1.GetMember(Of EventSymbol)("WinRT").IsWindowsRuntimeEvent)
Dim c2 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C2")
Assert.False(c2.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent)
Assert.True(c2.GetMember(Of EventSymbol)("WinRT").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_MixingWinRTAndNETEvents_Multiple()
Dim source =
<compilation>
<file name="a.vb">
' Try going back and forth
Class C3
Implements I1, I2
Public Event Normal Implements I1.Normal, I1.WinRT, I2.Normal, I2.WinRT
End Class
</file>
</compilation>
Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I1") + String.Format(_eventInterfaceILTemplate, "I2"))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), TestOptions.ReleaseDll)
' CONSIDER: This is not how dev11 handles this scenario: it reports the first diagnostic, but then reports
' ERR_IdentNotMemberOfInterface4 (BC30401) and ERR_UnimplementedMember3 (BC30149) for all subsequent implemented members
' (side-effects of calling SetIsBad on the implementing event).
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I1.WinRT").WithArguments("Normal", "I1.WinRT", "I1.Normal"),
Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.WinRT").WithArguments("Normal", "I2.WinRT", "I1.Normal"))
Dim c3 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C3")
Assert.False(c3.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_WinRTEventWithoutDelegate_FieldLike()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Event E ' As System.Action
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)>
Public Sub ERR_WinRTEventWithoutDelegate_Custom()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E ' As System.Action
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
' Once the as-clause is missing, the event is parsed as a field-like event, hence the many syntax errors.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E"),
Diagnostic(ERRID.ERR_CustomEventRequiresAs, "Public Custom Event E ' As System.Action" + Environment.NewLine),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "AddHandler(value As System.Action)"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"),
Diagnostic(ERRID.ERR_InvalidEndAddHandler, "End AddHandler"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"),
Diagnostic(ERRID.ERR_InvalidEndRemoveHandler, "End RemoveHandler"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "RaiseEvent()"),
Diagnostic(ERRID.ERR_InvalidEndRaiseEvent, "End RaiseEvent"),
Diagnostic(ERRID.ERR_InvalidEndEvent, "End Event"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_WinRTEventWithoutDelegate_Implements()
Dim source =
<compilation>
<file name="a.vb">
Interface I
Event E1 As System.Action
Event E2 As System.Action
End Interface
Class Test
Implements I
Public Event E1 Implements I.E1
Public Custom Event E2 Implements I.E2
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
' Everything goes sideways for E2 since it custom events are required to have as-clauses.
' The key thing is that neither event reports ERR_WinRTEventWithoutDelegate.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_CustomEventRequiresAs, "Public Custom Event E2 Implements I.E2"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "AddHandler(value As System.Action)"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"),
Diagnostic(ERRID.ERR_InvalidEndAddHandler, "End AddHandler"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"),
Diagnostic(ERRID.ERR_InvalidEndRemoveHandler, "End RemoveHandler"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "RaiseEvent()"),
Diagnostic(ERRID.ERR_InvalidEndRaiseEvent, "End RaiseEvent"),
Diagnostic(ERRID.ERR_InvalidEndEvent, "End Event"),
Diagnostic(ERRID.ERR_EventImplMismatch5, "I.E2").WithArguments("Public Event E2 As ?", "Event E2 As System.Action", "I", "?", "System.Action"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E1").IsWindowsRuntimeEvent)
Assert.True(type.GetMember(Of EventSymbol)("E2").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_AddParamWrongForWinRT()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E As System.Action
AddHandler(value As System.Action(Of Integer))
Return Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_AddParamWrongForWinRT, "AddHandler(value As System.Action(Of Integer))"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_RemoveParamWrongForWinRT()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E As System.Action
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_RemoveParamWrongForWinRT, "RemoveHandler(value As System.Action)"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_RemoveParamWrongForWinRT_MissingTokenType()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E As System.Action
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD)
' This diagnostic is from binding the return type of the AddHandler, not from checking the parameter type
' of the ReturnHandler. The key point is that a cascading ERR_RemoveParamWrongForWinRT is not reported.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, <![CDATA[AddHandler(value As System.Action)
Return Nothing
End AddHandler]]>.Value.Replace(vbLf, vbCrLf)).WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", comp.AssemblyName + ".winmdobj"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_EventImplRemoveHandlerParamWrong()
Dim source =
<compilation>
<file name="a.vb">
Interface I
Event E As System.Action
end Interface
Class Test
Implements I
Public Custom Event F As System.Action Implements I.E
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_EventImplRemoveHandlerParamWrong, "RemoveHandler(value As System.Action)").WithArguments("F", "E", "I"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("F").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_EventImplRemoveHandlerParamWrong_MissingTokenType()
Dim source =
<compilation>
<file name="a.vb">
Interface I
Event E As System.Action
end Interface
Class Test
Implements I
Public Custom Event F As System.Action Implements I.E
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD)
' This diagnostic is from binding the return type of the AddHandler, not from checking the parameter type
' of the ReturnHandler. The key point is that a cascading ERR_RemoveParamWrongForWinRT is not reported.
Dim outputName As String = comp.AssemblyName + ".winmdobj"
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, <![CDATA[AddHandler(value As System.Action)
Return Nothing
End AddHandler]]>.Value.Replace(vbLf, vbCrLf)).WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("F").IsWindowsRuntimeEvent)
End Sub
' Confirms that we're getting decl errors from the backing field.
<Fact>
Public Sub MissingTokenTableType()
Dim source =
<compilation name="test">
<file name="a.vb">
Class Test
Event E As System.Action
End Class
Namespace System.Runtime.InteropServices.WindowsRuntime
Public Structure EventRegistrationToken
End Structure
End Namespace
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD)
AssertTheseDeclarationDiagnostics(comp, <errors><![CDATA[
BC31091: Import of type 'EventRegistrationTokenTable(Of )' from assembly or module 'test.winmdobj' failed.
Event E As System.Action
~
]]></errors>)
End Sub
<Fact>
Public Sub ReturnLocal()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E As System.Action
AddHandler(value As System.Action)
add_E = Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
Dim v = CompileAndVerify(comp)
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Dim eventSymbol As EventSymbol = type.GetMember(Of EventSymbol)("E")
Assert.True(eventSymbol.IsWindowsRuntimeEvent)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim syntax = tree.GetRoot().DescendantNodes().OfType(Of AssignmentStatementSyntax).Single().Left
Dim symbol = model.GetSymbolInfo(syntax).Symbol
Assert.Equal(SymbolKind.Local, symbol.Kind)
Assert.Equal(eventSymbol.AddMethod.ReturnType, DirectCast(symbol, LocalSymbol).Type)
Assert.Equal(eventSymbol.AddMethod.Name, symbol.Name)
v.VerifyIL("Test.add_E", "
{
// Code size 10 (0xa)
.maxstack 1
.locals init (System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken V_0) //add_E
IL_0000: ldloca.s V_0
IL_0002: initobj ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken""
IL_0008: ldloc.0
IL_0009: ret
}
")
End Sub
<Fact>
Public Sub AccessorSignatures()
Dim source =
<compilation>
<file name="a.vb">
Class Test
public event FieldLike As System.Action
Public Custom Event Custom As System.Action
AddHandler(value As System.Action)
Throw New System.Exception()
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Public Shared Sub Main()
End Sub
End Class
</file>
</compilation>
For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, New VisualBasicCompilationOptions(kind))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Dim fieldLikeEvent = type.GetMember(Of EventSymbol)("FieldLike")
Dim customEvent = type.GetMember(Of EventSymbol)("Custom")
If kind.IsWindowsRuntime() Then
comp.VerifyDiagnostics()
VerifyWinRTEventShape(customEvent, comp)
VerifyWinRTEventShape(fieldLikeEvent, comp)
Else
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_AddRemoveParamNotEventType, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"))
VerifyNormalEventShape(customEvent, comp)
VerifyNormalEventShape(fieldLikeEvent, comp)
End If
Next
End Sub
<Fact()>
Public Sub HandlerSemanticInfo()
Dim source =
<compilation>
<file name="a.vb">
Class C
Event QQQ As System.Action
Sub Test()
AddHandler QQQ, Nothing
RemoveHandler QQQ, Nothing
RaiseEvent QQQ()
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics()
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim references = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax).Where(Function(id) id.Identifier.ValueText = "QQQ").ToArray()
Assert.Equal(3, references.Count) ' Decl is just a token
Dim eventSymbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of EventSymbol)("QQQ")
AssertEx.All(references, Function(ref) model.GetSymbolInfo(ref).Symbol.Equals(eventSymbol))
Dim actionType = comp.GetWellKnownType(WellKnownType.System_Action)
Assert.Equal(actionType, eventSymbol.Type)
AssertEx.All(references, Function(ref) model.GetTypeInfo(ref).Type.Equals(actionType))
End Sub
<Fact>
Public Sub NoReturnFromAddHandler()
Dim source =
<compilation>
<file name="a.vb">
Delegate Sub EventDelegate()
Class Events
Custom Event E As eventdelegate
AddHandler(value As eventdelegate)
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
' Note the distinct new error code.
comp.VerifyDiagnostics(
Diagnostic(ERRID.WRN_DefAsgNoRetValWinRtEventVal1, "End AddHandler").WithArguments("E"))
End Sub
Private Shared Sub VerifyWinRTEventShape([event] As EventSymbol, compilation As VisualBasicCompilation)
Assert.True([event].IsWindowsRuntimeEvent)
Dim eventType = [event].Type
Dim tokenType = compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken)
Assert.NotNull(tokenType)
Dim voidType = compilation.GetSpecialType(SpecialType.System_Void)
Assert.NotNull(voidType)
Dim addMethod = [event].AddMethod
Assert.Equal(tokenType, addMethod.ReturnType)
Assert.False(addMethod.IsSub)
Assert.Equal(1, addMethod.ParameterCount)
Assert.Equal(eventType, addMethod.Parameters.Single().Type)
Dim removeMethod = [event].RemoveMethod
Assert.Equal(voidType, removeMethod.ReturnType)
Assert.True(removeMethod.IsSub)
Assert.Equal(1, removeMethod.ParameterCount)
Assert.Equal(tokenType, removeMethod.Parameters.Single().Type)
If [event].HasAssociatedField Then
Dim expectedFieldType = compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T).Construct(eventType)
Assert.Equal(expectedFieldType, [event].AssociatedField.Type)
Else
Assert.Null([event].AssociatedField)
End If
End Sub
Private Shared Sub VerifyNormalEventShape([event] As EventSymbol, compilation As VisualBasicCompilation)
Assert.False([event].IsWindowsRuntimeEvent)
Dim eventType = [event].Type
Dim voidType = compilation.GetSpecialType(SpecialType.System_Void)
Assert.NotNull(voidType)
Dim addMethod = [event].AddMethod
Assert.Equal(voidType, addMethod.ReturnType)
Assert.True(addMethod.IsSub)
Assert.Equal(1, addMethod.ParameterCount)
Assert.Equal(eventType, addMethod.Parameters.Single().Type)
Dim removeMethod = [event].RemoveMethod
Assert.Equal(voidType, removeMethod.ReturnType)
Assert.True(removeMethod.IsSub)
Assert.Equal(1, removeMethod.ParameterCount)
If [event].HasAssociatedField Then
' Otherwise, we had to be explicit and we favored WinRT because that's what we're testing.
Assert.Equal(eventType, removeMethod.Parameters.Single().Type)
End If
If [event].HasAssociatedField Then
Assert.Equal(eventType, [event].AssociatedField.Type)
Else
Assert.Null([event].AssociatedField)
End If
End Sub
<Fact>
Public Sub BackingField()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event CustomEvent As System.Action
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Public Event FieldLikeEvent As System.Action
Sub Test()
dim f1 = CustomEventEvent
dim f2 = FieldLikeEventEvent
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
' No backing field for custom event.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_NameNotDeclared1, "CustomEventEvent").WithArguments("CustomEventEvent"))
Dim fieldLikeEvent = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test").GetMember(Of EventSymbol)("FieldLikeEvent")
Dim tokenTableType = comp.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim syntax = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Single(Function(id) id.Identifier.ValueText = "FieldLikeEventEvent")
Dim symbol = model.GetSymbolInfo(syntax).Symbol
Assert.Equal(SymbolKind.Field, symbol.Kind)
Assert.Equal(fieldLikeEvent, DirectCast(symbol, FieldSymbol).AssociatedSymbol)
Dim type = model.GetTypeInfo(syntax).Type
Assert.Equal(tokenTableType, type.OriginalDefinition)
Assert.Equal(fieldLikeEvent.Type, DirectCast(type, NamedTypeSymbol).TypeArguments.Single())
End Sub
<Fact()>
Public Sub RaiseBaseEventedFromDerivedNestedTypes()
Dim source =
<compilation>
<file name="filename.vb">
Delegate Sub D()
Class C1
Event HelloWorld As D
Class C2
Inherits C1
Sub t
RaiseEvent HelloWorld
End Sub
End Class
End Class
</file>
</compilation>
CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD).VerifyDiagnostics()
End Sub
End Class
End Namespace
| ' 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.
Imports System.Linq
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata
Public Class WinMdEventTest
Inherits BasicTestBase
Private ReadOnly _eventInterfaceILTemplate As String = <![CDATA[
.class interface public abstract auto ansi {0}
{{
.method public hidebysig newslot specialname abstract virtual
instance void add_Normal(class [mscorlib]System.Action 'value') cil managed
{{
}}
.method public hidebysig newslot specialname abstract virtual
instance void remove_Normal(class [mscorlib]System.Action 'value') cil managed
{{
}}
.method public hidebysig newslot specialname abstract virtual
instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken
add_WinRT([in] class [mscorlib]System.Action 'value') cil managed
{{
}}
.method public hidebysig newslot specialname abstract virtual
instance void remove_WinRT([in] valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed
{{
}}
.event class [mscorlib]System.Action Normal
{{
.addon instance void {0}::add_Normal(class [mscorlib]System.Action)
.removeon instance void {0}::remove_Normal(class [mscorlib]System.Action)
}}
.event class [mscorlib]System.Action WinRT
{{
.addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken {0}::add_WinRT(class [mscorlib]System.Action)
.removeon instance void {0}::remove_WinRT(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
}}
}} // end of class {0}
]]>.Value
Private ReadOnly _eventLibRef As MetadataReference
Private ReadOnly _dynamicCommonSrc As XElement =
<compilation>
<file name="dynamic_common.vb">
<![CDATA[
Imports System.Runtime.InteropServices.WindowsRuntime
Imports EventLibrary
Public Partial Class A
Implements I
Public Event d1 As voidVoidDelegate Implements I.d1
Public Event d2 As voidStringDelegate Implements I.d2
Public Event d3 As voidDynamicDelegate Implements I.d3
Public Event d4 As voidDelegateDelegate Implements I.d4
End Class
Public Partial Class B
Implements I
Private voidTable As New EventRegistrationTokenTable(Of voidVoidDelegate)()
Private voidStringTable As New EventRegistrationTokenTable(Of voidStringDelegate)()
Private voidDynamicTable As New EventRegistrationTokenTable(Of voidDynamicDelegate)()
Private voidDelegateTable As New EventRegistrationTokenTable(Of voidDelegateDelegate)()
Public Custom Event d1 As voidVoidDelegate Implements I.d1
AddHandler(value As voidVoidDelegate)
Return voidTable.AddEventHandler(value)
End AddHandler
RemoveHandler(value As EventRegistrationToken)
voidTable.RemoveEventHandler(value)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Public Custom Event d2 As voidStringDelegate Implements I.d2
AddHandler(value As voidStringDelegate)
Return voidStringTable.AddEventHandler(value)
End AddHandler
RemoveHandler(value As EventRegistrationToken)
voidStringTable.RemoveEventHandler(value)
End RemoveHandler
RaiseEvent(s As String)
End RaiseEvent
End Event
Public Custom Event d3 As voidDynamicDelegate Implements I.d3
AddHandler(value As voidDynamicDelegate)
Return voidDynamicTable.AddEventHandler(value)
End AddHandler
RemoveHandler(value As EventRegistrationToken)
voidDynamicTable.RemoveEventHandler(value)
End RemoveHandler
RaiseEvent(d As Object)
End RaiseEvent
End Event
Public Custom Event d4 As voidDelegateDelegate Implements I.d4
AddHandler(value As voidDelegateDelegate)
Return voidDelegateTable.AddEventHandler(value)
End AddHandler
RemoveHandler(value As EventRegistrationToken)
voidDelegateTable.RemoveEventHandler(value)
End RemoveHandler
RaiseEvent([delegate] As voidVoidDelegate)
End RaiseEvent
End Event
End Class
]]>
</file>
</compilation>
Public Sub New()
' The following two libraries are shrunk code pulled from
' corresponding files in the csharp5 legacy tests
Dim eventLibSrc =
<compilation><file name="EventLibrary.vb">
<![CDATA[
Namespace EventLibrary
Public Delegate Sub voidVoidDelegate()
Public Delegate Sub voidStringDelegate(s As String)
Public Delegate Sub voidDynamicDelegate(d As Object)
Public Delegate Sub voidDelegateDelegate([delegate] As voidVoidDelegate)
Public Interface I
Event d1 As voidVoidDelegate
Event d2 As voidStringDelegate
Event d3 As voidDynamicDelegate
Event d4 As voidDelegateDelegate
End Interface
End Namespace
]]>
</file></compilation>
_eventLibRef = CreateEmptyCompilationWithReferences(
eventLibSrc,
references:={MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929},
options:=TestOptions.ReleaseWinMD).EmitToImageReference()
End Sub
<Fact()>
Public Sub WinMdExternalEventTests()
Dim src =
<compilation><file name="c.vb">
<![CDATA[
Imports EventLibrary
Class C
Sub Main()
Dim a = new A()
Dim b = new B()
Dim void = Sub()
End Sub
Dim str = Sub(s As String)
End Sub
Dim dyn = Sub(d As Object)
End Sub
Dim del = Sub([delegate] As voidVoidDelegate)
End Sub
AddHandler a.d1, void
AddHandler a.d2, str
AddHandler a.d3, dyn
AddHandler a.d4, del
RemoveHandler a.d1, void
RemoveHandler a.d2, str
RemoveHandler a.d3, dyn
RemoveHandler a.d4, del
AddHandler b.d1, void
AddHandler b.d2, str
AddHandler b.d3, dyn
AddHandler b.d4, del
RemoveHandler b.d1, void
RemoveHandler b.d2, str
RemoveHandler b.d3, dyn
RemoveHandler b.d4, del
End Sub
End Class
]]>
</file></compilation>
Dim dynamicCommonRef As MetadataReference = CreateEmptyCompilationWithReferences(
_dynamicCommonSrc,
references:={
MscorlibRef_v4_0_30316_17626,
_eventLibRef},
options:=TestOptions.ReleaseModule).EmitToImageReference()
Dim verifier = CompileAndVerifyOnWin8Only(
src,
allReferences:={
MscorlibRef_v4_0_30316_17626,
SystemCoreRef_v4_0_30319_17929,
CSharpRef,
_eventLibRef,
dynamicCommonRef})
verifier.VerifyIL("C.Main", <![CDATA[
{
// Code size 931 (0x3a3)
.maxstack 4
.locals init (A V_0, //a
B V_1, //b
VB$AnonymousDelegate_0 V_2, //void
VB$AnonymousDelegate_1(Of String) V_3, //str
VB$AnonymousDelegate_2(Of Object) V_4, //dyn
VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate) V_5, //del
VB$AnonymousDelegate_0 V_6,
VB$AnonymousDelegate_1(Of String) V_7,
VB$AnonymousDelegate_2(Of Object) V_8,
VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate) V_9)
IL_0000: newobj "Sub A..ctor()"
IL_0005: stloc.0
IL_0006: newobj "Sub B..ctor()"
IL_000b: stloc.1
IL_000c: ldsfld "C._Closure$__.$I1-0 As <generated method>"
IL_0011: brfalse.s IL_001a
IL_0013: ldsfld "C._Closure$__.$I1-0 As <generated method>"
IL_0018: br.s IL_0030
IL_001a: ldsfld "C._Closure$__.$I As C._Closure$__"
IL_001f: ldftn "Sub C._Closure$__._Lambda$__1-0()"
IL_0025: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)"
IL_002a: dup
IL_002b: stsfld "C._Closure$__.$I1-0 As <generated method>"
IL_0030: stloc.2
IL_0031: ldsfld "C._Closure$__.$I1-1 As <generated method>"
IL_0036: brfalse.s IL_003f
IL_0038: ldsfld "C._Closure$__.$I1-1 As <generated method>"
IL_003d: br.s IL_0055
IL_003f: ldsfld "C._Closure$__.$I As C._Closure$__"
IL_0044: ldftn "Sub C._Closure$__._Lambda$__1-1(String)"
IL_004a: newobj "Sub VB$AnonymousDelegate_1(Of String)..ctor(Object, System.IntPtr)"
IL_004f: dup
IL_0050: stsfld "C._Closure$__.$I1-1 As <generated method>"
IL_0055: stloc.3
IL_0056: ldsfld "C._Closure$__.$I1-2 As <generated method>"
IL_005b: brfalse.s IL_0064
IL_005d: ldsfld "C._Closure$__.$I1-2 As <generated method>"
IL_0062: br.s IL_007a
IL_0064: ldsfld "C._Closure$__.$I As C._Closure$__"
IL_0069: ldftn "Sub C._Closure$__._Lambda$__1-2(Object)"
IL_006f: newobj "Sub VB$AnonymousDelegate_2(Of Object)..ctor(Object, System.IntPtr)"
IL_0074: dup
IL_0075: stsfld "C._Closure$__.$I1-2 As <generated method>"
IL_007a: stloc.s V_4
IL_007c: ldsfld "C._Closure$__.$I1-3 As <generated method>"
IL_0081: brfalse.s IL_008a
IL_0083: ldsfld "C._Closure$__.$I1-3 As <generated method>"
IL_0088: br.s IL_00a0
IL_008a: ldsfld "C._Closure$__.$I As C._Closure$__"
IL_008f: ldftn "Sub C._Closure$__._Lambda$__1-3(EventLibrary.voidVoidDelegate)"
IL_0095: newobj "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate)..ctor(Object, System.IntPtr)"
IL_009a: dup
IL_009b: stsfld "C._Closure$__.$I1-3 As <generated method>"
IL_00a0: stloc.s V_5
IL_00a2: ldloc.0
IL_00a3: dup
IL_00a4: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00aa: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00af: ldloc.0
IL_00b0: dup
IL_00b1: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00b7: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00bc: ldloc.2
IL_00bd: stloc.s V_6
IL_00bf: ldloc.s V_6
IL_00c1: brfalse.s IL_00d2
IL_00c3: ldloc.s V_6
IL_00c5: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_00cb: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_00d0: br.s IL_00d3
IL_00d2: ldnull
IL_00d3: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_00d8: ldloc.0
IL_00d9: dup
IL_00da: ldvirtftn "Sub A.add_d2(EventLibrary.voidStringDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00e0: newobj "Sub System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00e5: ldloc.0
IL_00e6: dup
IL_00e7: ldvirtftn "Sub A.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00ed: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00f2: ldloc.3
IL_00f3: stloc.s V_7
IL_00f5: ldloc.s V_7
IL_00f7: brfalse.s IL_0108
IL_00f9: ldloc.s V_7
IL_00fb: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)"
IL_0101: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)"
IL_0106: br.s IL_0109
IL_0108: ldnull
IL_0109: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidStringDelegate)(System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)"
IL_010e: ldloc.0
IL_010f: dup
IL_0110: ldvirtftn "Sub A.add_d3(EventLibrary.voidDynamicDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0116: newobj "Sub System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_011b: ldloc.0
IL_011c: dup
IL_011d: ldvirtftn "Sub A.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0123: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0128: ldloc.s V_4
IL_012a: stloc.s V_8
IL_012c: ldloc.s V_8
IL_012e: brfalse.s IL_013f
IL_0130: ldloc.s V_8
IL_0132: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)"
IL_0138: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)"
IL_013d: br.s IL_0140
IL_013f: ldnull
IL_0140: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)"
IL_0145: ldloc.0
IL_0146: dup
IL_0147: ldvirtftn "Sub A.add_d4(EventLibrary.voidDelegateDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_014d: newobj "Sub System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0152: ldloc.0
IL_0153: dup
IL_0154: ldvirtftn "Sub A.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_015a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_015f: ldloc.s V_5
IL_0161: stloc.s V_9
IL_0163: ldloc.s V_9
IL_0165: brfalse.s IL_0176
IL_0167: ldloc.s V_9
IL_0169: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)"
IL_016f: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)"
IL_0174: br.s IL_0177
IL_0176: ldnull
IL_0177: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)"
IL_017c: ldloc.0
IL_017d: dup
IL_017e: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0184: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0189: ldloc.2
IL_018a: stloc.s V_6
IL_018c: ldloc.s V_6
IL_018e: brfalse.s IL_019f
IL_0190: ldloc.s V_6
IL_0192: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_0198: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_019d: br.s IL_01a0
IL_019f: ldnull
IL_01a0: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_01a5: ldloc.0
IL_01a6: dup
IL_01a7: ldvirtftn "Sub A.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_01ad: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_01b2: ldloc.3
IL_01b3: stloc.s V_7
IL_01b5: ldloc.s V_7
IL_01b7: brfalse.s IL_01c8
IL_01b9: ldloc.s V_7
IL_01bb: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)"
IL_01c1: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)"
IL_01c6: br.s IL_01c9
IL_01c8: ldnull
IL_01c9: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidStringDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)"
IL_01ce: ldloc.0
IL_01cf: dup
IL_01d0: ldvirtftn "Sub A.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_01d6: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_01db: ldloc.s V_4
IL_01dd: stloc.s V_8
IL_01df: ldloc.s V_8
IL_01e1: brfalse.s IL_01f2
IL_01e3: ldloc.s V_8
IL_01e5: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)"
IL_01eb: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)"
IL_01f0: br.s IL_01f3
IL_01f2: ldnull
IL_01f3: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)"
IL_01f8: ldloc.0
IL_01f9: dup
IL_01fa: ldvirtftn "Sub A.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0200: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0205: ldloc.s V_5
IL_0207: stloc.s V_9
IL_0209: ldloc.s V_9
IL_020b: brfalse.s IL_021c
IL_020d: ldloc.s V_9
IL_020f: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)"
IL_0215: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)"
IL_021a: br.s IL_021d
IL_021c: ldnull
IL_021d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)"
IL_0222: ldloc.1
IL_0223: dup
IL_0224: ldvirtftn "Sub B.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_022a: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_022f: ldloc.1
IL_0230: dup
IL_0231: ldvirtftn "Sub B.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0237: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_023c: ldloc.2
IL_023d: stloc.s V_6
IL_023f: ldloc.s V_6
IL_0241: brfalse.s IL_0252
IL_0243: ldloc.s V_6
IL_0245: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_024b: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0250: br.s IL_0253
IL_0252: ldnull
IL_0253: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_0258: ldloc.1
IL_0259: dup
IL_025a: ldvirtftn "Sub B.add_d2(EventLibrary.voidStringDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0260: newobj "Sub System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0265: ldloc.1
IL_0266: dup
IL_0267: ldvirtftn "Sub B.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_026d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0272: ldloc.3
IL_0273: stloc.s V_7
IL_0275: ldloc.s V_7
IL_0277: brfalse.s IL_0288
IL_0279: ldloc.s V_7
IL_027b: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)"
IL_0281: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)"
IL_0286: br.s IL_0289
IL_0288: ldnull
IL_0289: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidStringDelegate)(System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)"
IL_028e: ldloc.1
IL_028f: dup
IL_0290: ldvirtftn "Sub B.add_d3(EventLibrary.voidDynamicDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0296: newobj "Sub System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_029b: ldloc.1
IL_029c: dup
IL_029d: ldvirtftn "Sub B.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_02a3: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_02a8: ldloc.s V_4
IL_02aa: stloc.s V_8
IL_02ac: ldloc.s V_8
IL_02ae: brfalse.s IL_02bf
IL_02b0: ldloc.s V_8
IL_02b2: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)"
IL_02b8: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)"
IL_02bd: br.s IL_02c0
IL_02bf: ldnull
IL_02c0: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)"
IL_02c5: ldloc.1
IL_02c6: dup
IL_02c7: ldvirtftn "Sub B.add_d4(EventLibrary.voidDelegateDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_02cd: newobj "Sub System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_02d2: ldloc.1
IL_02d3: dup
IL_02d4: ldvirtftn "Sub B.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_02da: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_02df: ldloc.s V_5
IL_02e1: stloc.s V_9
IL_02e3: ldloc.s V_9
IL_02e5: brfalse.s IL_02f6
IL_02e7: ldloc.s V_9
IL_02e9: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)"
IL_02ef: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)"
IL_02f4: br.s IL_02f7
IL_02f6: ldnull
IL_02f7: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)"
IL_02fc: ldloc.1
IL_02fd: dup
IL_02fe: ldvirtftn "Sub B.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0304: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0309: ldloc.2
IL_030a: stloc.s V_6
IL_030c: ldloc.s V_6
IL_030e: brfalse.s IL_031f
IL_0310: ldloc.s V_6
IL_0312: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_0318: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_031d: br.s IL_0320
IL_031f: ldnull
IL_0320: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_0325: ldloc.1
IL_0326: dup
IL_0327: ldvirtftn "Sub B.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_032d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0332: ldloc.3
IL_0333: stloc.s V_7
IL_0335: ldloc.s V_7
IL_0337: brfalse.s IL_0348
IL_0339: ldloc.s V_7
IL_033b: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)"
IL_0341: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)"
IL_0346: br.s IL_0349
IL_0348: ldnull
IL_0349: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidStringDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)"
IL_034e: ldloc.1
IL_034f: dup
IL_0350: ldvirtftn "Sub B.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0356: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_035b: ldloc.s V_4
IL_035d: stloc.s V_8
IL_035f: ldloc.s V_8
IL_0361: brfalse.s IL_0372
IL_0363: ldloc.s V_8
IL_0365: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)"
IL_036b: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)"
IL_0370: br.s IL_0373
IL_0372: ldnull
IL_0373: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)"
IL_0378: ldloc.1
IL_0379: dup
IL_037a: ldvirtftn "Sub B.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0380: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0385: ldloc.s V_5
IL_0387: stloc.s V_9
IL_0389: ldloc.s V_9
IL_038b: brfalse.s IL_039c
IL_038d: ldloc.s V_9
IL_038f: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)"
IL_0395: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)"
IL_039a: br.s IL_039d
IL_039c: ldnull
IL_039d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)"
IL_03a2: ret
}
]]>.Value)
End Sub
<Fact()>
Public Sub WinMdEventInternalStaticAccess()
Dim src =
<compilation>
<file name="a.vb">
<![CDATA[
Imports EventLibrary
Public Partial Class A
Implements I
' Remove a delegate from inside of the class
Public Shared Function Scenario1(a As A) As Boolean
Dim testDelegate = Sub()
End Sub
' Setup
AddHandler a.d1, testDelegate
RemoveHandler a.d1, testDelegate
Return a.d1Event Is Nothing
End Function
' Remove a delegate from inside of the class
Public Function Scenario2() As Boolean
Dim b As A = Me
Dim testDelegate = Sub()
End Sub
' Setup
AddHandler b.d1, testDelegate
RemoveHandler b.d1, testDelegate
Return b.d1Event Is Nothing
End Function
End Class
]]>
</file>
<file name="b.vb">
<%= _dynamicCommonSrc %>
</file>
</compilation>
Dim verifier = CompileAndVerifyOnWin8Only(
src,
allReferences:={
MscorlibRef_v4_0_30316_17626,
SystemCoreRef_v4_0_30319_17929,
_eventLibRef})
verifier.VerifyDiagnostics()
verifier.VerifyIL("A.Scenario1", <![CDATA[
{
// Code size 136 (0x88)
.maxstack 4
.locals init (VB$AnonymousDelegate_0 V_0, //testDelegate
VB$AnonymousDelegate_0 V_1)
IL_0000: ldsfld "A._Closure$__.$I1-0 As <generated method>"
IL_0005: brfalse.s IL_000e
IL_0007: ldsfld "A._Closure$__.$I1-0 As <generated method>"
IL_000c: br.s IL_0024
IL_000e: ldsfld "A._Closure$__.$I As A._Closure$__"
IL_0013: ldftn "Sub A._Closure$__._Lambda$__1-0()"
IL_0019: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)"
IL_001e: dup
IL_001f: stsfld "A._Closure$__.$I1-0 As <generated method>"
IL_0024: stloc.0
IL_0025: ldarg.0
IL_0026: dup
IL_0027: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_002d: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0032: ldarg.0
IL_0033: dup
IL_0034: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_003f: ldloc.0
IL_0040: stloc.1
IL_0041: ldloc.1
IL_0042: brfalse.s IL_0052
IL_0044: ldloc.1
IL_0045: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_004b: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0050: br.s IL_0053
IL_0052: ldnull
IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_0058: ldarg.0
IL_0059: dup
IL_005a: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0060: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0065: ldloc.0
IL_0066: stloc.1
IL_0067: ldloc.1
IL_0068: brfalse.s IL_0078
IL_006a: ldloc.1
IL_006b: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_0071: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0076: br.s IL_0079
IL_0078: ldnull
IL_0079: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_007e: ldarg.0
IL_007f: ldfld "A.d1Event As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of EventLibrary.voidVoidDelegate)"
IL_0084: ldnull
IL_0085: ceq
IL_0087: ret
}
]]>.Value)
verifier.VerifyIL("A.Scenario2", <![CDATA[
{
// Code size 138 (0x8a)
.maxstack 4
.locals init (A V_0, //b
VB$AnonymousDelegate_0 V_1, //testDelegate
VB$AnonymousDelegate_0 V_2)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldsfld "A._Closure$__.$I2-0 As <generated method>"
IL_0007: brfalse.s IL_0010
IL_0009: ldsfld "A._Closure$__.$I2-0 As <generated method>"
IL_000e: br.s IL_0026
IL_0010: ldsfld "A._Closure$__.$I As A._Closure$__"
IL_0015: ldftn "Sub A._Closure$__._Lambda$__2-0()"
IL_001b: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)"
IL_0020: dup
IL_0021: stsfld "A._Closure$__.$I2-0 As <generated method>"
IL_0026: stloc.1
IL_0027: ldloc.0
IL_0028: dup
IL_0029: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_002f: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0034: ldloc.0
IL_0035: dup
IL_0036: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0041: ldloc.1
IL_0042: stloc.2
IL_0043: ldloc.2
IL_0044: brfalse.s IL_0054
IL_0046: ldloc.2
IL_0047: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_004d: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0052: br.s IL_0055
IL_0054: ldnull
IL_0055: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_005a: ldloc.0
IL_005b: dup
IL_005c: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0062: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0067: ldloc.1
IL_0068: stloc.2
IL_0069: ldloc.2
IL_006a: brfalse.s IL_007a
IL_006c: ldloc.2
IL_006d: ldftn "Sub VB$AnonymousDelegate_0.Invoke()"
IL_0073: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)"
IL_0078: br.s IL_007b
IL_007a: ldnull
IL_007b: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)"
IL_0080: ldloc.0
IL_0081: ldfld "A.d1Event As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of EventLibrary.voidVoidDelegate)"
IL_0086: ldnull
IL_0087: ceq
IL_0089: ret
}
]]>.Value)
End Sub
''' <summary>
''' Verify that WinRT events compile into the IL that we
''' would expect.
''' </summary>
<ConditionalFact(GetType(OSVersionWin8))>
<WorkItem(18092, "https://github.com/dotnet/roslyn/issues/18092")>
Public Sub WinMdEvent()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Imports Windows.ApplicationModel
Imports Windows.UI.Xaml
Public Class abcdef
Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs)
End Sub
Public Sub goo()
Dim application As Application = Nothing
AddHandler application.Suspending, AddressOf Me.OnSuspending
RemoveHandler application.Suspending, AddressOf Me.OnSuspending
End Sub
Public Shared Sub Main()
Dim abcdef As abcdef = New abcdef()
abcdef.goo()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithWinRt(source)
Dim expectedIL = <output>
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (Windows.UI.Xaml.Application V_0) //application
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: dup
IL_0004: ldvirtftn "Sub Windows.UI.Xaml.Application.add_Suspending(Windows.UI.Xaml.SuspendingEventHandler) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000a: newobj "Sub System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000f: ldloc.0
IL_0010: dup
IL_0011: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0017: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001c: ldarg.0
IL_001d: ldftn "Sub abcdef.OnSuspending(Object, Windows.ApplicationModel.SuspendingEventArgs)"
IL_0023: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)"
IL_0028: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)"
IL_002d: ldloc.0
IL_002e: dup
IL_002f: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0035: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_003a: ldarg.0
IL_003b: ldftn "Sub abcdef.OnSuspending(Object, Windows.ApplicationModel.SuspendingEventArgs)"
IL_0041: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)"
IL_0046: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)"
IL_004b: ret
}
</output>
CompileAndVerify(compilation).VerifyIL("abcdef.goo", expectedIL.Value())
End Sub
<Fact()>
Public Sub WinMdSynthesizedEventDelegate()
Dim src =
<compilation>
<file name="c.vb">
Class C
Event E(a As Integer)
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(
src,
references:={MscorlibRef_v4_0_30316_17626},
options:=TestOptions.ReleaseWinMD)
comp.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E"))
End Sub
''' <summary>
''' Verify that WinRT events compile into the IL that we
''' would expect.
''' </summary>
Public Sub WinMdEventLambda()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Imports Windows.ApplicationModel
Imports Windows.UI.Xaml
Public Class abcdef
Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs)
End Sub
Public Sub goo()
Dim application As Application = Nothing
AddHandler application.Suspending, Sub(sender as Object, e As SuspendingEventArgs)
End Sub
End Sub
Public Shared Sub Main()
Dim abcdef As abcdef = New abcdef()
abcdef.goo()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithWinRt(source)
Dim expectedIL =
<output>
{
// Code size 66 (0x42)
.maxstack 4
.locals init (Windows.UI.Xaml.Application V_0) //application
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: dup
IL_0004: ldvirtftn "Sub Windows.UI.Xaml.Application.add_Suspending(Windows.UI.Xaml.SuspendingEventHandler) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000a: newobj "Sub System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000f: ldloc.0
IL_0010: dup
IL_0011: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0017: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001c: ldsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler"
IL_0021: brfalse.s IL_002a
IL_0023: ldsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler"
IL_0028: br.s IL_003c
IL_002a: ldnull
IL_002b: ldftn "Sub abcdef._Lambda$__1(Object, Object, Windows.ApplicationModel.SuspendingEventArgs)"
IL_0031: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)"
IL_0036: dup
IL_0037: stsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler"
IL_003c: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)"
IL_0041: ret
}
</output>
CompileAndVerify(compilation, verify:=If(OSVersion.IsWin8, Verification.Passes, Verification.Skipped)).VerifyIL("abcdef.goo", expectedIL.Value())
End Sub
<Fact>
Public Sub IsWindowsRuntimeEvent_EventSymbolSubtypes()
Dim il = <![CDATA[
.class public auto ansi sealed Event
extends [mscorlib]System.MulticastDelegate
{
.method private hidebysig specialname rtspecialname
instance void .ctor(object 'object',
native int 'method') runtime managed
{
}
.method public hidebysig newslot specialname virtual
instance void Invoke() runtime managed
{
}
} // end of class Event
.class interface public abstract auto ansi Interface`1<T>
{
.method public hidebysig newslot specialname abstract virtual
instance void add_Normal(class Event 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void remove_Normal(class Event 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken
add_WinRT([in] class Event 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual
instance void remove_WinRT([in] valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed
{
}
.event Event Normal
{
.addon instance void Interface`1::add_Normal(class Event)
.removeon instance void Interface`1::remove_Normal(class Event)
} // end of event I`1::Normal
.event Event WinRT
{
.addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken Interface`1::add_WinRT(class Event)
.removeon instance void Interface`1::remove_WinRT(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
}
} // end of class Interface
]]>
Dim source =
<compilation>
<file name="a.vb">
Class C
Implements [Interface](Of Integer)
Public Event Normal() Implements [Interface](Of Integer).Normal
Public Event WinRT() Implements [Interface](Of Integer).WinRT
End Class
</file>
</compilation>
Dim ilRef = CompileIL(il.Value)
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}))
comp.VerifyDiagnostics()
Dim interfaceType = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Interface")
Dim interfaceNormalEvent = interfaceType.GetMember(Of EventSymbol)("Normal")
Dim interfaceWinRTEvent = interfaceType.GetMember(Of EventSymbol)("WinRT")
Assert.IsType(Of PEEventSymbol)(interfaceNormalEvent)
Assert.IsType(Of PEEventSymbol)(interfaceWinRTEvent)
' Only depends on accessor signatures - doesn't care if it's in a windowsruntime type.
Assert.False(interfaceNormalEvent.IsWindowsRuntimeEvent)
Assert.True(interfaceWinRTEvent.IsWindowsRuntimeEvent)
Dim implementingType = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim implementingNormalEvent = implementingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("Normal"))
Dim implementingWinRTEvent = implementingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("WinRT"))
Assert.IsType(Of SourceEventSymbol)(implementingNormalEvent)
Assert.IsType(Of SourceEventSymbol)(implementingWinRTEvent)
' Based on kind of explicitly implemented interface event (other checks to be tested separately).
Assert.False(implementingNormalEvent.IsWindowsRuntimeEvent)
Assert.True(implementingWinRTEvent.IsWindowsRuntimeEvent)
Dim substitutedNormalEvent = implementingNormalEvent.ExplicitInterfaceImplementations.Single()
Dim substitutedWinRTEvent = implementingWinRTEvent.ExplicitInterfaceImplementations.Single()
Assert.IsType(Of SubstitutedEventSymbol)(substitutedNormalEvent)
Assert.IsType(Of SubstitutedEventSymbol)(substitutedWinRTEvent)
' Based on original definition.
Assert.False(substitutedNormalEvent.IsWindowsRuntimeEvent)
Assert.True(substitutedWinRTEvent.IsWindowsRuntimeEvent)
Dim retargetingAssembly = New RetargetingAssemblySymbol(DirectCast(comp.Assembly, SourceAssemblySymbol), isLinked:=False)
retargetingAssembly.SetCorLibrary(comp.Assembly.CorLibrary)
Dim retargetingType = retargetingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim retargetingNormalEvent = retargetingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("Normal"))
Dim retargetingWinRTEvent = retargetingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("WinRT"))
Assert.IsType(Of RetargetingEventSymbol)(retargetingNormalEvent)
Assert.IsType(Of RetargetingEventSymbol)(retargetingWinRTEvent)
' Based on underlying symbol.
Assert.False(retargetingNormalEvent.IsWindowsRuntimeEvent)
Assert.True(retargetingWinRTEvent.IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub IsWindowsRuntimeEvent_Source_OutputKind()
Dim source =
<compilation>
<file name="a.vb">
Class C
Public Event E As System.Action
Shared Sub Main()
End Sub
End Class
Interface I
Event E As System.Action
End Interface
</file>
</compilation>
For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, New VisualBasicCompilationOptions(kind))
comp.VerifyDiagnostics()
Dim [class] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim classEvent = [class].GetMember(Of EventSymbol)("E")
' Specifically test interfaces because they follow a different code path.
Dim [interface] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("I")
Dim interfaceEvent = [interface].GetMember(Of EventSymbol)("E")
Assert.Equal(kind.IsWindowsRuntime(), classEvent.IsWindowsRuntimeEvent)
Assert.Equal(kind.IsWindowsRuntime(), interfaceEvent.IsWindowsRuntimeEvent)
Next
End Sub
<Fact>
Public Sub IsWindowsRuntimeEvent_Source_InterfaceImplementation()
Dim source =
<compilation>
<file name="a.vb">
Class C
Implements I
Public Event Normal Implements I.Normal
Public Event WinRT Implements I.WinRT
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I"))
For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), New VisualBasicCompilationOptions(kind))
comp.VerifyDiagnostics()
Dim [class] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
Dim normalEvent = [class].GetMember(Of EventSymbol)("Normal")
Dim winRTEvent = [class].GetMember(Of EventSymbol)("WinRT")
Assert.False(normalEvent.IsWindowsRuntimeEvent)
Assert.True(winRTEvent.IsWindowsRuntimeEvent)
Next
End Sub
<Fact>
Public Sub ERR_MixingWinRTAndNETEvents()
Dim source =
<compilation>
<file name="a.vb">
' Fine to implement more than one interface of the same WinRT-ness
Class C1
Implements I1, I2
Public Event Normal Implements I1.Normal, I2.Normal
Public Event WinRT Implements I1.WinRT, I2.WinRT
End Class
' Error to implement two interfaces of different WinRT-ness
Class C2
Implements I1, I2
Public Event Normal Implements I1.Normal, I2.WinRT
Public Event WinRT Implements I1.WinRT, I2.Normal
End Class
</file>
</compilation>
Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I1") + String.Format(_eventInterfaceILTemplate, "I2"))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), TestOptions.ReleaseDll)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.WinRT").WithArguments("Normal", "I2.WinRT", "I1.Normal"),
Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.Normal").WithArguments("WinRT", "I1.WinRT", "I2.Normal"))
Dim c1 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C1")
Assert.False(c1.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent)
Assert.True(c1.GetMember(Of EventSymbol)("WinRT").IsWindowsRuntimeEvent)
Dim c2 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C2")
Assert.False(c2.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent)
Assert.True(c2.GetMember(Of EventSymbol)("WinRT").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_MixingWinRTAndNETEvents_Multiple()
Dim source =
<compilation>
<file name="a.vb">
' Try going back and forth
Class C3
Implements I1, I2
Public Event Normal Implements I1.Normal, I1.WinRT, I2.Normal, I2.WinRT
End Class
</file>
</compilation>
Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I1") + String.Format(_eventInterfaceILTemplate, "I2"))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), TestOptions.ReleaseDll)
' CONSIDER: This is not how dev11 handles this scenario: it reports the first diagnostic, but then reports
' ERR_IdentNotMemberOfInterface4 (BC30401) and ERR_UnimplementedMember3 (BC30149) for all subsequent implemented members
' (side-effects of calling SetIsBad on the implementing event).
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I1.WinRT").WithArguments("Normal", "I1.WinRT", "I1.Normal"),
Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.WinRT").WithArguments("Normal", "I2.WinRT", "I1.Normal"))
Dim c3 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C3")
Assert.False(c3.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_WinRTEventWithoutDelegate_FieldLike()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Event E ' As System.Action
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)>
Public Sub ERR_WinRTEventWithoutDelegate_Custom()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E ' As System.Action
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
' Once the as-clause is missing, the event is parsed as a field-like event, hence the many syntax errors.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E"),
Diagnostic(ERRID.ERR_CustomEventRequiresAs, "Public Custom Event E ' As System.Action" + Environment.NewLine),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "AddHandler(value As System.Action)"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"),
Diagnostic(ERRID.ERR_InvalidEndAddHandler, "End AddHandler"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"),
Diagnostic(ERRID.ERR_InvalidEndRemoveHandler, "End RemoveHandler"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "RaiseEvent()"),
Diagnostic(ERRID.ERR_InvalidEndRaiseEvent, "End RaiseEvent"),
Diagnostic(ERRID.ERR_InvalidEndEvent, "End Event"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_WinRTEventWithoutDelegate_Implements()
Dim source =
<compilation>
<file name="a.vb">
Interface I
Event E1 As System.Action
Event E2 As System.Action
End Interface
Class Test
Implements I
Public Event E1 Implements I.E1
Public Custom Event E2 Implements I.E2
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
' Everything goes sideways for E2 since it custom events are required to have as-clauses.
' The key thing is that neither event reports ERR_WinRTEventWithoutDelegate.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_CustomEventRequiresAs, "Public Custom Event E2 Implements I.E2"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "AddHandler(value As System.Action)"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"),
Diagnostic(ERRID.ERR_InvalidEndAddHandler, "End AddHandler"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"),
Diagnostic(ERRID.ERR_InvalidEndRemoveHandler, "End RemoveHandler"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "RaiseEvent()"),
Diagnostic(ERRID.ERR_InvalidEndRaiseEvent, "End RaiseEvent"),
Diagnostic(ERRID.ERR_InvalidEndEvent, "End Event"),
Diagnostic(ERRID.ERR_EventImplMismatch5, "I.E2").WithArguments("Public Event E2 As ?", "Event E2 As System.Action", "I", "?", "System.Action"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E1").IsWindowsRuntimeEvent)
Assert.True(type.GetMember(Of EventSymbol)("E2").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_AddParamWrongForWinRT()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E As System.Action
AddHandler(value As System.Action(Of Integer))
Return Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_AddParamWrongForWinRT, "AddHandler(value As System.Action(Of Integer))"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_RemoveParamWrongForWinRT()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E As System.Action
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_RemoveParamWrongForWinRT, "RemoveHandler(value As System.Action)"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_RemoveParamWrongForWinRT_MissingTokenType()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E As System.Action
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD)
' This diagnostic is from binding the return type of the AddHandler, not from checking the parameter type
' of the ReturnHandler. The key point is that a cascading ERR_RemoveParamWrongForWinRT is not reported.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, <![CDATA[AddHandler(value As System.Action)
Return Nothing
End AddHandler]]>.Value.Replace(vbLf, vbCrLf)).WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", comp.AssemblyName + ".winmdobj"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_EventImplRemoveHandlerParamWrong()
Dim source =
<compilation>
<file name="a.vb">
Interface I
Event E As System.Action
end Interface
Class Test
Implements I
Public Custom Event F As System.Action Implements I.E
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_EventImplRemoveHandlerParamWrong, "RemoveHandler(value As System.Action)").WithArguments("F", "E", "I"))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("F").IsWindowsRuntimeEvent)
End Sub
<Fact>
Public Sub ERR_EventImplRemoveHandlerParamWrong_MissingTokenType()
Dim source =
<compilation>
<file name="a.vb">
Interface I
Event E As System.Action
end Interface
Class Test
Implements I
Public Custom Event F As System.Action Implements I.E
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD)
' This diagnostic is from binding the return type of the AddHandler, not from checking the parameter type
' of the ReturnHandler. The key point is that a cascading ERR_RemoveParamWrongForWinRT is not reported.
Dim outputName As String = comp.AssemblyName + ".winmdobj"
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, <![CDATA[AddHandler(value As System.Action)
Return Nothing
End AddHandler]]>.Value.Replace(vbLf, vbCrLf)).WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Assert.True(type.GetMember(Of EventSymbol)("F").IsWindowsRuntimeEvent)
End Sub
' Confirms that we're getting decl errors from the backing field.
<Fact>
Public Sub MissingTokenTableType()
Dim source =
<compilation name="test">
<file name="a.vb">
Class Test
Event E As System.Action
End Class
Namespace System.Runtime.InteropServices.WindowsRuntime
Public Structure EventRegistrationToken
End Structure
End Namespace
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD)
AssertTheseDeclarationDiagnostics(comp, <errors><![CDATA[
BC31091: Import of type 'EventRegistrationTokenTable(Of )' from assembly or module 'test.winmdobj' failed.
Event E As System.Action
~
]]></errors>)
End Sub
<Fact>
Public Sub ReturnLocal()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event E As System.Action
AddHandler(value As System.Action)
add_E = Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
Dim v = CompileAndVerify(comp)
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Dim eventSymbol As EventSymbol = type.GetMember(Of EventSymbol)("E")
Assert.True(eventSymbol.IsWindowsRuntimeEvent)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim syntax = tree.GetRoot().DescendantNodes().OfType(Of AssignmentStatementSyntax).Single().Left
Dim symbol = model.GetSymbolInfo(syntax).Symbol
Assert.Equal(SymbolKind.Local, symbol.Kind)
Assert.Equal(eventSymbol.AddMethod.ReturnType, DirectCast(symbol, LocalSymbol).Type)
Assert.Equal(eventSymbol.AddMethod.Name, symbol.Name)
v.VerifyIL("Test.add_E", "
{
// Code size 10 (0xa)
.maxstack 1
.locals init (System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken V_0) //add_E
IL_0000: ldloca.s V_0
IL_0002: initobj ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken""
IL_0008: ldloc.0
IL_0009: ret
}
")
End Sub
<Fact>
Public Sub AccessorSignatures()
Dim source =
<compilation>
<file name="a.vb">
Class Test
public event FieldLike As System.Action
Public Custom Event Custom As System.Action
AddHandler(value As System.Action)
Throw New System.Exception()
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Public Shared Sub Main()
End Sub
End Class
</file>
</compilation>
For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind))
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, New VisualBasicCompilationOptions(kind))
Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test")
Dim fieldLikeEvent = type.GetMember(Of EventSymbol)("FieldLike")
Dim customEvent = type.GetMember(Of EventSymbol)("Custom")
If kind.IsWindowsRuntime() Then
comp.VerifyDiagnostics()
VerifyWinRTEventShape(customEvent, comp)
VerifyWinRTEventShape(fieldLikeEvent, comp)
Else
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_AddRemoveParamNotEventType, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"))
VerifyNormalEventShape(customEvent, comp)
VerifyNormalEventShape(fieldLikeEvent, comp)
End If
Next
End Sub
<Fact()>
Public Sub HandlerSemanticInfo()
Dim source =
<compilation>
<file name="a.vb">
Class C
Event QQQ As System.Action
Sub Test()
AddHandler QQQ, Nothing
RemoveHandler QQQ, Nothing
RaiseEvent QQQ()
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD)
comp.VerifyDiagnostics()
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim references = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax).Where(Function(id) id.Identifier.ValueText = "QQQ").ToArray()
Assert.Equal(3, references.Count) ' Decl is just a token
Dim eventSymbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of EventSymbol)("QQQ")
AssertEx.All(references, Function(ref) model.GetSymbolInfo(ref).Symbol.Equals(eventSymbol))
Dim actionType = comp.GetWellKnownType(WellKnownType.System_Action)
Assert.Equal(actionType, eventSymbol.Type)
AssertEx.All(references, Function(ref) model.GetTypeInfo(ref).Type.Equals(actionType))
End Sub
<Fact>
Public Sub NoReturnFromAddHandler()
Dim source =
<compilation>
<file name="a.vb">
Delegate Sub EventDelegate()
Class Events
Custom Event E As eventdelegate
AddHandler(value As eventdelegate)
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
' Note the distinct new error code.
comp.VerifyDiagnostics(
Diagnostic(ERRID.WRN_DefAsgNoRetValWinRtEventVal1, "End AddHandler").WithArguments("E"))
End Sub
Private Shared Sub VerifyWinRTEventShape([event] As EventSymbol, compilation As VisualBasicCompilation)
Assert.True([event].IsWindowsRuntimeEvent)
Dim eventType = [event].Type
Dim tokenType = compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken)
Assert.NotNull(tokenType)
Dim voidType = compilation.GetSpecialType(SpecialType.System_Void)
Assert.NotNull(voidType)
Dim addMethod = [event].AddMethod
Assert.Equal(tokenType, addMethod.ReturnType)
Assert.False(addMethod.IsSub)
Assert.Equal(1, addMethod.ParameterCount)
Assert.Equal(eventType, addMethod.Parameters.Single().Type)
Dim removeMethod = [event].RemoveMethod
Assert.Equal(voidType, removeMethod.ReturnType)
Assert.True(removeMethod.IsSub)
Assert.Equal(1, removeMethod.ParameterCount)
Assert.Equal(tokenType, removeMethod.Parameters.Single().Type)
If [event].HasAssociatedField Then
Dim expectedFieldType = compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T).Construct(eventType)
Assert.Equal(expectedFieldType, [event].AssociatedField.Type)
Else
Assert.Null([event].AssociatedField)
End If
End Sub
Private Shared Sub VerifyNormalEventShape([event] As EventSymbol, compilation As VisualBasicCompilation)
Assert.False([event].IsWindowsRuntimeEvent)
Dim eventType = [event].Type
Dim voidType = compilation.GetSpecialType(SpecialType.System_Void)
Assert.NotNull(voidType)
Dim addMethod = [event].AddMethod
Assert.Equal(voidType, addMethod.ReturnType)
Assert.True(addMethod.IsSub)
Assert.Equal(1, addMethod.ParameterCount)
Assert.Equal(eventType, addMethod.Parameters.Single().Type)
Dim removeMethod = [event].RemoveMethod
Assert.Equal(voidType, removeMethod.ReturnType)
Assert.True(removeMethod.IsSub)
Assert.Equal(1, removeMethod.ParameterCount)
If [event].HasAssociatedField Then
' Otherwise, we had to be explicit and we favored WinRT because that's what we're testing.
Assert.Equal(eventType, removeMethod.Parameters.Single().Type)
End If
If [event].HasAssociatedField Then
Assert.Equal(eventType, [event].AssociatedField.Type)
Else
Assert.Null([event].AssociatedField)
End If
End Sub
<Fact>
Public Sub BackingField()
Dim source =
<compilation>
<file name="a.vb">
Class Test
Public Custom Event CustomEvent As System.Action
AddHandler(value As System.Action)
Return Nothing
End AddHandler
RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Public Event FieldLikeEvent As System.Action
Sub Test()
dim f1 = CustomEventEvent
dim f2 = FieldLikeEventEvent
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD)
' No backing field for custom event.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_NameNotDeclared1, "CustomEventEvent").WithArguments("CustomEventEvent"))
Dim fieldLikeEvent = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test").GetMember(Of EventSymbol)("FieldLikeEvent")
Dim tokenTableType = comp.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T)
Dim tree = comp.SyntaxTrees.Single()
Dim model = comp.GetSemanticModel(tree)
Dim syntax = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Single(Function(id) id.Identifier.ValueText = "FieldLikeEventEvent")
Dim symbol = model.GetSymbolInfo(syntax).Symbol
Assert.Equal(SymbolKind.Field, symbol.Kind)
Assert.Equal(fieldLikeEvent, DirectCast(symbol, FieldSymbol).AssociatedSymbol)
Dim type = model.GetTypeInfo(syntax).Type
Assert.Equal(tokenTableType, type.OriginalDefinition)
Assert.Equal(fieldLikeEvent.Type, DirectCast(type, NamedTypeSymbol).TypeArguments.Single())
End Sub
<Fact()>
Public Sub RaiseBaseEventedFromDerivedNestedTypes()
Dim source =
<compilation>
<file name="filename.vb">
Delegate Sub D()
Class C1
Event HelloWorld As D
Class C2
Inherits C1
Sub t
RaiseEvent HelloWorld
End Sub
End Class
End Class
</file>
</compilation>
CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD).VerifyDiagnostics()
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,922 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot. | Fixes #52639. | AlekseyTs | 2021-08-26T16:50:08Z | 2021-08-27T18:29:57Z | 26c94b18f1bddadc789f5511b4dc3c9c3f3208c7 | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | Avoid calling DefineUserDefinedStateMachineHoistedLocal for fields without long-lived local slot.. Fixes #52639. | ./src/VisualStudio/Core/Def/Storage/ProjectContainerKeyCache.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.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.VisualStudio.RpcContracts.Caching;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Storage
{
/// <summary>
/// Cache of our own internal roslyn storage keys to the equivalent platform cloud cache keys. Cloud cache keys can
/// store a lot of date in them (like their 'dimensions' dictionary. We don't want to continually recreate these as
/// we read/write date to the db.
/// </summary>
internal class ProjectContainerKeyCache
{
private static readonly ImmutableSortedDictionary<string, string?> EmptyDimensions = ImmutableSortedDictionary.Create<string, string?>(StringComparer.Ordinal);
/// <summary>
/// Container key explicitly for the project itself.
/// </summary>
public readonly CacheContainerKey? ProjectContainerKey;
/// <summary>
/// Cache from document green nodes to the container keys we've computed for it. We can avoid computing these
/// container keys when called repeatedly for the same documents.
/// </summary>
/// <remarks>
/// We can use a normal Dictionary here instead of a <see cref="ConditionalWeakTable{TKey, TValue}"/> as
/// instances of <see cref="ProjectContainerKeyCache"/> are always owned in a context where the <see
/// cref="ProjectState"/> is alive. As that instance is alive, all <see cref="TextDocumentState"/>s the project
/// points at will be held alive strongly too.
/// </remarks>
private readonly Dictionary<TextDocumentState, CacheContainerKey?> _documentToContainerKey = new();
private readonly Func<TextDocumentState, CacheContainerKey?> _documentToContainerKeyCallback;
public ProjectContainerKeyCache(string relativePathBase, ProjectKey projectKey)
{
ProjectContainerKey = CreateProjectContainerKey(relativePathBase, projectKey);
_documentToContainerKeyCallback = ds => CreateDocumentContainerKey(relativePathBase, DocumentKey.ToDocumentKey(projectKey, ds));
}
public CacheContainerKey? GetDocumentContainerKey(TextDocumentState state)
{
lock (_documentToContainerKey)
return _documentToContainerKey.GetOrAdd(state, _documentToContainerKeyCallback);
}
public static CacheContainerKey? CreateProjectContainerKey(
string relativePathBase, ProjectKey projectKey)
{
// Creates a container key for this project. The container key is a mix of the project's name, relative
// file path (to the solution), and optional parse options.
// If we don't have a valid solution path, we can't store anything.
if (string.IsNullOrEmpty(relativePathBase))
return null;
// We have to have a file path for this project
if (RoslynString.IsNullOrEmpty(projectKey.FilePath))
return null;
// The file path has to be relative to the base path the DB is associated with (either the solution-path or
// repo-path).
var relativePath = PathUtilities.GetRelativePath(relativePathBase, projectKey.FilePath!);
if (relativePath == projectKey.FilePath)
return null;
var dimensions = EmptyDimensions
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.Name)}", projectKey.Name)
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.FilePath)}", relativePath)
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.ParseOptionsChecksum)}", projectKey.ParseOptionsChecksum.ToString());
return new CacheContainerKey("Roslyn.Project", dimensions);
}
public static CacheContainerKey? CreateDocumentContainerKey(
string relativePathBase,
DocumentKey documentKey)
{
// See if we can get a project key for this info. If not, we def can't get a doc key.
var projectContainerKey = CreateProjectContainerKey(relativePathBase, documentKey.Project);
if (projectContainerKey == null)
return null;
// We have to have a file path for this document
if (string.IsNullOrEmpty(documentKey.FilePath))
return null;
// The file path has to be relative to the base path the DB is associated with (either the solution-path or
// repo-path).
var relativePath = PathUtilities.GetRelativePath(relativePathBase, documentKey.FilePath!);
if (relativePath == documentKey.FilePath)
return null;
var dimensions = projectContainerKey.Value.Dimensions
.Add($"{nameof(DocumentKey)}.{nameof(DocumentKey.Name)}", documentKey.Name)
.Add($"{nameof(DocumentKey)}.{nameof(DocumentKey.FilePath)}", relativePath);
return new CacheContainerKey("Roslyn.Document", dimensions);
}
}
}
| // 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.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.VisualStudio.RpcContracts.Caching;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Storage
{
/// <summary>
/// Cache of our own internal roslyn storage keys to the equivalent platform cloud cache keys. Cloud cache keys can
/// store a lot of date in them (like their 'dimensions' dictionary. We don't want to continually recreate these as
/// we read/write date to the db.
/// </summary>
internal class ProjectContainerKeyCache
{
private static readonly ImmutableSortedDictionary<string, string?> EmptyDimensions = ImmutableSortedDictionary.Create<string, string?>(StringComparer.Ordinal);
/// <summary>
/// Container key explicitly for the project itself.
/// </summary>
public readonly CacheContainerKey? ProjectContainerKey;
/// <summary>
/// Cache from document green nodes to the container keys we've computed for it. We can avoid computing these
/// container keys when called repeatedly for the same documents.
/// </summary>
/// <remarks>
/// We can use a normal Dictionary here instead of a <see cref="ConditionalWeakTable{TKey, TValue}"/> as
/// instances of <see cref="ProjectContainerKeyCache"/> are always owned in a context where the <see
/// cref="ProjectState"/> is alive. As that instance is alive, all <see cref="TextDocumentState"/>s the project
/// points at will be held alive strongly too.
/// </remarks>
private readonly Dictionary<TextDocumentState, CacheContainerKey?> _documentToContainerKey = new();
private readonly Func<TextDocumentState, CacheContainerKey?> _documentToContainerKeyCallback;
public ProjectContainerKeyCache(string relativePathBase, ProjectKey projectKey)
{
ProjectContainerKey = CreateProjectContainerKey(relativePathBase, projectKey);
_documentToContainerKeyCallback = ds => CreateDocumentContainerKey(relativePathBase, DocumentKey.ToDocumentKey(projectKey, ds));
}
public CacheContainerKey? GetDocumentContainerKey(TextDocumentState state)
{
lock (_documentToContainerKey)
return _documentToContainerKey.GetOrAdd(state, _documentToContainerKeyCallback);
}
public static CacheContainerKey? CreateProjectContainerKey(
string relativePathBase, ProjectKey projectKey)
{
// Creates a container key for this project. The container key is a mix of the project's name, relative
// file path (to the solution), and optional parse options.
// If we don't have a valid solution path, we can't store anything.
if (string.IsNullOrEmpty(relativePathBase))
return null;
// We have to have a file path for this project
if (RoslynString.IsNullOrEmpty(projectKey.FilePath))
return null;
// The file path has to be relative to the base path the DB is associated with (either the solution-path or
// repo-path).
var relativePath = PathUtilities.GetRelativePath(relativePathBase, projectKey.FilePath!);
if (relativePath == projectKey.FilePath)
return null;
var dimensions = EmptyDimensions
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.Name)}", projectKey.Name)
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.FilePath)}", relativePath)
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.ParseOptionsChecksum)}", projectKey.ParseOptionsChecksum.ToString());
return new CacheContainerKey("Roslyn.Project", dimensions);
}
public static CacheContainerKey? CreateDocumentContainerKey(
string relativePathBase,
DocumentKey documentKey)
{
// See if we can get a project key for this info. If not, we def can't get a doc key.
var projectContainerKey = CreateProjectContainerKey(relativePathBase, documentKey.Project);
if (projectContainerKey == null)
return null;
// We have to have a file path for this document
if (string.IsNullOrEmpty(documentKey.FilePath))
return null;
// The file path has to be relative to the base path the DB is associated with (either the solution-path or
// repo-path).
var relativePath = PathUtilities.GetRelativePath(relativePathBase, documentKey.FilePath!);
if (relativePath == documentKey.FilePath)
return null;
var dimensions = projectContainerKey.Value.Dimensions
.Add($"{nameof(DocumentKey)}.{nameof(DocumentKey.Name)}", documentKey.Name)
.Add($"{nameof(DocumentKey)}.{nameof(DocumentKey.FilePath)}", relativePath);
return new CacheContainerKey("Roslyn.Document", dimensions);
}
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.