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,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/CSharp/Portable/BoundTree/BoundDagRelationalTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class BoundDagRelationalTest
{
public BinaryOperatorKind Relation => OperatorKind.Operator();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class BoundDagRelationalTest
{
public BinaryOperatorKind Relation => OperatorKind.Operator();
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/WithBlockTests.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.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class WithBlockTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub ApplyAfterWithStatement()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo()
With variable
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class c1
Sub goo()
With variable
End With
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub DontApplyForMatchedWith()
VerifyStatementEndConstructNotApplied(
text:="Class c1
Sub goo()
With variable
End With
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNestedWith()
VerifyStatementEndConstructApplied(
before:="Class C
Sub S
With K
With K
End With
End Sub
End Class",
beforeCaret:={3, -1},
after:="Class C
Sub S
With K
With K
End With
End With
End Sub
End Class",
afterCaret:={4, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyWithFollowsCode()
VerifyStatementEndConstructApplied(
before:="Class C
Sub S
With K
Dim x = 5
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class C
Sub S
With K
End With
Dim x = 5
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidWithSyntax()
VerifyStatementEndConstructNotApplied(
text:="Class EC
Sub S
With using
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidWithLocation()
VerifyStatementEndConstructNotApplied(
text:="Class EC
With True
End Class",
caret:={1, -1})
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.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class WithBlockTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub ApplyAfterWithStatement()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo()
With variable
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class c1
Sub goo()
With variable
End With
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub DontApplyForMatchedWith()
VerifyStatementEndConstructNotApplied(
text:="Class c1
Sub goo()
With variable
End With
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNestedWith()
VerifyStatementEndConstructApplied(
before:="Class C
Sub S
With K
With K
End With
End Sub
End Class",
beforeCaret:={3, -1},
after:="Class C
Sub S
With K
With K
End With
End With
End Sub
End Class",
afterCaret:={4, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyWithFollowsCode()
VerifyStatementEndConstructApplied(
before:="Class C
Sub S
With K
Dim x = 5
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class C
Sub S
With K
End With
Dim x = 5
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidWithSyntax()
VerifyStatementEndConstructNotApplied(
text:="Class EC
Sub S
With using
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidWithLocation()
VerifyStatementEndConstructNotApplied(
text:="Class EC
With True
End Class",
caret:={1, -1})
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Analyzers/CSharp/Analyzers/FileHeaders/CSharpFileHeaderHelper.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 Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.FileHeaders;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.FileHeaders
{
/// <summary>
/// Helper class used for working with file headers.
/// </summary>
internal sealed class CSharpFileHeaderHelper : AbstractFileHeaderHelper
{
public static readonly CSharpFileHeaderHelper Instance = new();
private CSharpFileHeaderHelper()
: base(CSharpSyntaxKinds.Instance)
{
}
public override string CommentPrefix => "//";
protected override ReadOnlyMemory<char> GetTextContextOfComment(SyntaxTrivia commentTrivia)
{
if (commentTrivia.IsKind(SyntaxKind.SingleLineCommentTrivia))
{
return commentTrivia.ToFullString().AsMemory()[2..];
}
else if (commentTrivia.IsKind(SyntaxKind.MultiLineCommentTrivia))
{
var triviaString = commentTrivia.ToFullString();
var startIndex = triviaString.IndexOf("/*", StringComparison.Ordinal) + 2;
var endIndex = triviaString.LastIndexOf("*/", StringComparison.Ordinal);
if (endIndex < startIndex)
{
// While editing, it is possible to have a multiline comment trivia that does not contain the closing '*/' yet.
return triviaString.AsMemory()[startIndex..];
}
return triviaString.AsMemory()[startIndex..endIndex];
}
else
{
throw ExceptionUtilities.UnexpectedValue(commentTrivia.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.
using System;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.FileHeaders;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.FileHeaders
{
/// <summary>
/// Helper class used for working with file headers.
/// </summary>
internal sealed class CSharpFileHeaderHelper : AbstractFileHeaderHelper
{
public static readonly CSharpFileHeaderHelper Instance = new();
private CSharpFileHeaderHelper()
: base(CSharpSyntaxKinds.Instance)
{
}
public override string CommentPrefix => "//";
protected override ReadOnlyMemory<char> GetTextContextOfComment(SyntaxTrivia commentTrivia)
{
if (commentTrivia.IsKind(SyntaxKind.SingleLineCommentTrivia))
{
return commentTrivia.ToFullString().AsMemory()[2..];
}
else if (commentTrivia.IsKind(SyntaxKind.MultiLineCommentTrivia))
{
var triviaString = commentTrivia.ToFullString();
var startIndex = triviaString.IndexOf("/*", StringComparison.Ordinal) + 2;
var endIndex = triviaString.LastIndexOf("*/", StringComparison.Ordinal);
if (endIndex < startIndex)
{
// While editing, it is possible to have a multiline comment trivia that does not contain the closing '*/' yet.
return triviaString.AsMemory()[startIndex..];
}
return triviaString.AsMemory()[startIndex..endIndex];
}
else
{
throw ExceptionUtilities.UnexpectedValue(commentTrivia.Kind());
}
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerExecutor.AnalyzerDiagnosticReporter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class AnalyzerExecutor
{
/// <summary>
/// Pooled object that carries the info needed to process
/// a reported diagnostic from a syntax node action.
/// </summary>
private sealed class AnalyzerDiagnosticReporter
{
public readonly Action<Diagnostic> AddDiagnosticAction;
private static readonly ObjectPool<AnalyzerDiagnosticReporter> s_objectPool =
new ObjectPool<AnalyzerDiagnosticReporter>(() => new AnalyzerDiagnosticReporter(), 10);
public static AnalyzerDiagnosticReporter GetInstance(
SourceOrAdditionalFile contextFile,
TextSpan? span,
Compilation compilation,
DiagnosticAnalyzer analyzer,
bool isSyntaxDiagnostic,
Action<Diagnostic>? addNonCategorizedDiagnostic,
Action<Diagnostic, DiagnosticAnalyzer, bool>? addCategorizedLocalDiagnostic,
Action<Diagnostic, DiagnosticAnalyzer>? addCategorizedNonLocalDiagnostic,
Func<Diagnostic, DiagnosticAnalyzer, Compilation, CancellationToken, bool> shouldSuppressGeneratedCodeDiagnostic,
CancellationToken cancellationToken)
{
var item = s_objectPool.Allocate();
item._contextFile = contextFile;
item._span = span;
item._compilation = compilation;
item._analyzer = analyzer;
item._isSyntaxDiagnostic = isSyntaxDiagnostic;
item._addNonCategorizedDiagnostic = addNonCategorizedDiagnostic;
item._addCategorizedLocalDiagnostic = addCategorizedLocalDiagnostic;
item._addCategorizedNonLocalDiagnostic = addCategorizedNonLocalDiagnostic;
item._shouldSuppressGeneratedCodeDiagnostic = shouldSuppressGeneratedCodeDiagnostic;
item._cancellationToken = cancellationToken;
return item;
}
public void Free()
{
_contextFile = null!;
_span = null;
_compilation = null!;
_analyzer = null!;
_isSyntaxDiagnostic = default;
_addNonCategorizedDiagnostic = null!;
_addCategorizedLocalDiagnostic = null!;
_addCategorizedNonLocalDiagnostic = null!;
_shouldSuppressGeneratedCodeDiagnostic = null!;
_cancellationToken = default;
s_objectPool.Free(this);
}
private SourceOrAdditionalFile? _contextFile;
private TextSpan? _span;
private Compilation _compilation;
private DiagnosticAnalyzer _analyzer;
private bool _isSyntaxDiagnostic;
private Action<Diagnostic>? _addNonCategorizedDiagnostic;
private Action<Diagnostic, DiagnosticAnalyzer, bool>? _addCategorizedLocalDiagnostic;
private Action<Diagnostic, DiagnosticAnalyzer>? _addCategorizedNonLocalDiagnostic;
private Func<Diagnostic, DiagnosticAnalyzer, Compilation, CancellationToken, bool> _shouldSuppressGeneratedCodeDiagnostic;
private CancellationToken _cancellationToken;
// Pooled objects are initialized in their GetInstance method
#pragma warning disable 8618
private AnalyzerDiagnosticReporter()
{
AddDiagnosticAction = AddDiagnostic;
}
#pragma warning restore 8618
private void AddDiagnostic(Diagnostic diagnostic)
{
if (_shouldSuppressGeneratedCodeDiagnostic(diagnostic, _analyzer, _compilation, _cancellationToken))
{
return;
}
if (_addCategorizedLocalDiagnostic == null)
{
Debug.Assert(_addNonCategorizedDiagnostic != null);
_addNonCategorizedDiagnostic(diagnostic);
return;
}
Debug.Assert(_addNonCategorizedDiagnostic == null);
Debug.Assert(_addCategorizedNonLocalDiagnostic != null);
if (isLocalDiagnostic(diagnostic) &&
(!_span.HasValue || _span.Value.IntersectsWith(diagnostic.Location.SourceSpan)))
{
_addCategorizedLocalDiagnostic(diagnostic, _analyzer, _isSyntaxDiagnostic);
}
else
{
_addCategorizedNonLocalDiagnostic(diagnostic, _analyzer);
}
return;
bool isLocalDiagnostic(Diagnostic diagnostic)
{
if (diagnostic.Location.IsInSource)
{
return _contextFile?.SourceTree != null &&
_contextFile.Value.SourceTree == diagnostic.Location.SourceTree;
}
if (_contextFile?.AdditionalFile != null &&
diagnostic.Location is ExternalFileLocation externalFileLocation)
{
return PathUtilities.Comparer.Equals(_contextFile.Value.AdditionalFile.Path, externalFileLocation.FilePath);
}
return false;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class AnalyzerExecutor
{
/// <summary>
/// Pooled object that carries the info needed to process
/// a reported diagnostic from a syntax node action.
/// </summary>
private sealed class AnalyzerDiagnosticReporter
{
public readonly Action<Diagnostic> AddDiagnosticAction;
private static readonly ObjectPool<AnalyzerDiagnosticReporter> s_objectPool =
new ObjectPool<AnalyzerDiagnosticReporter>(() => new AnalyzerDiagnosticReporter(), 10);
public static AnalyzerDiagnosticReporter GetInstance(
SourceOrAdditionalFile contextFile,
TextSpan? span,
Compilation compilation,
DiagnosticAnalyzer analyzer,
bool isSyntaxDiagnostic,
Action<Diagnostic>? addNonCategorizedDiagnostic,
Action<Diagnostic, DiagnosticAnalyzer, bool>? addCategorizedLocalDiagnostic,
Action<Diagnostic, DiagnosticAnalyzer>? addCategorizedNonLocalDiagnostic,
Func<Diagnostic, DiagnosticAnalyzer, Compilation, CancellationToken, bool> shouldSuppressGeneratedCodeDiagnostic,
CancellationToken cancellationToken)
{
var item = s_objectPool.Allocate();
item._contextFile = contextFile;
item._span = span;
item._compilation = compilation;
item._analyzer = analyzer;
item._isSyntaxDiagnostic = isSyntaxDiagnostic;
item._addNonCategorizedDiagnostic = addNonCategorizedDiagnostic;
item._addCategorizedLocalDiagnostic = addCategorizedLocalDiagnostic;
item._addCategorizedNonLocalDiagnostic = addCategorizedNonLocalDiagnostic;
item._shouldSuppressGeneratedCodeDiagnostic = shouldSuppressGeneratedCodeDiagnostic;
item._cancellationToken = cancellationToken;
return item;
}
public void Free()
{
_contextFile = null!;
_span = null;
_compilation = null!;
_analyzer = null!;
_isSyntaxDiagnostic = default;
_addNonCategorizedDiagnostic = null!;
_addCategorizedLocalDiagnostic = null!;
_addCategorizedNonLocalDiagnostic = null!;
_shouldSuppressGeneratedCodeDiagnostic = null!;
_cancellationToken = default;
s_objectPool.Free(this);
}
private SourceOrAdditionalFile? _contextFile;
private TextSpan? _span;
private Compilation _compilation;
private DiagnosticAnalyzer _analyzer;
private bool _isSyntaxDiagnostic;
private Action<Diagnostic>? _addNonCategorizedDiagnostic;
private Action<Diagnostic, DiagnosticAnalyzer, bool>? _addCategorizedLocalDiagnostic;
private Action<Diagnostic, DiagnosticAnalyzer>? _addCategorizedNonLocalDiagnostic;
private Func<Diagnostic, DiagnosticAnalyzer, Compilation, CancellationToken, bool> _shouldSuppressGeneratedCodeDiagnostic;
private CancellationToken _cancellationToken;
// Pooled objects are initialized in their GetInstance method
#pragma warning disable 8618
private AnalyzerDiagnosticReporter()
{
AddDiagnosticAction = AddDiagnostic;
}
#pragma warning restore 8618
private void AddDiagnostic(Diagnostic diagnostic)
{
if (_shouldSuppressGeneratedCodeDiagnostic(diagnostic, _analyzer, _compilation, _cancellationToken))
{
return;
}
if (_addCategorizedLocalDiagnostic == null)
{
Debug.Assert(_addNonCategorizedDiagnostic != null);
_addNonCategorizedDiagnostic(diagnostic);
return;
}
Debug.Assert(_addNonCategorizedDiagnostic == null);
Debug.Assert(_addCategorizedNonLocalDiagnostic != null);
if (isLocalDiagnostic(diagnostic) &&
(!_span.HasValue || _span.Value.IntersectsWith(diagnostic.Location.SourceSpan)))
{
_addCategorizedLocalDiagnostic(diagnostic, _analyzer, _isSyntaxDiagnostic);
}
else
{
_addCategorizedNonLocalDiagnostic(diagnostic, _analyzer);
}
return;
bool isLocalDiagnostic(Diagnostic diagnostic)
{
if (diagnostic.Location.IsInSource)
{
return _contextFile?.SourceTree != null &&
_contextFile.Value.SourceTree == diagnostic.Location.SourceTree;
}
if (_contextFile?.AdditionalFile != null &&
diagnostic.Location is ExternalFileLocation externalFileLocation)
{
return PathUtilities.Comparer.Equals(_contextFile.Value.AdditionalFile.Path, externalFileLocation.FilePath);
}
return false;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Tools/ExternalAccess/FSharp/Internal/Editor/FSharpSynchronousIndentationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor
{
[Shared]
[ExportLanguageService(typeof(IIndentationService), LanguageNames.FSharp)]
internal class FSharpSynchronousIndentationService : IIndentationService
{
private readonly IFSharpSynchronousIndentationService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpSynchronousIndentationService(IFSharpSynchronousIndentationService service)
{
_service = service;
}
public IndentationResult GetIndentation(Document document, int lineNumber, FormattingOptions.IndentStyle indentStyle, CancellationToken cancellationToken)
{
var result = _service.GetDesiredIndentation(document, lineNumber, cancellationToken);
if (result.HasValue)
{
return new IndentationResult(result.Value.BasePosition, result.Value.Offset);
}
else
{
return default;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor
{
[Shared]
[ExportLanguageService(typeof(IIndentationService), LanguageNames.FSharp)]
internal class FSharpSynchronousIndentationService : IIndentationService
{
private readonly IFSharpSynchronousIndentationService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpSynchronousIndentationService(IFSharpSynchronousIndentationService service)
{
_service = service;
}
public IndentationResult GetIndentation(Document document, int lineNumber, FormattingOptions.IndentStyle indentStyle, CancellationToken cancellationToken)
{
var result = _service.GetDesiredIndentation(document, lineNumber, cancellationToken);
if (result.HasValue)
{
return new IndentationResult(result.Value.BasePosition, result.Value.Offset);
}
else
{
return default;
}
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/Test/Resources/Core/NetFX/aacorlib/Key.snk | $ RSA2 +ok^q}5-8VA>&p)冀3es2[:gX:6̴ޏWOcM&顡onSb'2.5}2m
fW3b!Z["Aofj-k
ckһmj&}es!U +qM,CS.$sF*Ee-WuEWe社M42溯.$e;u6푾f̰I
h= <40Y$x|@9jJzה`}Z =5l7C2F#B5٥3ۏxctMu
P/Q1^e6
0%6$$65VgL`X@|Rt2!zLNhGca !ge&RTSs(~p)DuaȿXOF<+6U5
'[cW=E/\QSUf^掓.p@9<1?c#C{5eTf% iWS gBJC)\ {z | $ RSA2 +ok^q}5-8VA>&p)冀3es2[:gX:6̴ޏWOcM&顡onSb'2.5}2m
fW3b!Z["Aofj-k
ckһmj&}es!U +qM,CS.$sF*Ee-WuEWe社M42溯.$e;u6푾f̰I
h= <40Y$x|@9jJzה`}Z =5l7C2F#B5٥3ۏxctMu
P/Q1^e6
0%6$$65VgL`X@|Rt2!zLNhGca !ge&RTSs(~p)DuaȿXOF<+6U5
'[cW=E/\QSUf^掓.p@9<1?c#C{5eTf% iWS gBJC)\ {z | -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/CSharp/Portable/BoundTree/BoundFunctionPointerInvocation.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 Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class BoundFunctionPointerInvocation
{
public FunctionPointerTypeSymbol FunctionPointer
{
get
{
Debug.Assert(InvokedExpression.Type is FunctionPointerTypeSymbol);
return (FunctionPointerTypeSymbol)InvokedExpression.Type;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class BoundFunctionPointerInvocation
{
public FunctionPointerTypeSymbol FunctionPointer
{
get
{
Debug.Assert(InvokedExpression.Type is FunctionPointerTypeSymbol);
return (FunctionPointerTypeSymbol)InvokedExpression.Type;
}
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/VisualBasic/Portable/Binding/Binder_XmlLiterals.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.Generic
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
Private Function BindXmlComment(
syntax As XmlCommentSyntax,
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
If rootInfoOpt Is Nothing Then
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
End If
Dim str = CreateStringLiteral(syntax, GetXmlString(syntax.TextTokens), compilerGenerated:=True, diagnostics:=diagnostics)
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XComment, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(str),
diagnostics)
Return New BoundXmlComment(syntax, str, objectCreation, objectCreation.Type)
End Function
Private Function BindXmlDocument(syntax As XmlDocumentSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
Dim declaration = BindXmlDeclaration(syntax.Declaration, diagnostics)
' Match the native compiler and invoke the XDocument(XDeclaration, Params Object())
' .ctor, with Nothing for the Params array argument.
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XDocument, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(declaration, New BoundLiteral(syntax, ConstantValue.Nothing, Nothing)),
diagnostics)
Dim childNodeBuilder = ArrayBuilder(Of BoundExpression).GetInstance()
BindXmlContent(syntax.PrecedingMisc, childNodeBuilder, rootInfoOpt:=Nothing, diagnostics:=diagnostics)
childNodeBuilder.Add(BindXmlContent(syntax.Root, rootInfoOpt:=Nothing, diagnostics:=diagnostics))
BindXmlContent(syntax.FollowingMisc, childNodeBuilder, rootInfoOpt:=Nothing, diagnostics:=diagnostics)
Dim childNodes = childNodeBuilder.ToImmutableAndFree()
Dim rewriterInfo = BindXmlContainerRewriterInfo(syntax, objectCreation, childNodes, rootInfoOpt:=Nothing, diagnostics:=diagnostics)
Return New BoundXmlDocument(syntax, declaration, childNodes, rewriterInfo, objectCreation.Type, rewriterInfo.HasErrors)
End Function
Private Function BindXmlDeclaration(syntax As XmlDeclarationSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim version = BindXmlDeclarationOption(syntax, syntax.Version, diagnostics)
Dim encoding = BindXmlDeclarationOption(syntax, syntax.Encoding, diagnostics)
Dim standalone = BindXmlDeclarationOption(syntax, syntax.Standalone, diagnostics)
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XDeclaration, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(version, encoding, standalone),
diagnostics)
Return New BoundXmlDeclaration(syntax, version, encoding, standalone, objectCreation, objectCreation.Type)
End Function
Private Function BindXmlDeclarationOption(syntax As XmlDeclarationSyntax, optionSyntax As XmlDeclarationOptionSyntax, diagnostics As BindingDiagnosticBag) As BoundLiteral
If optionSyntax Is Nothing Then
Return CreateStringLiteral(syntax, Nothing, compilerGenerated:=True, diagnostics:=diagnostics)
Else
Dim value = optionSyntax.Value
Return CreateStringLiteral(value, GetXmlString(value.TextTokens), compilerGenerated:=False, diagnostics:=diagnostics)
End If
End Function
Private Function BindXmlProcessingInstruction(syntax As XmlProcessingInstructionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim target = CreateStringLiteral(syntax, GetXmlName(syntax.Name), compilerGenerated:=True, diagnostics:=diagnostics)
Dim data = CreateStringLiteral(syntax, GetXmlString(syntax.TextTokens), compilerGenerated:=True, diagnostics:=diagnostics)
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XProcessingInstruction, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(target, data),
diagnostics)
Return New BoundXmlProcessingInstruction(syntax, target, data, objectCreation, objectCreation.Type)
End Function
Private Function BindXmlEmptyElement(
syntax As XmlEmptyElementSyntax,
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
Return BindXmlElement(syntax, syntax.Name, syntax.Attributes, Nothing, rootInfoOpt, diagnostics)
End Function
Private Function BindXmlElement(
syntax As XmlElementSyntax,
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
Dim startTag = syntax.StartTag
Return BindXmlElement(syntax, startTag.Name, startTag.Attributes, syntax.Content, rootInfoOpt, diagnostics)
End Function
Private Function BindXmlElement(
syntax As XmlNodeSyntax,
nameSyntax As XmlNodeSyntax,
attributes As SyntaxList(Of XmlNodeSyntax),
content As SyntaxList(Of XmlNodeSyntax),
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
If rootInfoOpt Is Nothing Then
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
' 'importedNamespaces' is the set of Imports statements that are referenced
' within the XmlElement, represented as { prefix, namespace } pairs. The set is
' used to ensure the necessary xmlns attributes are added to the resulting XML at
' runtime. The set is represented as a flat list rather than a dictionary so that the
' order of the xmlns attributes matches the XML generated by the native compiler.
Dim importedNamespaces = ArrayBuilder(Of KeyValuePair(Of String, String)).GetInstance()
Dim binder = New XmlRootElementBinder(Me)
Dim result = binder.BindXmlElement(syntax, nameSyntax, attributes, content, New XmlElementRootInfo(Me, syntax, importedNamespaces), diagnostics)
importedNamespaces.Free()
Return result
Else
Dim allAttributes As Dictionary(Of XmlName, BoundXmlAttribute) = Nothing
Dim xmlnsAttributes = ArrayBuilder(Of BoundXmlAttribute).GetInstance()
Dim otherAttributes = ArrayBuilder(Of XmlNodeSyntax).GetInstance()
Dim namespaces = BindXmlnsAttributes(attributes, allAttributes, xmlnsAttributes, otherAttributes, rootInfoOpt.ImportedNamespaces, diagnostics)
Debug.Assert((namespaces Is Nothing) OrElse (namespaces.Count > 0))
Dim binder = If(namespaces Is Nothing, Me, New XmlElementBinder(Me, namespaces))
Dim result = binder.BindXmlElementWithoutAddingNamespaces(syntax, nameSyntax, allAttributes, xmlnsAttributes, otherAttributes, content, rootInfoOpt, diagnostics)
otherAttributes.Free()
xmlnsAttributes.Free()
Return result
End If
End Function
Private Function BindXmlElementWithoutAddingNamespaces(
syntax As XmlNodeSyntax,
nameSyntax As XmlNodeSyntax,
<Out()> ByRef allAttributes As Dictionary(Of XmlName, BoundXmlAttribute),
xmlnsAttributes As ArrayBuilder(Of BoundXmlAttribute),
otherAttributes As ArrayBuilder(Of XmlNodeSyntax),
content As SyntaxList(Of XmlNodeSyntax),
rootInfo As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
' Any expression type is allowed as long as there is an appropriate XElement
' constructor for that argument type. In particular, this allows expressions of type
' XElement since XElement includes New(other As XElement). This is consistent with
' the native compiler, but contradicts the spec (11.23.4: "... the embedded expression
' must be a value of a type implicitly convertible to System.Xml.Linq.XName").
Dim argument As BoundExpression
If nameSyntax.Kind = SyntaxKind.XmlEmbeddedExpression Then
argument = BindXmlEmbeddedExpression(DirectCast(nameSyntax, XmlEmbeddedExpressionSyntax), diagnostics:=diagnostics)
Else
Dim fromImports = False
Dim prefix As String = Nothing
Dim localName As String = Nothing
Dim [namespace] As String = Nothing
argument = BindXmlName(DirectCast(nameSyntax, XmlNameSyntax), forElement:=True, rootInfoOpt:=rootInfo, fromImports:=fromImports, prefix:=prefix, localName:=localName, [namespace]:=[namespace], diagnostics:=diagnostics)
If fromImports Then
AddImportedNamespaceIfNecessary(rootInfo.ImportedNamespaces, prefix, [namespace], forElement:=True)
End If
End If
' Expression* .Semantics::InterpretXmlName( [ ParseTree::Expression* Expr ] [ BCSym.[Alias]** ResolvedPrefix ] )
' . . .
'If NameExpr.ResultType Is GetFXSymbolProvider().GetObjectType() AndAlso Not m_UsingOptionTypeStrict Then
' NameExpr = AllocateExpression( _
' BILOP.SX_DIRECTCAST, _
' m_XmlSymbols.GetXName(), _
' NameExpr, _
' NameExpr.Loc)
'End If
If argument.Type.IsObjectType AndAlso OptionStrict <> VisualBasic.OptionStrict.On Then
Dim xnameType = GetWellKnownType(WellKnownType.System_Xml_Linq_XName, syntax, diagnostics)
argument = ApplyDirectCastConversion(syntax, argument, xnameType, diagnostics:=diagnostics)
End If
Dim objectCreation = BindObjectCreationExpression(
nameSyntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XElement, nameSyntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(argument),
diagnostics)
Dim childNodeBuilder = ArrayBuilder(Of BoundExpression).GetInstance()
For Each xmlnsAttribute In xmlnsAttributes
childNodeBuilder.Add(xmlnsAttribute)
Next
Debug.Assert(otherAttributes.All(Function(a) (a.Kind = SyntaxKind.XmlAttribute) OrElse (a.Kind = SyntaxKind.XmlEmbeddedExpression)))
BindXmlAttributes(allAttributes, otherAttributes, childNodeBuilder, rootInfo, diagnostics)
If syntax.Kind <> SyntaxKind.XmlEmptyElement Then
If content.Count > 0 Then
BindXmlContent(content, childNodeBuilder, rootInfo, diagnostics)
Else
' An XElement with a start and end tag but no content. Include a compiler-
' generated empty string as content for consistency with the native compiler.
' (This also ensures <x></x> is serialized as <x></x> rather than <x/>.)
childNodeBuilder.Add(CreateStringLiteral(syntax, String.Empty, compilerGenerated:=True, diagnostics:=diagnostics))
End If
End If
Dim childNodes = childNodeBuilder.ToImmutableAndFree()
Dim rewriterInfo = BindXmlContainerRewriterInfo(syntax, objectCreation, childNodes, rootInfo, diagnostics)
Return New BoundXmlElement(syntax, argument, childNodes, rewriterInfo, objectCreation.Type, rewriterInfo.HasErrors)
End Function
Private Function BindXmlContainerRewriterInfo(
syntax As XmlNodeSyntax,
objectCreation As BoundExpression,
childNodes As ImmutableArray(Of BoundExpression),
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundXmlContainerRewriterInfo
If (childNodes.Length = 0) AndAlso
((rootInfoOpt Is Nothing) OrElse (rootInfoOpt.ImportedNamespaces.Count = 0)) Then
Return New BoundXmlContainerRewriterInfo(objectCreation)
End If
Dim placeholder = (New BoundRValuePlaceholder(syntax, objectCreation.Type)).MakeCompilerGenerated()
Dim sideEffectBuilder = ArrayBuilder(Of BoundExpression).GetInstance()
Dim addGroup = GetXmlMethodOrPropertyGroup(syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XContainer, syntax, diagnostics),
StringConstants.XmlAddMethodName,
placeholder,
diagnostics)
' The following are arguments to
' InternalXmlHelper.RemoveNamespaceAttributes(prefixes As String(),
' namespaces As XNamespace(), attributes As List(Of XAttribute), arg As XElement) As XElement
Dim inScopeXmlNamespaces As ImmutableArray(Of KeyValuePair(Of String, String)) = Nothing
Dim prefixesPlaceholder As BoundRValuePlaceholder = Nothing
Dim namespacesPlaceholder As BoundRValuePlaceholder = Nothing
For Each childNode In childNodes
' Skip attributes that match imports since those are redundant.
If (childNode.Kind = BoundKind.XmlAttribute) AndAlso DirectCast(childNode, BoundXmlAttribute).MatchesImport Then
Continue For
End If
' Any namespaces from Imports <xmlns:p="..."> that were used within an
' XElement require xmlns:p="..." attributes to be added to the root of the XML.
' (The xmlns declarations are added to the root to generate the simplest XML.)
' If the XML contains embedded expressions, those embedded expressions may
' also reference namespaces. For instance, the XML generated at runtime for
' <x <%= <p:y/> %>/> should be <x xmlns:p="..."><p:y/></x>. In general, these
' cases of embedded expressions are handled by adding xmlns attributes
' to the root of the XML within the embedded expression, then using methods
' at runtime (when stitching together the XML) to move any attributes to the
' containing XML. For instance, for <x <%= e %>/> we generate the following code:
'
' Dim prefixes As New String() From { ... } ' prefixes in use at 'x'
' Dim namespaces As New XNamespace() From { ... } ' namespaces in use at 'x'
' Dim attribs As New List(Of XAttribute) ' attributes on 'x' plus any removed from 'e'
' e = InternalXmlHelper.RemoveNamespaceAttributes(prefixes, namespaces, attribs, e)
' x.Add(attribs)
' x.Add(e)
'
' In a handful of cases where the namespaces on the embedded expression can
' be determined at compile time, the native compiler avoids the cost of calling
' RemoveNamespaceAttributes by moving namespaces at compile time. (See
' XmlSemantics::TraceLinqExpression.) That is an optimization only and for simplicity
' is not included. (If we do add static analysis, we'll need to handle cases where
' embedded expressions contain both namespaces that can be determined at compile
' time and namespaces that may be included at runtime. For instance, the expression
' <p:y> in <x <%= <p:y><%= e %></p:y> %>/> uses "p" but may also use namespaces
' in <%= e %>.)
Dim expr = childNode
Debug.Assert(expr.Type IsNot Nothing)
' If rootInfoOpt Is Nothing, we're binding an XDocument, not an XElement,
' in which case it's not possible to remove embedded xmlns attributes.
If (rootInfoOpt IsNot Nothing) AndAlso
(expr.Kind = BoundKind.XmlEmbeddedExpression) AndAlso
HasImportedXmlNamespaces AndAlso
Not expr.Type.IsIntrinsicOrEnumType() Then
If inScopeXmlNamespaces.IsDefault Then
Dim builder = ArrayBuilder(Of KeyValuePair(Of String, String)).GetInstance()
GetInScopeXmlNamespaces(builder)
inScopeXmlNamespaces = builder.ToImmutableAndFree()
End If
If prefixesPlaceholder Is Nothing Then
Dim prefixesType = CreateArrayType(GetSpecialType(SpecialType.System_String, syntax, diagnostics))
prefixesPlaceholder = (New BoundRValuePlaceholder(syntax, prefixesType)).MakeCompilerGenerated()
Dim namespacesType = CreateArrayType(GetWellKnownType(WellKnownType.System_Xml_Linq_XNamespace, syntax, diagnostics))
namespacesPlaceholder = (New BoundRValuePlaceholder(syntax, namespacesType)).MakeCompilerGenerated()
End If
' Generate update to child using RemoveNamespaceAttributes.
expr = rootInfoOpt.BindRemoveNamespaceAttributesInvocation(expr, prefixesPlaceholder, namespacesPlaceholder, diagnostics)
End If
sideEffectBuilder.Add(BindInvocationExpressionIfGroupNotNothing(syntax, addGroup, ImmutableArray.Create(Of BoundExpression)(expr), diagnostics))
Next
Dim xmlnsAttributesPlaceholder As BoundRValuePlaceholder = Nothing
Dim xmlnsAttributes As BoundExpression = Nothing
' At the root element, add any xmlns attributes required from Imports,
' and any xmlns attributes removed from embedded expressions.
Dim isRoot = (rootInfoOpt IsNot Nothing) AndAlso (rootInfoOpt.Syntax Is syntax)
If isRoot Then
' Imports declarations are added in the reverse order that the
' prefixes were discovered, to match the native compiler.
Dim importedNamespaces = rootInfoOpt.ImportedNamespaces
For i = importedNamespaces.Count - 1 To 0 Step -1
Dim pair = importedNamespaces(i)
Dim attribute = BindXmlnsAttribute(syntax, pair.Key, pair.Value, diagnostics)
sideEffectBuilder.Add(BindInvocationExpressionIfGroupNotNothing(syntax, addGroup, ImmutableArray.Create(Of BoundExpression)(attribute), diagnostics))
Next
' Add any xmlns attributes from embedded expressions. (If there were
' any embedded expressions, XmlnsAttributesPlaceholder will be set.)
xmlnsAttributesPlaceholder = rootInfoOpt.XmlnsAttributesPlaceholder
If xmlnsAttributesPlaceholder IsNot Nothing Then
xmlnsAttributes = BindObjectCreationExpression(syntax, xmlnsAttributesPlaceholder.Type, ImmutableArray(Of BoundExpression).Empty, diagnostics).MakeCompilerGenerated()
sideEffectBuilder.Add(BindInvocationExpressionIfGroupNotNothing(syntax, addGroup, ImmutableArray.Create(Of BoundExpression)(xmlnsAttributesPlaceholder), diagnostics))
End If
End If
Return New BoundXmlContainerRewriterInfo(
isRoot,
placeholder,
objectCreation,
xmlnsAttributesPlaceholder:=xmlnsAttributesPlaceholder,
xmlnsAttributes:=xmlnsAttributes,
prefixesPlaceholder:=prefixesPlaceholder,
namespacesPlaceholder:=namespacesPlaceholder,
importedNamespaces:=If(isRoot, rootInfoOpt.ImportedNamespaces.ToImmutable(), Nothing),
inScopeXmlNamespaces:=inScopeXmlNamespaces,
sideEffects:=sideEffectBuilder.ToImmutableAndFree())
End Function
Private Function BindRemoveNamespaceAttributesInvocation(
syntax As VisualBasicSyntaxNode,
expr As BoundExpression,
prefixesPlaceholder As BoundRValuePlaceholder,
namespacesPlaceholder As BoundRValuePlaceholder,
<Out()> ByRef xmlnsAttributesPlaceholder As BoundRValuePlaceholder,
<Out()> ByRef removeNamespacesGroup As BoundMethodOrPropertyGroup,
diagnostics As BindingDiagnosticBag) As BoundExpression
If xmlnsAttributesPlaceholder Is Nothing Then
Dim listType = GetWellKnownType(WellKnownType.System_Collections_Generic_List_T, syntax, diagnostics).Construct(
GetWellKnownType(WellKnownType.System_Xml_Linq_XAttribute, syntax, diagnostics))
xmlnsAttributesPlaceholder = (New BoundRValuePlaceholder(syntax, listType)).MakeCompilerGenerated()
' Generate method group and arguments for RemoveNamespaceAttributes.
removeNamespacesGroup = GetXmlMethodOrPropertyGroup(syntax,
GetInternalXmlHelperType(syntax, diagnostics),
StringConstants.XmlRemoveNamespaceAttributesMethodName,
Nothing,
diagnostics)
End If
' Invoke RemoveNamespaceAttributes.
Return BindInvocationExpressionIfGroupNotNothing(expr.Syntax,
removeNamespacesGroup,
ImmutableArray.Create(Of BoundExpression)(prefixesPlaceholder, namespacesPlaceholder, xmlnsAttributesPlaceholder, expr),
diagnostics).MakeCompilerGenerated()
End Function
Private Function CreateArrayType(elementType As TypeSymbol) As ArrayTypeSymbol
Return ArrayTypeSymbol.CreateSZArray(elementType, ImmutableArray(Of CustomModifier).Empty, compilation:=Compilation)
End Function
Private Shared Function GetXmlnsXmlName(prefix As String) As XmlName
Dim localName = If(String.IsNullOrEmpty(prefix), StringConstants.XmlnsPrefix, prefix)
Dim [namespace] = If(String.IsNullOrEmpty(prefix), StringConstants.DefaultXmlNamespace, StringConstants.XmlnsNamespace)
Return New XmlName(localName, [namespace])
End Function
Private Function BindXmlnsAttribute(
syntax As XmlNodeSyntax,
prefix As String,
namespaceName As String,
diagnostics As BindingDiagnosticBag) As BoundXmlAttribute
Dim name = BindXmlnsName(syntax, prefix, compilerGenerated:=True, diagnostics:=diagnostics)
Dim [namespace] = BindXmlNamespace(syntax,
CreateStringLiteral(syntax, namespaceName, compilerGenerated:=True, diagnostics:=diagnostics),
diagnostics)
Return BindXmlnsAttribute(syntax, name, [namespace], useConstructor:=False, matchesImport:=False, compilerGenerated:=True, hasErrors:=False, diagnostics:=diagnostics)
End Function
Private Function BindXmlnsName(
syntax As XmlNodeSyntax,
prefix As String,
compilerGenerated As Boolean,
diagnostics As BindingDiagnosticBag) As BoundExpression
Dim name = GetXmlnsXmlName(prefix)
Return BindXmlName(syntax,
CreateStringLiteral(syntax,
name.LocalName,
compilerGenerated,
diagnostics),
CreateStringLiteral(syntax,
name.XmlNamespace,
compilerGenerated,
diagnostics),
diagnostics)
End Function
Private Function BindXmlnsAttribute(
syntax As XmlNodeSyntax,
prefix As BoundExpression,
[namespace] As BoundExpression,
useConstructor As Boolean,
matchesImport As Boolean,
compilerGenerated As Boolean,
hasErrors As Boolean,
diagnostics As BindingDiagnosticBag) As BoundXmlAttribute
Dim objectCreation As BoundExpression
If useConstructor Then
objectCreation = BindObjectCreationExpression(syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XAttribute, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(prefix, [namespace]),
diagnostics)
Else
Dim type = GetInternalXmlHelperType(syntax, diagnostics)
Dim group = GetXmlMethodOrPropertyGroup(syntax, type, StringConstants.XmlCreateNamespaceAttributeMethodName, Nothing, diagnostics)
objectCreation = BindInvocationExpressionIfGroupNotNothing(syntax, group, ImmutableArray.Create(Of BoundExpression)(prefix, [namespace]), diagnostics)
End If
Dim result = New BoundXmlAttribute(syntax, prefix, [namespace], matchesImport, objectCreation, objectCreation.Type, hasErrors)
If compilerGenerated Then
result.SetWasCompilerGenerated()
End If
Return result
End Function
Private Function BindXmlAttribute(
syntax As XmlAttributeSyntax,
rootInfo As XmlElementRootInfo,
<Out()> ByRef xmlName As XmlName,
diagnostics As BindingDiagnosticBag) As BoundXmlAttribute
Dim nameSyntax = syntax.Name
Dim name As BoundExpression
If nameSyntax.Kind = SyntaxKind.XmlEmbeddedExpression Then
name = BindXmlEmbeddedExpression(DirectCast(nameSyntax, XmlEmbeddedExpressionSyntax), diagnostics:=diagnostics)
xmlName = Nothing
Else
Dim fromImports = False
Dim prefix As String = Nothing
Dim localName As String = Nothing
Dim [namespace] As String = Nothing
name = BindXmlName(
DirectCast(nameSyntax, XmlNameSyntax),
forElement:=False,
rootInfoOpt:=rootInfo,
fromImports:=fromImports,
prefix:=prefix,
localName:=localName,
[namespace]:=[namespace],
diagnostics:=diagnostics)
If fromImports Then
AddImportedNamespaceIfNecessary(rootInfo.ImportedNamespaces, prefix, [namespace], forElement:=False)
End If
xmlName = New XmlName(localName, [namespace])
End If
Dim value As BoundExpression
Dim objectCreation As BoundExpression
Dim valueSyntax = syntax.Value
Dim matchesImport As Boolean = False
If valueSyntax.Kind = SyntaxKind.XmlEmbeddedExpression Then
' Use InternalXmlHelper.CreateAttribute rather than 'New XAttribute()' for attributes
' with embedded expression values since CreateAttribute handles Nothing values.
value = BindXmlEmbeddedExpression(DirectCast(valueSyntax, XmlEmbeddedExpressionSyntax), diagnostics)
Dim group = GetXmlMethodOrPropertyGroup(valueSyntax,
GetInternalXmlHelperType(syntax, diagnostics),
StringConstants.XmlCreateAttributeMethodName,
Nothing,
diagnostics)
objectCreation = BindInvocationExpressionIfGroupNotNothing(valueSyntax,
group,
ImmutableArray.Create(Of BoundExpression)(name, value),
diagnostics)
Else
Dim str = GetXmlString(DirectCast(valueSyntax, XmlStringSyntax).TextTokens)
' Mark if this attribute is an xmlns declaration that matches an Imports,
' since xmlns declarations from Imports will be added directly at the
' XmlElement root, and this attribute can be dropped then.
matchesImport = (nameSyntax.Kind = SyntaxKind.XmlName) AndAlso MatchesXmlnsImport(DirectCast(nameSyntax, XmlNameSyntax), str)
value = CreateStringLiteral(valueSyntax, str, compilerGenerated:=False, diagnostics:=diagnostics)
objectCreation = BindObjectCreationExpression(nameSyntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XAttribute, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(name, value),
diagnostics)
End If
Return New BoundXmlAttribute(syntax, name, value, matchesImport, objectCreation, objectCreation.Type)
End Function
''' <summary>
''' Returns True if the xmlns { prefix, namespace } pair matches
''' an Imports declaration and there aren't any xmlns declarations
''' for the same prefix on any outer XElement scopes.
''' </summary>
Private Function MatchesXmlnsImport(prefix As String, [namespace] As String) As Boolean
Dim fromImports As Boolean = False
Dim otherNamespace As String = Nothing
Return LookupXmlNamespace(prefix, False, otherNamespace, fromImports) AndAlso
fromImports AndAlso
([namespace] = otherNamespace)
End Function
Private Function MatchesXmlnsImport(name As XmlNameSyntax, value As String) As Boolean
Dim prefix As String = Nothing
TryGetXmlnsPrefix(name, prefix, BindingDiagnosticBag.Discarded)
If prefix Is Nothing Then
Return False
End If
' Match using containing Binder since this Binder
' contains this xmlns attribute in XmlNamespaces.
Return ContainingBinder.MatchesXmlnsImport(prefix, value)
End Function
''' <summary>
''' Bind the expression within the XmlEmbeddedExpressionSyntax,
''' and wrap in a BoundXmlEmbeddedExpression.
''' </summary>
Private Function BindXmlEmbeddedExpression(syntax As XmlEmbeddedExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim binder = New XmlEmbeddedExpressionBinder(Me)
Dim expr = binder.BindRValue(syntax.Expression, diagnostics)
Debug.Assert(expr IsNot Nothing)
Debug.Assert(expr.Type IsNot Nothing)
Return New BoundXmlEmbeddedExpression(syntax, expr, expr.Type)
End Function
Private Sub BindXmlAttributes(
<Out()> ByRef allAttributes As Dictionary(Of XmlName, BoundXmlAttribute),
attributes As ArrayBuilder(Of XmlNodeSyntax),
childNodeBuilder As ArrayBuilder(Of BoundExpression),
rootInfo As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag)
For Each childSyntax In attributes
If childSyntax.Kind = SyntaxKind.XmlAttribute Then
Dim attributeSyntax = DirectCast(childSyntax, XmlAttributeSyntax)
Dim name As XmlName = Nothing
Dim attribute = BindXmlAttribute(attributeSyntax, rootInfo, name, diagnostics)
childNodeBuilder.Add(attribute)
' Name may be Nothing for embedded expressions.
' Otherwise, check for duplicates.
If name.LocalName IsNot Nothing Then
AddXmlAttributeIfNotDuplicate(attributeSyntax.Name, name, attribute, allAttributes, diagnostics)
End If
Else
Dim child = BindXmlContent(childSyntax, rootInfo, diagnostics)
childNodeBuilder.Add(child)
End If
Next
End Sub
Private Structure XmlName
Public Sub New(localName As String, [namespace] As String)
Me.LocalName = localName
Me.XmlNamespace = [namespace]
End Sub
Public ReadOnly LocalName As String
Public ReadOnly XmlNamespace As String
End Structure
Private NotInheritable Class XmlNameComparer
Implements IEqualityComparer(Of XmlName)
Public Shared ReadOnly Instance As New XmlNameComparer()
Private Function IEqualityComparer_Equals(x As XmlName, y As XmlName) As Boolean Implements IEqualityComparer(Of XmlName).Equals
Return String.Equals(x.LocalName, y.LocalName, StringComparison.Ordinal) AndAlso String.Equals(x.XmlNamespace, y.XmlNamespace, StringComparison.Ordinal)
End Function
Private Function IEqualityComparer_GetHashCode(obj As XmlName) As Integer Implements IEqualityComparer(Of XmlName).GetHashCode
Dim result = obj.LocalName.GetHashCode()
If obj.XmlNamespace IsNot Nothing Then
result = Hash.Combine(result, obj.XmlNamespace.GetHashCode())
End If
Return result
End Function
End Class
Private Sub BindXmlContent(content As SyntaxList(Of XmlNodeSyntax), childNodeBuilder As ArrayBuilder(Of BoundExpression), rootInfoOpt As XmlElementRootInfo, diagnostics As BindingDiagnosticBag)
For Each childSyntax In content
childNodeBuilder.Add(BindXmlContent(childSyntax, rootInfoOpt, diagnostics))
Next
End Sub
Private Function BindXmlContent(syntax As XmlNodeSyntax, rootInfoOpt As XmlElementRootInfo, diagnostics As BindingDiagnosticBag) As BoundExpression
Select Case syntax.Kind
Case SyntaxKind.XmlProcessingInstruction
Return BindXmlProcessingInstruction(DirectCast(syntax, XmlProcessingInstructionSyntax), diagnostics)
Case SyntaxKind.XmlComment
Return BindXmlComment(DirectCast(syntax, XmlCommentSyntax), rootInfoOpt, diagnostics)
Case SyntaxKind.XmlElement
Return BindXmlElement(DirectCast(syntax, XmlElementSyntax), rootInfoOpt, diagnostics)
Case SyntaxKind.XmlEmptyElement
Return BindXmlEmptyElement(DirectCast(syntax, XmlEmptyElementSyntax), rootInfoOpt, diagnostics)
Case SyntaxKind.XmlEmbeddedExpression
Return BindXmlEmbeddedExpression(DirectCast(syntax, XmlEmbeddedExpressionSyntax), diagnostics)
Case SyntaxKind.XmlCDataSection
Return BindXmlCData(DirectCast(syntax, XmlCDataSectionSyntax), rootInfoOpt, diagnostics)
Case SyntaxKind.XmlText
Return BindXmlText(DirectCast(syntax, XmlTextSyntax), diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(syntax.Kind)
End Select
End Function
Private Function BindXmlAttributeAccess(syntax As XmlMemberAccessExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
Dim receiver = BindXmlMemberAccessReceiver(syntax, diagnostics)
Dim nameSyntax = If(syntax.Name.Kind = SyntaxKind.XmlName,
DirectCast(syntax.Name, XmlNameSyntax),
DirectCast(syntax.Name, XmlBracketedNameSyntax).Name)
Dim name = BindXmlName(nameSyntax, forElement:=False, diagnostics:=diagnostics)
Dim receiverType = receiver.Type
Debug.Assert(receiverType IsNot Nothing)
Dim memberAccess As BoundExpression = Nothing
If receiverType.SpecialType = SpecialType.System_Object Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoXmlAxesLateBinding)
ElseIf Not receiverType.IsErrorType() Then
Dim group As BoundMethodOrPropertyGroup = Nothing
' Determine the appropriate overload, allowing
' XElement or IEnumerable(Of XElement) argument.
Dim xmlType = GetWellKnownType(WellKnownType.System_Xml_Linq_XElement, syntax, diagnostics)
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If receiverType.IsOrDerivedFrom(xmlType, useSiteInfo) OrElse receiverType.IsCompatibleWithGenericIEnumerableOfType(xmlType, useSiteInfo) Then
group = GetXmlMethodOrPropertyGroup(syntax,
GetInternalXmlHelperType(syntax, diagnostics),
StringConstants.XmlAttributeValueMethodName,
Nothing,
diagnostics)
End If
diagnostics.Add(syntax, useSiteInfo)
If group IsNot Nothing Then
memberAccess = BindInvocationExpressionIfGroupNotNothing(syntax, group, ImmutableArray.Create(Of BoundExpression)(receiver, name), diagnostics)
memberAccess = MakeValue(memberAccess, diagnostics)
Else
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_TypeDisallowsAttributes, receiverType)
End If
End If
If memberAccess Is Nothing Then
memberAccess = BadExpression(syntax, ImmutableArray.Create(receiver, name), Compilation.GetSpecialType(SpecialType.System_String))
End If
Return New BoundXmlMemberAccess(syntax, memberAccess, memberAccess.Type)
End Function
Private Function BindXmlElementAccess(syntax As XmlMemberAccessExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Return BindXmlElementAccess(syntax, StringConstants.XmlElementsMethodName, ERRID.ERR_TypeDisallowsElements, diagnostics)
End Function
Private Function BindXmlDescendantAccess(syntax As XmlMemberAccessExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Return BindXmlElementAccess(syntax, StringConstants.XmlDescendantsMethodName, ERRID.ERR_TypeDisallowsDescendants, diagnostics)
End Function
Private Function BindXmlElementAccess(syntax As XmlMemberAccessExpressionSyntax, memberName As String, typeDisallowsError As ERRID, diagnostics As BindingDiagnosticBag) As BoundExpression
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
Dim receiver = BindXmlMemberAccessReceiver(syntax, diagnostics)
Dim name = BindXmlName(DirectCast(syntax.Name, XmlBracketedNameSyntax).Name, forElement:=True, diagnostics:=diagnostics)
Dim receiverType = receiver.Type
Debug.Assert(receiverType IsNot Nothing)
Dim memberAccess As BoundExpression = Nothing
If receiverType.SpecialType = SpecialType.System_Object Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoXmlAxesLateBinding)
ElseIf Not receiverType.IsErrorType() Then
Dim group As BoundMethodOrPropertyGroup = Nothing
Dim arguments As ImmutableArray(Of BoundExpression) = Nothing
' Determine the appropriate overload, allowing
' XContainer or IEnumerable(Of XContainer) argument.
Dim xmlType = GetWellKnownType(WellKnownType.System_Xml_Linq_XContainer, syntax, diagnostics)
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If receiverType.IsOrDerivedFrom(xmlType, useSiteInfo) Then
group = GetXmlMethodOrPropertyGroup(syntax,
xmlType,
memberName,
receiver,
diagnostics)
arguments = ImmutableArray.Create(Of BoundExpression)(name)
ElseIf receiverType.IsCompatibleWithGenericIEnumerableOfType(xmlType, useSiteInfo) Then
group = GetXmlMethodOrPropertyGroup(syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_Extensions, syntax, diagnostics),
memberName,
Nothing,
diagnostics)
arguments = ImmutableArray.Create(Of BoundExpression)(receiver, name)
End If
diagnostics.Add(syntax, useSiteInfo)
If group IsNot Nothing Then
memberAccess = BindInvocationExpressionIfGroupNotNothing(syntax, group, arguments, diagnostics)
memberAccess = MakeRValue(memberAccess, diagnostics)
Else
ReportDiagnostic(diagnostics, syntax, typeDisallowsError, receiverType)
End If
End If
If memberAccess Is Nothing Then
memberAccess = BadExpression(syntax, ImmutableArray.Create(receiver, name), ErrorTypeSymbol.UnknownResultType)
End If
Return New BoundXmlMemberAccess(syntax, memberAccess, memberAccess.Type)
End Function
Private Function BindXmlMemberAccessReceiver(syntax As XmlMemberAccessExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
If syntax.Base Is Nothing Then
Dim receiver As BoundExpression
Dim conditionalAccess As ConditionalAccessExpressionSyntax = syntax.GetCorrespondingConditionalAccessExpression()
If conditionalAccess IsNot Nothing Then
receiver = GetConditionalAccessReceiver(conditionalAccess)
Else
receiver = TryBindOmittedLeftForXmlMemberAccess(syntax, diagnostics, Me)
End If
If receiver Is Nothing Then
Return ReportDiagnosticAndProduceBadExpression(diagnostics, syntax, ERRID.ERR_BadWithRef)
End If
Return receiver
Else
Dim receiver = BindValue(syntax.Base, diagnostics)
Debug.Assert(receiver IsNot Nothing)
Return AdjustReceiverValue(receiver, syntax, diagnostics)
End If
End Function
Private Function BindXmlName(
syntax As XmlNameSyntax,
forElement As Boolean,
diagnostics As BindingDiagnosticBag) As BoundExpression
Dim fromImports = False
Dim prefix As String = Nothing
Dim localName As String = Nothing
Dim [namespace] As String = Nothing
Return BindXmlName(syntax, forElement, Nothing, fromImports, prefix, localName, [namespace], diagnostics)
End Function
Private Function BindXmlName(
syntax As XmlNameSyntax,
forElement As Boolean,
rootInfoOpt As XmlElementRootInfo,
<Out()> ByRef fromImports As Boolean,
<Out()> ByRef prefix As String,
<Out()> ByRef localName As String,
<Out()> ByRef [namespace] As String,
diagnostics As BindingDiagnosticBag) As BoundExpression
Dim prefixSyntax = syntax.Prefix
Dim namespaceExpr As BoundLiteral
fromImports = False
localName = GetXmlName(syntax.LocalName)
[namespace] = Nothing
If prefixSyntax IsNot Nothing Then
Dim prefixToken = prefixSyntax.Name
prefix = GetXmlName(prefixToken)
If forElement AndAlso (prefix = StringConstants.XmlnsPrefix) Then
' "Element names cannot use the 'xmlns' prefix."
ReportDiagnostic(diagnostics, prefixToken, ERRID.ERR_IllegalXmlnsPrefix)
Return BadExpression(syntax, Compilation.GetSpecialType(SpecialType.System_String))
End If
If Not LookupXmlNamespace(prefix, False, [namespace], fromImports) Then
Return ReportXmlNamespacePrefixNotDefined(syntax, prefixSyntax.Name, prefix, compilerGenerated:=False, diagnostics:=diagnostics)
End If
namespaceExpr = CreateStringLiteral(prefixSyntax, [namespace], compilerGenerated:=False, diagnostics:=diagnostics)
Else
prefix = StringConstants.DefaultXmlnsPrefix
If forElement Then
Dim found = LookupXmlNamespace(prefix, False, [namespace], fromImports)
Debug.Assert(found)
Else
[namespace] = StringConstants.DefaultXmlNamespace
End If
namespaceExpr = CreateStringLiteral(syntax, [namespace], compilerGenerated:=True, diagnostics:=diagnostics)
End If
' LocalName is marked as CompilerGenerated to avoid confusing the semantic model
' with two BoundNodes (LocalName and entire XName) for the same syntax node.
Dim localNameExpr = CreateStringLiteral(syntax, localName, compilerGenerated:=True, diagnostics:=diagnostics)
Return BindXmlName(syntax, localNameExpr, namespaceExpr, diagnostics)
End Function
Private Shared Sub AddImportedNamespaceIfNecessary(
importedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String)),
prefix As String,
[namespace] As String,
forElement As Boolean)
Debug.Assert(prefix IsNot Nothing)
Debug.Assert([namespace] IsNot Nothing)
' If the namespace is the default, create an xmlns="" attribute
' if the reference was for an XmlElement name. Otherwise,
' avoid adding an attribute for the default namespace.
If [namespace] = StringConstants.DefaultXmlNamespace Then
If Not forElement OrElse (prefix = StringConstants.DefaultXmlnsPrefix) Then
Return
End If
prefix = StringConstants.DefaultXmlnsPrefix
End If
For Each pair In importedNamespaces
If pair.Key = prefix Then
Return
End If
Next
importedNamespaces.Add(New KeyValuePair(Of String, String)(prefix, [namespace]))
End Sub
Private Function BindXmlName(syntax As VisualBasicSyntaxNode, localName As BoundExpression, [namespace] As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim group = GetXmlMethodOrPropertyGroup(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XName, syntax, diagnostics),
StringConstants.XmlGetMethodName,
Nothing,
diagnostics)
Dim objectCreation = BindInvocationExpressionIfGroupNotNothing(syntax, group, ImmutableArray.Create(Of BoundExpression)(localName, [namespace]), diagnostics)
Return New BoundXmlName(syntax, [namespace], localName, objectCreation, objectCreation.Type)
End Function
Private Function BindGetXmlNamespace(syntax As GetXmlNamespaceExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
Dim nameSyntax = syntax.Name
Dim [namespace] As String = Nothing
Dim fromImports = False
Dim expr As BoundExpression
If nameSyntax IsNot Nothing Then
Dim prefixToken = nameSyntax.Name
Dim prefix = GetXmlName(prefixToken)
If LookupXmlNamespace(prefix, False, [namespace], fromImports) Then
expr = CreateStringLiteral(nameSyntax, [namespace], compilerGenerated:=False, diagnostics:=diagnostics)
Else
expr = ReportXmlNamespacePrefixNotDefined(nameSyntax, prefixToken, prefix, compilerGenerated:=False, diagnostics:=diagnostics)
End If
Else
Dim found = LookupXmlNamespace(StringConstants.DefaultXmlnsPrefix, False, [namespace], fromImports)
Debug.Assert(found)
expr = CreateStringLiteral(syntax, [namespace], compilerGenerated:=True, diagnostics:=diagnostics)
End If
Return BindXmlNamespace(syntax, expr, diagnostics)
End Function
Private Function BindXmlNamespace(syntax As VisualBasicSyntaxNode, [namespace] As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim group = GetXmlMethodOrPropertyGroup(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XNamespace, syntax, diagnostics),
StringConstants.XmlGetMethodName,
Nothing,
diagnostics)
Dim objectCreation = BindInvocationExpressionIfGroupNotNothing(syntax, group, ImmutableArray.Create(Of BoundExpression)([namespace]), diagnostics)
Return New BoundXmlNamespace(syntax, [namespace], objectCreation, objectCreation.Type)
End Function
Private Function ReportXmlNamespacePrefixNotDefined(syntax As VisualBasicSyntaxNode, prefixToken As SyntaxToken, prefix As String, compilerGenerated As Boolean, diagnostics As BindingDiagnosticBag) As BoundBadExpression
Debug.Assert(prefix IsNot Nothing)
Debug.Assert(prefix = GetXmlName(prefixToken))
' "XML namespace prefix '{0}' is not defined."
ReportDiagnostic(diagnostics, prefixToken, ERRID.ERR_UndefinedXmlPrefix, prefix)
Dim result = BadExpression(syntax, Compilation.GetSpecialType(SpecialType.System_String))
If compilerGenerated Then
result.SetWasCompilerGenerated()
End If
Return result
End Function
Private Function BindXmlCData(syntax As XmlCDataSectionSyntax, rootInfoOpt As XmlElementRootInfo, diagnostics As BindingDiagnosticBag) As BoundExpression
If rootInfoOpt Is Nothing Then
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
End If
Dim value = CreateStringLiteral(syntax, GetXmlString(syntax.TextTokens), compilerGenerated:=True, diagnostics:=diagnostics)
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XCData, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(value),
diagnostics)
Return New BoundXmlCData(syntax, value, objectCreation, objectCreation.Type)
End Function
Private Function BindXmlText(syntax As XmlTextSyntax, diagnostics As BindingDiagnosticBag) As BoundLiteral
Return CreateStringLiteral(syntax, GetXmlString(syntax.TextTokens), compilerGenerated:=False, diagnostics:=diagnostics)
End Function
Friend Shared Function GetXmlString(tokens As SyntaxTokenList) As String
Dim n = tokens.Count
If n = 0 Then
Return String.Empty
ElseIf n = 1 Then
Return GetXmlString(tokens(0))
Else
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
For Each token In tokens
builder.Append(GetXmlString(token))
Next
Dim result = builder.ToString()
pooledBuilder.Free()
Return result
End If
End Function
Private Shared Function GetXmlString(token As SyntaxToken) As String
Select Case token.Kind
Case SyntaxKind.XmlTextLiteralToken, SyntaxKind.XmlEntityLiteralToken
Return token.ValueText
Case Else
Throw ExceptionUtilities.UnexpectedValue(token.Kind)
End Select
End Function
Private Function GetXmlMethodOrPropertyGroup(syntax As VisualBasicSyntaxNode, type As NamedTypeSymbol, memberName As String, receiverOpt As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundMethodOrPropertyGroup
If type.IsErrorType() Then
Return Nothing
End If
Debug.Assert((receiverOpt Is Nothing) OrElse
receiverOpt.Type.IsErrorType() OrElse
receiverOpt.Type.IsOrDerivedFrom(type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded))
Dim group As BoundMethodOrPropertyGroup = Nothing
Dim result = LookupResult.GetInstance()
' Match the lookup of XML members in the native compiler: consider members
' on this type only, not base types, and ignore extension methods or properties
' from the current scope. (Extension methods and properties will be included,
' as shared members, if the members are defined on 'type' however.)
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
LookupMember(result,
type,
memberName,
arity:=0,
options:=LookupOptions.AllMethodsOfAnyArity Or LookupOptions.NoBaseClassLookup Or LookupOptions.IgnoreExtensionMethods,
useSiteInfo:=useSiteInfo)
diagnostics.Add(syntax, useSiteInfo)
If result.IsGood Then
Debug.Assert(result.Symbols.Count > 0)
Dim symbol0 = result.Symbols(0)
Select Case result.Symbols(0).Kind
Case SymbolKind.Method
group = New BoundMethodGroup(syntax,
Nothing,
result.Symbols.ToDowncastedImmutable(Of MethodSymbol),
result.Kind,
receiverOpt,
QualificationKind.QualifiedViaValue)
Case SymbolKind.Property
group = New BoundPropertyGroup(syntax,
result.Symbols.ToDowncastedImmutable(Of PropertySymbol),
result.Kind,
receiverOpt,
QualificationKind.QualifiedViaValue)
End Select
End If
If group Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
If(result.HasDiagnostic,
result.Diagnostic,
ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, memberName, type)))
End If
result.Free()
Return group
End Function
''' <summary>
''' If the method or property group is not Nothing, bind as an invocation expression.
''' Otherwise return a BoundBadExpression containing the arguments.
''' </summary>
Private Function BindInvocationExpressionIfGroupNotNothing(syntax As SyntaxNode, groupOpt As BoundMethodOrPropertyGroup, arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag) As BoundExpression
If groupOpt Is Nothing Then
Return BadExpression(syntax, arguments, ErrorTypeSymbol.UnknownResultType)
Else
Return BindInvocationExpression(syntax,
syntax,
TypeCharacter.None,
groupOpt,
arguments,
argumentNames:=Nothing,
diagnostics:=diagnostics,
callerInfoOpt:=Nothing)
End If
End Function
''' <summary>
''' Check if XML features are allowed. If not, report an error and return a
''' separate DiagnosticBag that can be used for binding sub-expressions.
''' </summary>
Private Function CheckXmlFeaturesAllowed(syntax As VisualBasicSyntaxNode, diagnostics As BindingDiagnosticBag) As BindingDiagnosticBag
' Check if XObject is available, which matches the native compiler.
Dim type = Compilation.GetWellKnownType(WellKnownType.System_Xml_Linq_XObject)
If type.IsErrorType() Then
' "XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core."
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_XmlFeaturesNotAvailable)
' DiagnosticBag does not need to be created from the pool
' since this is an error recovery scenario only.
Return BindingDiagnosticBag.Discarded
Else
Return diagnostics
End If
End Function
Private Function CreateStringLiteral(
syntax As VisualBasicSyntaxNode,
str As String,
compilerGenerated As Boolean,
diagnostics As BindingDiagnosticBag,
Optional hasErrors As Boolean = False) As BoundLiteral
Debug.Assert(syntax IsNot Nothing)
Dim result = New BoundLiteral(syntax, ConstantValue.Create(str), GetSpecialType(SpecialType.System_String, syntax, diagnostics), hasErrors:=hasErrors)
If compilerGenerated Then
result.SetWasCompilerGenerated()
End If
Return result
End Function
''' <summary>
''' Bind any xmlns declaration attributes and return the bound nodes plus a Dictionary
''' of { prefix, namespace } pairs that will be used for namespace lookup at and below
''' the containing XmlElement. Any xmlns declarations that are redundant with Imports
''' in scope (same prefix and namespace) are dropped, and instead, an entry is added
''' to the 'importedNamespaces' collection. When the root XmlElement is generated,
''' xmlns attributes will be added for all entries in importedNamespaces. Any attributes
''' other than xmlns are added to the 'otherAttributes' collection for binding by the caller.
''' </summary>
Private Function BindXmlnsAttributes(
attributes As SyntaxList(Of XmlNodeSyntax),
<Out()> ByRef allAttributes As Dictionary(Of XmlName, BoundXmlAttribute),
xmlnsAttributes As ArrayBuilder(Of BoundXmlAttribute),
otherAttributes As ArrayBuilder(Of XmlNodeSyntax),
importedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String)),
diagnostics As BindingDiagnosticBag) As Dictionary(Of String, String)
Debug.Assert(xmlnsAttributes.Count = 0)
Debug.Assert(otherAttributes.Count = 0)
Dim namespaces As Dictionary(Of String, String) = Nothing
For Each attribute In attributes
Dim syntax = TryCast(attribute, XmlAttributeSyntax)
Dim prefix As String = Nothing
Dim namespaceName As String = Nothing
Dim [namespace] As BoundExpression = Nothing
Dim hasErrors As Boolean = False
If (syntax IsNot Nothing) AndAlso
TryGetXmlnsAttribute(syntax, prefix, namespaceName, [namespace], hasErrors, fromImport:=False, diagnostics:=diagnostics) Then
Debug.Assert(prefix IsNot Nothing)
Debug.Assert(hasErrors OrElse (namespaceName IsNot Nothing))
Debug.Assert(hasErrors OrElse ([namespace] IsNot Nothing))
Dim matchesImport = Not hasErrors AndAlso MatchesXmlnsImport(prefix, namespaceName)
' Generate a BoundXmlAttribute, even if we'll drop the
' attribute, since the semantic model will need one.
Dim xmlnsAttribute = BindXmlnsAttribute(
syntax,
BindXmlnsName(syntax.Name, prefix, compilerGenerated:=False, diagnostics:=diagnostics),
[namespace],
useConstructor:=True,
matchesImport:=matchesImport,
compilerGenerated:=False,
hasErrors:=hasErrors,
diagnostics:=diagnostics)
xmlnsAttributes.Add(xmlnsAttribute)
If Not hasErrors Then
If matchesImport Then
AddImportedNamespaceIfNecessary(importedNamespaces, prefix, namespaceName, forElement:=False)
End If
' Check for duplicates.
If AddXmlAttributeIfNotDuplicate(syntax.Name, GetXmlnsXmlName(prefix), xmlnsAttribute, allAttributes, diagnostics) Then
If namespaces Is Nothing Then
namespaces = New Dictionary(Of String, String)
End If
namespaces.Add(prefix, namespaceName)
End If
End If
Else
' Not an xmlns attribute. Defer binding to the caller, to
' allow the caller to include any namespaces found here
' in the lookup of the prefix on this and other attributes.
otherAttributes.Add(attribute)
End If
Next
Return namespaces
End Function
Private Shared Function AddXmlAttributeIfNotDuplicate(
syntax As XmlNodeSyntax,
name As XmlName,
attribute As BoundXmlAttribute,
<Out()> ByRef allAttributes As Dictionary(Of XmlName, BoundXmlAttribute),
diagnostics As BindingDiagnosticBag) As Boolean
If allAttributes Is Nothing Then
allAttributes = New Dictionary(Of XmlName, BoundXmlAttribute)(XmlNameComparer.Instance)
End If
If allAttributes.ContainsKey(name) Then
' "Duplicate XML attribute '{0}'."
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_DuplicateXmlAttribute, syntax.ToString())
Return False
Else
allAttributes.Add(name, attribute)
Return True
End If
End Function
''' <summary>
''' If the attribute represents an xmlns declaration, populate 'prefix' and 'namespace',
''' and generate diagnostics and set hasErrors if there are errors. Returns True if this
''' is an xmlns declaration, even if there are errors. Unless this attribute is from an
''' Imports statement, generate the BoundExpression for the namespace as well.
''' (For Imports, binding is skipped, since a BoundNode is not needed, and in the
''' invalid case of "xmlns:p=<%= expr %>", expr may result in a cycle.
''' </summary>
Private Function TryGetXmlnsAttribute(
syntax As XmlAttributeSyntax,
<Out()> ByRef prefix As String,
<Out()> ByRef namespaceName As String,
<Out()> ByRef [namespace] As BoundExpression,
<Out()> ByRef hasErrors As Boolean,
fromImport As Boolean,
diagnostics As BindingDiagnosticBag) As Boolean
prefix = Nothing
namespaceName = Nothing
[namespace] = Nothing
hasErrors = False
' If the name is an embedded expression, it should not be treated as an
' "xmlns" declaration at compile-time, regardless of the expression value.
If syntax.Name.Kind = SyntaxKind.XmlEmbeddedExpression Then
Return False
End If
Debug.Assert(syntax.Name.Kind = SyntaxKind.XmlName)
Dim nameSyntax = DirectCast(syntax.Name, XmlNameSyntax)
If Not TryGetXmlnsPrefix(nameSyntax, prefix, diagnostics) Then
Return False
End If
Debug.Assert(prefix IsNot Nothing)
Dim valueSyntax = syntax.Value
If valueSyntax.Kind <> SyntaxKind.XmlString Then
Debug.Assert(valueSyntax.Kind = SyntaxKind.XmlEmbeddedExpression)
' "An embedded expression cannot be used here."
ReportDiagnostic(diagnostics, valueSyntax, ERRID.ERR_EmbeddedExpression)
hasErrors = True
' Avoid binding Imports since that might result in a cycle.
If Not fromImport Then
[namespace] = BindXmlEmbeddedExpression(DirectCast(valueSyntax, XmlEmbeddedExpressionSyntax), diagnostics)
End If
Else
namespaceName = GetXmlString(DirectCast(valueSyntax, XmlStringSyntax).TextTokens)
Debug.Assert(namespaceName IsNot Nothing)
If (prefix = StringConstants.XmlnsPrefix) OrElse
((prefix = StringConstants.XmlPrefix) AndAlso (namespaceName <> StringConstants.XmlNamespace)) Then
' "XML namespace prefix '{0}' is reserved for use by XML and the namespace URI cannot be changed."
ReportDiagnostic(diagnostics, nameSyntax.LocalName, ERRID.ERR_ReservedXmlPrefix, prefix)
hasErrors = True
ElseIf Not fromImport AndAlso
String.IsNullOrEmpty(namespaceName) AndAlso
Not String.IsNullOrEmpty(prefix) Then
' "Namespace declaration with prefix cannot have an empty value inside an XML literal."
ReportDiagnostic(diagnostics, nameSyntax.LocalName, ERRID.ERR_IllegalDefaultNamespace)
hasErrors = True
ElseIf RedefinesReservedXmlNamespace(syntax.Value, prefix, StringConstants.XmlnsPrefix, namespaceName, StringConstants.XmlnsNamespace, diagnostics) OrElse
RedefinesReservedXmlNamespace(syntax.Value, prefix, StringConstants.XmlPrefix, namespaceName, StringConstants.XmlNamespace, diagnostics) Then
hasErrors = True
End If
If Not fromImport Then
[namespace] = CreateStringLiteral(
valueSyntax,
namespaceName,
compilerGenerated:=False,
diagnostics:=diagnostics)
End If
End If
Return True
End Function
Private Shared Function RedefinesReservedXmlNamespace(syntax As VisualBasicSyntaxNode, prefix As String, reservedPrefix As String, [namespace] As String, reservedNamespace As String, diagnostics As BindingDiagnosticBag) As Boolean
If ([namespace] = reservedNamespace) AndAlso (prefix <> reservedPrefix) Then
' "Prefix '{0}' cannot be bound to namespace name reserved for '{1}'."
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ReservedXmlNamespace, prefix, reservedPrefix)
Return True
End If
Return False
End Function
''' <summary>
''' If name is "xmlns", set prefix to String.Empty and return True.
''' If name is "xmlns:p", set prefix to p and return True.
''' Otherwise return False.
''' </summary>
Private Function TryGetXmlnsPrefix(syntax As XmlNameSyntax, <Out()> ByRef prefix As String, diagnostics As BindingDiagnosticBag) As Boolean
Dim localName = GetXmlName(syntax.LocalName)
Dim prefixName As String = Nothing
If syntax.Prefix IsNot Nothing Then
prefixName = GetXmlName(syntax.Prefix.Name)
If prefixName = StringConstants.XmlnsPrefix Then
prefix = localName
Return True
End If
End If
If localName = StringConstants.XmlnsPrefix Then
' Dev11 treats as p:xmlns="..." as an xmlns declaration, and ignores 'p',
' treating it as a declaration of the default namespace in all cases. Since
' the user probably intended to write xmlns:p="...", we now issue a warning.
If Not String.IsNullOrEmpty(prefixName) Then
' If 'p' maps to the empty namespace, we'll end up generating an attribute
' with local name "xmlns" in the empty namespace, which the runtime will
' interpret as an xmlns declaration of the default namespace. So, in that
' case, we treat p:xmlns="..." as an xmlns declaration as in Dev11.
Dim fromImports = False
Dim [namespace] As String = Nothing
' Lookup can ignore namespaces defined on XElements since we're interested
' in the default namespace and that can only be defined with Imports.
If LookupXmlNamespace(prefixName, True, [namespace], fromImports) AndAlso ([namespace] = StringConstants.DefaultXmlNamespace) Then
ReportDiagnostic(diagnostics, syntax, ERRID.WRN_EmptyPrefixAndXmlnsLocalName)
Else
ReportDiagnostic(diagnostics, syntax, ERRID.WRN_PrefixAndXmlnsLocalName, prefixName)
prefix = Nothing
Return False
End If
End If
prefix = String.Empty
Return True
End If
prefix = Nothing
Return False
End Function
Private Shared Function GetXmlName(token As SyntaxToken) As String
Select Case token.Kind
Case SyntaxKind.XmlNameToken
Return token.ValueText
Case Else
Throw ExceptionUtilities.UnexpectedValue(token.Kind)
End Select
End Function
''' <summary>
''' State tracked for the root XmlElement while binding nodes within the
''' tree. This state is mutable since it includes the set of namespaces from
''' Imports referenced within the tree. Ideally, this state would be part of the
''' XmlRootElementBinder, but since this state is mutable, there would be
''' issues caching and reusing the Binder. Instead, the state is passed
''' explicitly as an argument to each binding method.
''' </summary>
Private NotInheritable Class XmlElementRootInfo
Private ReadOnly _binder As Binder
Private ReadOnly _syntax As XmlNodeSyntax
Private ReadOnly _importedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String))
Private _xmlnsAttributesPlaceholder As BoundRValuePlaceholder
Private _removeNamespacesGroup As BoundMethodOrPropertyGroup
Public Sub New(binder As Binder, syntax As XmlNodeSyntax, importedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String)))
_binder = binder
_syntax = syntax
_importedNamespaces = importedNamespaces
End Sub
Public ReadOnly Property Syntax As XmlNodeSyntax
Get
Return _syntax
End Get
End Property
Public ReadOnly Property ImportedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String))
Get
Return _importedNamespaces
End Get
End Property
Public ReadOnly Property XmlnsAttributesPlaceholder As BoundRValuePlaceholder
Get
Return _xmlnsAttributesPlaceholder
End Get
End Property
Public Function BindRemoveNamespaceAttributesInvocation(
expr As BoundExpression,
prefixes As BoundRValuePlaceholder,
namespaces As BoundRValuePlaceholder,
diagnostics As BindingDiagnosticBag) As BoundExpression
Return _binder.BindRemoveNamespaceAttributesInvocation(
_syntax,
expr,
prefixes,
namespaces,
_xmlnsAttributesPlaceholder,
_removeNamespacesGroup,
diagnostics)
End Function
End Class
End Class
''' <summary>
''' Binding state used by the rewriter for XContainer derived types.
''' </summary>
Friend NotInheritable Class BoundXmlContainerRewriterInfo
Public Sub New(objectCreation As BoundExpression)
Debug.Assert(objectCreation IsNot Nothing)
Me.ObjectCreation = objectCreation
Me.SideEffects = ImmutableArray(Of BoundExpression).Empty
Me.HasErrors = objectCreation.HasErrors
End Sub
Public Sub New(isRoot As Boolean,
placeholder As BoundRValuePlaceholder,
objectCreation As BoundExpression,
xmlnsAttributesPlaceholder As BoundRValuePlaceholder,
xmlnsAttributes As BoundExpression,
prefixesPlaceholder As BoundRValuePlaceholder,
namespacesPlaceholder As BoundRValuePlaceholder,
importedNamespaces As ImmutableArray(Of KeyValuePair(Of String, String)),
inScopeXmlNamespaces As ImmutableArray(Of KeyValuePair(Of String, String)),
sideEffects As ImmutableArray(Of BoundExpression))
Debug.Assert(isRoot = Not importedNamespaces.IsDefault)
Debug.Assert(placeholder IsNot Nothing)
Debug.Assert(objectCreation IsNot Nothing)
Debug.Assert((xmlnsAttributesPlaceholder IsNot Nothing) = (xmlnsAttributes IsNot Nothing))
Debug.Assert((prefixesPlaceholder IsNot Nothing) = (namespacesPlaceholder IsNot Nothing))
Debug.Assert(Not sideEffects.IsDefault)
Me.IsRoot = isRoot
Me.Placeholder = placeholder
Me.ObjectCreation = objectCreation
Me.XmlnsAttributesPlaceholder = xmlnsAttributesPlaceholder
Me.XmlnsAttributes = xmlnsAttributes
Me.PrefixesPlaceholder = prefixesPlaceholder
Me.NamespacesPlaceholder = namespacesPlaceholder
Me.ImportedNamespaces = importedNamespaces
Me.InScopeXmlNamespaces = inScopeXmlNamespaces
Me.SideEffects = sideEffects
Me.HasErrors = objectCreation.HasErrors OrElse sideEffects.Any(Function(s) s.HasErrors)
End Sub
Public ReadOnly IsRoot As Boolean
Public ReadOnly Placeholder As BoundRValuePlaceholder
Public ReadOnly ObjectCreation As BoundExpression
Public ReadOnly XmlnsAttributesPlaceholder As BoundRValuePlaceholder
Public ReadOnly XmlnsAttributes As BoundExpression
Public ReadOnly PrefixesPlaceholder As BoundRValuePlaceholder
Public ReadOnly NamespacesPlaceholder As BoundRValuePlaceholder
Public ReadOnly ImportedNamespaces As ImmutableArray(Of KeyValuePair(Of String, String))
Public ReadOnly InScopeXmlNamespaces As ImmutableArray(Of KeyValuePair(Of String, String))
Public ReadOnly SideEffects As ImmutableArray(Of BoundExpression)
Public ReadOnly HasErrors As Boolean
End Class
''' <summary>
''' A binder to expose namespaces from Imports<xmlns:...> statements.
''' </summary>
Friend NotInheritable Class XmlNamespaceImportsBinder
Inherits Binder
Private ReadOnly _namespaces As IReadOnlyDictionary(Of String, XmlNamespaceAndImportsClausePosition)
Public Sub New(containingBinder As Binder, namespaces As IReadOnlyDictionary(Of String, XmlNamespaceAndImportsClausePosition))
MyBase.New(containingBinder)
Debug.Assert(namespaces IsNot Nothing)
Debug.Assert(namespaces.Count > 0)
_namespaces = namespaces
End Sub
Friend Overrides ReadOnly Property HasImportedXmlNamespaces As Boolean
Get
Return True
End Get
End Property
Friend Overrides Function LookupXmlNamespace(prefix As String,
ignoreXmlNodes As Boolean,
<Out()> ByRef [namespace] As String,
<Out()> ByRef fromImports As Boolean) As Boolean
Dim result As XmlNamespaceAndImportsClausePosition = Nothing
If _namespaces.TryGetValue(prefix, result) Then
[namespace] = result.XmlNamespace
Me.Compilation.MarkImportDirectiveAsUsed(Me.SyntaxTree, result.ImportsClausePosition)
fromImports = True
Return True
End If
Return MyBase.LookupXmlNamespace(prefix, ignoreXmlNodes, [namespace], fromImports)
End Function
End Class
Friend NotInheritable Class XmlRootElementBinder
Inherits Binder
Public Sub New(containingBinder As Binder)
MyBase.New(containingBinder)
End Sub
Friend Overrides Sub GetInScopeXmlNamespaces(builder As ArrayBuilder(Of KeyValuePair(Of String, String)))
End Sub
End Class
''' <summary>
''' A binder for XmlElement declarations.
''' </summary>
Friend NotInheritable Class XmlElementBinder
Inherits Binder
Private ReadOnly _namespaces As Dictionary(Of String, String)
Public Sub New(containingBinder As Binder, namespaces As Dictionary(Of String, String))
MyBase.New(containingBinder)
Debug.Assert(namespaces IsNot Nothing)
Debug.Assert(namespaces.Count > 0)
_namespaces = namespaces
End Sub
Friend Overrides Function LookupXmlNamespace(prefix As String, ignoreXmlNodes As Boolean, <Out()> ByRef [namespace] As String, <Out()> ByRef fromImports As Boolean) As Boolean
If Not ignoreXmlNodes Then
If _namespaces.TryGetValue(prefix, [namespace]) Then
fromImports = False
Return True
End If
End If
Return MyBase.LookupXmlNamespace(prefix, ignoreXmlNodes, [namespace], fromImports)
End Function
Friend Overrides Sub GetInScopeXmlNamespaces(builder As ArrayBuilder(Of KeyValuePair(Of String, String)))
builder.AddRange(_namespaces)
ContainingBinder.GetInScopeXmlNamespaces(builder)
End Sub
End Class
Friend NotInheritable Class XmlEmbeddedExpressionBinder
Inherits Binder
Public Sub New(containingBinder As Binder)
MyBase.New(containingBinder)
End Sub
Friend Overrides Function LookupXmlNamespace(prefix As String, ignoreXmlNodes As Boolean, <Out()> ByRef [namespace] As String, <Out()> ByRef fromImports As Boolean) As Boolean
' Perform further namespace lookup on the nearest containing binder
' that is outside any XML to avoid inheriting xmlns declarations
' from XML nodes outside of the embedded expression.
Return MyBase.LookupXmlNamespace(prefix, True, [namespace], fromImports)
End Function
Friend Overrides Sub GetInScopeXmlNamespaces(builder As ArrayBuilder(Of KeyValuePair(Of String, String)))
End Sub
End Class
''' <summary>
''' An extension property in reduced form, with first parameter
''' removed and exposed as an explicit receiver type.
''' </summary>
Friend NotInheritable Class ReducedExtensionPropertySymbol
Inherits PropertySymbol
Private ReadOnly _originalDefinition As PropertySymbol
Public Sub New(originalDefinition As PropertySymbol)
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsShared)
Debug.Assert(originalDefinition.ParameterCount = 1)
_originalDefinition = originalDefinition
End Sub
Friend Overrides ReadOnly Property ReducedFrom As PropertySymbol
Get
Return _originalDefinition
End Get
End Property
Friend Overrides ReadOnly Property ReducedFromDefinition As PropertySymbol
Get
Return _originalDefinition
End Get
End Property
Friend Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return _originalDefinition.Parameters(0).Type
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _originalDefinition.Name
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return _originalDefinition.HasSpecialName
End Get
End Property
Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
Get
Return _originalDefinition.CallingConvention
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _originalDefinition.ContainingSymbol
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return _originalDefinition.DeclaredAccessibility
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return _originalDefinition.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol)
Get
Return ImmutableArray(Of PropertySymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property GetMethod As MethodSymbol
Get
Return ReduceAccessorIfAny(_originalDefinition.GetMethod)
End Get
End Property
Friend Overrides ReadOnly Property AssociatedField As FieldSymbol
Get
Return _originalDefinition.AssociatedField
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return _originalDefinition.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property IsDefault As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _originalDefinition.Locations
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return ImmutableArray(Of ParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property SetMethod As MethodSymbol
Get
Return ReduceAccessorIfAny(_originalDefinition.SetMethod)
End Get
End Property
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return _originalDefinition.ReturnsByRef
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return _originalDefinition.Type
End Get
End Property
Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return _originalDefinition.TypeCustomModifiers
End Get
End Property
Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return _originalDefinition.RefCustomModifiers
End Get
End Property
Private Function ReduceAccessorIfAny(methodOpt As MethodSymbol) As ReducedExtensionAccessorSymbol
Return If(methodOpt Is Nothing, Nothing, New ReducedExtensionAccessorSymbol(Me, methodOpt))
End Function
Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean
Get
Debug.Assert(Not _originalDefinition.IsMyGroupCollectionProperty)
Return False
End Get
End Property
Private NotInheritable Class ReducedExtensionAccessorSymbol
Inherits MethodSymbol
Private ReadOnly _associatedProperty As ReducedExtensionPropertySymbol
Private ReadOnly _originalDefinition As MethodSymbol
Private _lazyParameters As ImmutableArray(Of ParameterSymbol)
Public Sub New(associatedProperty As ReducedExtensionPropertySymbol, originalDefinition As MethodSymbol)
_associatedProperty = associatedProperty
_originalDefinition = originalDefinition
End Sub
Friend Overrides ReadOnly Property CallsiteReducedFromMethod As MethodSymbol
Get
Return _originalDefinition
End Get
End Property
Public Overrides ReadOnly Property ReducedFrom As MethodSymbol
Get
Return _originalDefinition
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return _associatedProperty
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return _originalDefinition.HasSpecialName
End Get
End Property
Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
Get
Return Microsoft.Cci.CallingConvention.HasThis
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _originalDefinition.ContainingSymbol
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return _originalDefinition.DeclaredAccessibility
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return _originalDefinition.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
Return ImmutableArray(Of MethodSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return _originalDefinition.IsExternalMethod
End Get
End Property
Public Overrides Function GetDllImportData() As DllImportData
Return _originalDefinition.GetDllImportData()
End Function
Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData
Get
Return _originalDefinition.ReturnTypeMarshallingInformation
End Get
End Property
Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return _originalDefinition.ImplementationAttributes
End Get
End Property
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return _originalDefinition.HasDeclarativeSecurity
End Get
End Property
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Return _originalDefinition.GetSecurityInformation()
End Function
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return _originalDefinition.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return _originalDefinition.IsSub
End Get
End Property
Public Overrides ReadOnly Property IsAsync As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsIterator As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsInitOnly As Boolean
Get
Return _originalDefinition.IsInitOnly
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return _originalDefinition.IsVararg
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return _originalDefinition.GetAppliedConditionalSymbols()
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _originalDefinition.Locations
End Get
End Property
Public Overrides ReadOnly Property MethodKind As MethodKind
Get
Return _originalDefinition.MethodKind
End Get
End Property
Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean
Get
Return _originalDefinition.IsMethodKindBasedOnSyntax
End Get
End Property
Friend Overrides ReadOnly Property ParameterCount As Integer
Get
Return _originalDefinition.ParameterCount - 1
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
If _lazyParameters.IsDefault Then
ImmutableInterlocked.InterlockedInitialize(_lazyParameters, ReducedAccessorParameterSymbol.MakeParameters(Me, _originalDefinition.Parameters))
End If
Return _lazyParameters
End Get
End Property
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return _originalDefinition.ReturnsByRef
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _originalDefinition.ReturnType
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return _originalDefinition.ReturnTypeCustomModifiers
End Get
End Property
Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return _originalDefinition.RefCustomModifiers
End Get
End Property
Friend Overrides ReadOnly Property Syntax As SyntaxNode
Get
Return _originalDefinition.Syntax
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
Return _originalDefinition.TypeArguments
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return _originalDefinition.TypeParameters
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return False
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return _originalDefinition.GenerateDebugInfo
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
End Class
Private NotInheritable Class ReducedAccessorParameterSymbol
Inherits ReducedParameterSymbolBase
Public Shared Function MakeParameters(propertyOrAccessor As Symbol, originalParameters As ImmutableArray(Of ParameterSymbol)) As ImmutableArray(Of ParameterSymbol)
Dim n = originalParameters.Length
If n <= 1 Then
Debug.Assert(n = 1)
Return ImmutableArray(Of ParameterSymbol).Empty
Else
Dim parameters(n - 2) As ParameterSymbol
For i = 0 To n - 2
parameters(i) = New ReducedAccessorParameterSymbol(propertyOrAccessor, originalParameters(i + 1))
Next
Return parameters.AsImmutableOrNull()
End If
End Function
Private ReadOnly _propertyOrAccessor As Symbol
Public Sub New(propertyOrAccessor As Symbol, underlyingParameter As ParameterSymbol)
MyBase.New(underlyingParameter)
_propertyOrAccessor = propertyOrAccessor
End Sub
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _propertyOrAccessor
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return m_CurriedFromParameter.Type
End Get
End Property
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.Collections.Generic
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
Private Function BindXmlComment(
syntax As XmlCommentSyntax,
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
If rootInfoOpt Is Nothing Then
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
End If
Dim str = CreateStringLiteral(syntax, GetXmlString(syntax.TextTokens), compilerGenerated:=True, diagnostics:=diagnostics)
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XComment, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(str),
diagnostics)
Return New BoundXmlComment(syntax, str, objectCreation, objectCreation.Type)
End Function
Private Function BindXmlDocument(syntax As XmlDocumentSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
Dim declaration = BindXmlDeclaration(syntax.Declaration, diagnostics)
' Match the native compiler and invoke the XDocument(XDeclaration, Params Object())
' .ctor, with Nothing for the Params array argument.
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XDocument, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(declaration, New BoundLiteral(syntax, ConstantValue.Nothing, Nothing)),
diagnostics)
Dim childNodeBuilder = ArrayBuilder(Of BoundExpression).GetInstance()
BindXmlContent(syntax.PrecedingMisc, childNodeBuilder, rootInfoOpt:=Nothing, diagnostics:=diagnostics)
childNodeBuilder.Add(BindXmlContent(syntax.Root, rootInfoOpt:=Nothing, diagnostics:=diagnostics))
BindXmlContent(syntax.FollowingMisc, childNodeBuilder, rootInfoOpt:=Nothing, diagnostics:=diagnostics)
Dim childNodes = childNodeBuilder.ToImmutableAndFree()
Dim rewriterInfo = BindXmlContainerRewriterInfo(syntax, objectCreation, childNodes, rootInfoOpt:=Nothing, diagnostics:=diagnostics)
Return New BoundXmlDocument(syntax, declaration, childNodes, rewriterInfo, objectCreation.Type, rewriterInfo.HasErrors)
End Function
Private Function BindXmlDeclaration(syntax As XmlDeclarationSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim version = BindXmlDeclarationOption(syntax, syntax.Version, diagnostics)
Dim encoding = BindXmlDeclarationOption(syntax, syntax.Encoding, diagnostics)
Dim standalone = BindXmlDeclarationOption(syntax, syntax.Standalone, diagnostics)
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XDeclaration, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(version, encoding, standalone),
diagnostics)
Return New BoundXmlDeclaration(syntax, version, encoding, standalone, objectCreation, objectCreation.Type)
End Function
Private Function BindXmlDeclarationOption(syntax As XmlDeclarationSyntax, optionSyntax As XmlDeclarationOptionSyntax, diagnostics As BindingDiagnosticBag) As BoundLiteral
If optionSyntax Is Nothing Then
Return CreateStringLiteral(syntax, Nothing, compilerGenerated:=True, diagnostics:=diagnostics)
Else
Dim value = optionSyntax.Value
Return CreateStringLiteral(value, GetXmlString(value.TextTokens), compilerGenerated:=False, diagnostics:=diagnostics)
End If
End Function
Private Function BindXmlProcessingInstruction(syntax As XmlProcessingInstructionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim target = CreateStringLiteral(syntax, GetXmlName(syntax.Name), compilerGenerated:=True, diagnostics:=diagnostics)
Dim data = CreateStringLiteral(syntax, GetXmlString(syntax.TextTokens), compilerGenerated:=True, diagnostics:=diagnostics)
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XProcessingInstruction, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(target, data),
diagnostics)
Return New BoundXmlProcessingInstruction(syntax, target, data, objectCreation, objectCreation.Type)
End Function
Private Function BindXmlEmptyElement(
syntax As XmlEmptyElementSyntax,
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
Return BindXmlElement(syntax, syntax.Name, syntax.Attributes, Nothing, rootInfoOpt, diagnostics)
End Function
Private Function BindXmlElement(
syntax As XmlElementSyntax,
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
Dim startTag = syntax.StartTag
Return BindXmlElement(syntax, startTag.Name, startTag.Attributes, syntax.Content, rootInfoOpt, diagnostics)
End Function
Private Function BindXmlElement(
syntax As XmlNodeSyntax,
nameSyntax As XmlNodeSyntax,
attributes As SyntaxList(Of XmlNodeSyntax),
content As SyntaxList(Of XmlNodeSyntax),
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
If rootInfoOpt Is Nothing Then
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
' 'importedNamespaces' is the set of Imports statements that are referenced
' within the XmlElement, represented as { prefix, namespace } pairs. The set is
' used to ensure the necessary xmlns attributes are added to the resulting XML at
' runtime. The set is represented as a flat list rather than a dictionary so that the
' order of the xmlns attributes matches the XML generated by the native compiler.
Dim importedNamespaces = ArrayBuilder(Of KeyValuePair(Of String, String)).GetInstance()
Dim binder = New XmlRootElementBinder(Me)
Dim result = binder.BindXmlElement(syntax, nameSyntax, attributes, content, New XmlElementRootInfo(Me, syntax, importedNamespaces), diagnostics)
importedNamespaces.Free()
Return result
Else
Dim allAttributes As Dictionary(Of XmlName, BoundXmlAttribute) = Nothing
Dim xmlnsAttributes = ArrayBuilder(Of BoundXmlAttribute).GetInstance()
Dim otherAttributes = ArrayBuilder(Of XmlNodeSyntax).GetInstance()
Dim namespaces = BindXmlnsAttributes(attributes, allAttributes, xmlnsAttributes, otherAttributes, rootInfoOpt.ImportedNamespaces, diagnostics)
Debug.Assert((namespaces Is Nothing) OrElse (namespaces.Count > 0))
Dim binder = If(namespaces Is Nothing, Me, New XmlElementBinder(Me, namespaces))
Dim result = binder.BindXmlElementWithoutAddingNamespaces(syntax, nameSyntax, allAttributes, xmlnsAttributes, otherAttributes, content, rootInfoOpt, diagnostics)
otherAttributes.Free()
xmlnsAttributes.Free()
Return result
End If
End Function
Private Function BindXmlElementWithoutAddingNamespaces(
syntax As XmlNodeSyntax,
nameSyntax As XmlNodeSyntax,
<Out()> ByRef allAttributes As Dictionary(Of XmlName, BoundXmlAttribute),
xmlnsAttributes As ArrayBuilder(Of BoundXmlAttribute),
otherAttributes As ArrayBuilder(Of XmlNodeSyntax),
content As SyntaxList(Of XmlNodeSyntax),
rootInfo As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundExpression
' Any expression type is allowed as long as there is an appropriate XElement
' constructor for that argument type. In particular, this allows expressions of type
' XElement since XElement includes New(other As XElement). This is consistent with
' the native compiler, but contradicts the spec (11.23.4: "... the embedded expression
' must be a value of a type implicitly convertible to System.Xml.Linq.XName").
Dim argument As BoundExpression
If nameSyntax.Kind = SyntaxKind.XmlEmbeddedExpression Then
argument = BindXmlEmbeddedExpression(DirectCast(nameSyntax, XmlEmbeddedExpressionSyntax), diagnostics:=diagnostics)
Else
Dim fromImports = False
Dim prefix As String = Nothing
Dim localName As String = Nothing
Dim [namespace] As String = Nothing
argument = BindXmlName(DirectCast(nameSyntax, XmlNameSyntax), forElement:=True, rootInfoOpt:=rootInfo, fromImports:=fromImports, prefix:=prefix, localName:=localName, [namespace]:=[namespace], diagnostics:=diagnostics)
If fromImports Then
AddImportedNamespaceIfNecessary(rootInfo.ImportedNamespaces, prefix, [namespace], forElement:=True)
End If
End If
' Expression* .Semantics::InterpretXmlName( [ ParseTree::Expression* Expr ] [ BCSym.[Alias]** ResolvedPrefix ] )
' . . .
'If NameExpr.ResultType Is GetFXSymbolProvider().GetObjectType() AndAlso Not m_UsingOptionTypeStrict Then
' NameExpr = AllocateExpression( _
' BILOP.SX_DIRECTCAST, _
' m_XmlSymbols.GetXName(), _
' NameExpr, _
' NameExpr.Loc)
'End If
If argument.Type.IsObjectType AndAlso OptionStrict <> VisualBasic.OptionStrict.On Then
Dim xnameType = GetWellKnownType(WellKnownType.System_Xml_Linq_XName, syntax, diagnostics)
argument = ApplyDirectCastConversion(syntax, argument, xnameType, diagnostics:=diagnostics)
End If
Dim objectCreation = BindObjectCreationExpression(
nameSyntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XElement, nameSyntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(argument),
diagnostics)
Dim childNodeBuilder = ArrayBuilder(Of BoundExpression).GetInstance()
For Each xmlnsAttribute In xmlnsAttributes
childNodeBuilder.Add(xmlnsAttribute)
Next
Debug.Assert(otherAttributes.All(Function(a) (a.Kind = SyntaxKind.XmlAttribute) OrElse (a.Kind = SyntaxKind.XmlEmbeddedExpression)))
BindXmlAttributes(allAttributes, otherAttributes, childNodeBuilder, rootInfo, diagnostics)
If syntax.Kind <> SyntaxKind.XmlEmptyElement Then
If content.Count > 0 Then
BindXmlContent(content, childNodeBuilder, rootInfo, diagnostics)
Else
' An XElement with a start and end tag but no content. Include a compiler-
' generated empty string as content for consistency with the native compiler.
' (This also ensures <x></x> is serialized as <x></x> rather than <x/>.)
childNodeBuilder.Add(CreateStringLiteral(syntax, String.Empty, compilerGenerated:=True, diagnostics:=diagnostics))
End If
End If
Dim childNodes = childNodeBuilder.ToImmutableAndFree()
Dim rewriterInfo = BindXmlContainerRewriterInfo(syntax, objectCreation, childNodes, rootInfo, diagnostics)
Return New BoundXmlElement(syntax, argument, childNodes, rewriterInfo, objectCreation.Type, rewriterInfo.HasErrors)
End Function
Private Function BindXmlContainerRewriterInfo(
syntax As XmlNodeSyntax,
objectCreation As BoundExpression,
childNodes As ImmutableArray(Of BoundExpression),
rootInfoOpt As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag) As BoundXmlContainerRewriterInfo
If (childNodes.Length = 0) AndAlso
((rootInfoOpt Is Nothing) OrElse (rootInfoOpt.ImportedNamespaces.Count = 0)) Then
Return New BoundXmlContainerRewriterInfo(objectCreation)
End If
Dim placeholder = (New BoundRValuePlaceholder(syntax, objectCreation.Type)).MakeCompilerGenerated()
Dim sideEffectBuilder = ArrayBuilder(Of BoundExpression).GetInstance()
Dim addGroup = GetXmlMethodOrPropertyGroup(syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XContainer, syntax, diagnostics),
StringConstants.XmlAddMethodName,
placeholder,
diagnostics)
' The following are arguments to
' InternalXmlHelper.RemoveNamespaceAttributes(prefixes As String(),
' namespaces As XNamespace(), attributes As List(Of XAttribute), arg As XElement) As XElement
Dim inScopeXmlNamespaces As ImmutableArray(Of KeyValuePair(Of String, String)) = Nothing
Dim prefixesPlaceholder As BoundRValuePlaceholder = Nothing
Dim namespacesPlaceholder As BoundRValuePlaceholder = Nothing
For Each childNode In childNodes
' Skip attributes that match imports since those are redundant.
If (childNode.Kind = BoundKind.XmlAttribute) AndAlso DirectCast(childNode, BoundXmlAttribute).MatchesImport Then
Continue For
End If
' Any namespaces from Imports <xmlns:p="..."> that were used within an
' XElement require xmlns:p="..." attributes to be added to the root of the XML.
' (The xmlns declarations are added to the root to generate the simplest XML.)
' If the XML contains embedded expressions, those embedded expressions may
' also reference namespaces. For instance, the XML generated at runtime for
' <x <%= <p:y/> %>/> should be <x xmlns:p="..."><p:y/></x>. In general, these
' cases of embedded expressions are handled by adding xmlns attributes
' to the root of the XML within the embedded expression, then using methods
' at runtime (when stitching together the XML) to move any attributes to the
' containing XML. For instance, for <x <%= e %>/> we generate the following code:
'
' Dim prefixes As New String() From { ... } ' prefixes in use at 'x'
' Dim namespaces As New XNamespace() From { ... } ' namespaces in use at 'x'
' Dim attribs As New List(Of XAttribute) ' attributes on 'x' plus any removed from 'e'
' e = InternalXmlHelper.RemoveNamespaceAttributes(prefixes, namespaces, attribs, e)
' x.Add(attribs)
' x.Add(e)
'
' In a handful of cases where the namespaces on the embedded expression can
' be determined at compile time, the native compiler avoids the cost of calling
' RemoveNamespaceAttributes by moving namespaces at compile time. (See
' XmlSemantics::TraceLinqExpression.) That is an optimization only and for simplicity
' is not included. (If we do add static analysis, we'll need to handle cases where
' embedded expressions contain both namespaces that can be determined at compile
' time and namespaces that may be included at runtime. For instance, the expression
' <p:y> in <x <%= <p:y><%= e %></p:y> %>/> uses "p" but may also use namespaces
' in <%= e %>.)
Dim expr = childNode
Debug.Assert(expr.Type IsNot Nothing)
' If rootInfoOpt Is Nothing, we're binding an XDocument, not an XElement,
' in which case it's not possible to remove embedded xmlns attributes.
If (rootInfoOpt IsNot Nothing) AndAlso
(expr.Kind = BoundKind.XmlEmbeddedExpression) AndAlso
HasImportedXmlNamespaces AndAlso
Not expr.Type.IsIntrinsicOrEnumType() Then
If inScopeXmlNamespaces.IsDefault Then
Dim builder = ArrayBuilder(Of KeyValuePair(Of String, String)).GetInstance()
GetInScopeXmlNamespaces(builder)
inScopeXmlNamespaces = builder.ToImmutableAndFree()
End If
If prefixesPlaceholder Is Nothing Then
Dim prefixesType = CreateArrayType(GetSpecialType(SpecialType.System_String, syntax, diagnostics))
prefixesPlaceholder = (New BoundRValuePlaceholder(syntax, prefixesType)).MakeCompilerGenerated()
Dim namespacesType = CreateArrayType(GetWellKnownType(WellKnownType.System_Xml_Linq_XNamespace, syntax, diagnostics))
namespacesPlaceholder = (New BoundRValuePlaceholder(syntax, namespacesType)).MakeCompilerGenerated()
End If
' Generate update to child using RemoveNamespaceAttributes.
expr = rootInfoOpt.BindRemoveNamespaceAttributesInvocation(expr, prefixesPlaceholder, namespacesPlaceholder, diagnostics)
End If
sideEffectBuilder.Add(BindInvocationExpressionIfGroupNotNothing(syntax, addGroup, ImmutableArray.Create(Of BoundExpression)(expr), diagnostics))
Next
Dim xmlnsAttributesPlaceholder As BoundRValuePlaceholder = Nothing
Dim xmlnsAttributes As BoundExpression = Nothing
' At the root element, add any xmlns attributes required from Imports,
' and any xmlns attributes removed from embedded expressions.
Dim isRoot = (rootInfoOpt IsNot Nothing) AndAlso (rootInfoOpt.Syntax Is syntax)
If isRoot Then
' Imports declarations are added in the reverse order that the
' prefixes were discovered, to match the native compiler.
Dim importedNamespaces = rootInfoOpt.ImportedNamespaces
For i = importedNamespaces.Count - 1 To 0 Step -1
Dim pair = importedNamespaces(i)
Dim attribute = BindXmlnsAttribute(syntax, pair.Key, pair.Value, diagnostics)
sideEffectBuilder.Add(BindInvocationExpressionIfGroupNotNothing(syntax, addGroup, ImmutableArray.Create(Of BoundExpression)(attribute), diagnostics))
Next
' Add any xmlns attributes from embedded expressions. (If there were
' any embedded expressions, XmlnsAttributesPlaceholder will be set.)
xmlnsAttributesPlaceholder = rootInfoOpt.XmlnsAttributesPlaceholder
If xmlnsAttributesPlaceholder IsNot Nothing Then
xmlnsAttributes = BindObjectCreationExpression(syntax, xmlnsAttributesPlaceholder.Type, ImmutableArray(Of BoundExpression).Empty, diagnostics).MakeCompilerGenerated()
sideEffectBuilder.Add(BindInvocationExpressionIfGroupNotNothing(syntax, addGroup, ImmutableArray.Create(Of BoundExpression)(xmlnsAttributesPlaceholder), diagnostics))
End If
End If
Return New BoundXmlContainerRewriterInfo(
isRoot,
placeholder,
objectCreation,
xmlnsAttributesPlaceholder:=xmlnsAttributesPlaceholder,
xmlnsAttributes:=xmlnsAttributes,
prefixesPlaceholder:=prefixesPlaceholder,
namespacesPlaceholder:=namespacesPlaceholder,
importedNamespaces:=If(isRoot, rootInfoOpt.ImportedNamespaces.ToImmutable(), Nothing),
inScopeXmlNamespaces:=inScopeXmlNamespaces,
sideEffects:=sideEffectBuilder.ToImmutableAndFree())
End Function
Private Function BindRemoveNamespaceAttributesInvocation(
syntax As VisualBasicSyntaxNode,
expr As BoundExpression,
prefixesPlaceholder As BoundRValuePlaceholder,
namespacesPlaceholder As BoundRValuePlaceholder,
<Out()> ByRef xmlnsAttributesPlaceholder As BoundRValuePlaceholder,
<Out()> ByRef removeNamespacesGroup As BoundMethodOrPropertyGroup,
diagnostics As BindingDiagnosticBag) As BoundExpression
If xmlnsAttributesPlaceholder Is Nothing Then
Dim listType = GetWellKnownType(WellKnownType.System_Collections_Generic_List_T, syntax, diagnostics).Construct(
GetWellKnownType(WellKnownType.System_Xml_Linq_XAttribute, syntax, diagnostics))
xmlnsAttributesPlaceholder = (New BoundRValuePlaceholder(syntax, listType)).MakeCompilerGenerated()
' Generate method group and arguments for RemoveNamespaceAttributes.
removeNamespacesGroup = GetXmlMethodOrPropertyGroup(syntax,
GetInternalXmlHelperType(syntax, diagnostics),
StringConstants.XmlRemoveNamespaceAttributesMethodName,
Nothing,
diagnostics)
End If
' Invoke RemoveNamespaceAttributes.
Return BindInvocationExpressionIfGroupNotNothing(expr.Syntax,
removeNamespacesGroup,
ImmutableArray.Create(Of BoundExpression)(prefixesPlaceholder, namespacesPlaceholder, xmlnsAttributesPlaceholder, expr),
diagnostics).MakeCompilerGenerated()
End Function
Private Function CreateArrayType(elementType As TypeSymbol) As ArrayTypeSymbol
Return ArrayTypeSymbol.CreateSZArray(elementType, ImmutableArray(Of CustomModifier).Empty, compilation:=Compilation)
End Function
Private Shared Function GetXmlnsXmlName(prefix As String) As XmlName
Dim localName = If(String.IsNullOrEmpty(prefix), StringConstants.XmlnsPrefix, prefix)
Dim [namespace] = If(String.IsNullOrEmpty(prefix), StringConstants.DefaultXmlNamespace, StringConstants.XmlnsNamespace)
Return New XmlName(localName, [namespace])
End Function
Private Function BindXmlnsAttribute(
syntax As XmlNodeSyntax,
prefix As String,
namespaceName As String,
diagnostics As BindingDiagnosticBag) As BoundXmlAttribute
Dim name = BindXmlnsName(syntax, prefix, compilerGenerated:=True, diagnostics:=diagnostics)
Dim [namespace] = BindXmlNamespace(syntax,
CreateStringLiteral(syntax, namespaceName, compilerGenerated:=True, diagnostics:=diagnostics),
diagnostics)
Return BindXmlnsAttribute(syntax, name, [namespace], useConstructor:=False, matchesImport:=False, compilerGenerated:=True, hasErrors:=False, diagnostics:=diagnostics)
End Function
Private Function BindXmlnsName(
syntax As XmlNodeSyntax,
prefix As String,
compilerGenerated As Boolean,
diagnostics As BindingDiagnosticBag) As BoundExpression
Dim name = GetXmlnsXmlName(prefix)
Return BindXmlName(syntax,
CreateStringLiteral(syntax,
name.LocalName,
compilerGenerated,
diagnostics),
CreateStringLiteral(syntax,
name.XmlNamespace,
compilerGenerated,
diagnostics),
diagnostics)
End Function
Private Function BindXmlnsAttribute(
syntax As XmlNodeSyntax,
prefix As BoundExpression,
[namespace] As BoundExpression,
useConstructor As Boolean,
matchesImport As Boolean,
compilerGenerated As Boolean,
hasErrors As Boolean,
diagnostics As BindingDiagnosticBag) As BoundXmlAttribute
Dim objectCreation As BoundExpression
If useConstructor Then
objectCreation = BindObjectCreationExpression(syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XAttribute, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(prefix, [namespace]),
diagnostics)
Else
Dim type = GetInternalXmlHelperType(syntax, diagnostics)
Dim group = GetXmlMethodOrPropertyGroup(syntax, type, StringConstants.XmlCreateNamespaceAttributeMethodName, Nothing, diagnostics)
objectCreation = BindInvocationExpressionIfGroupNotNothing(syntax, group, ImmutableArray.Create(Of BoundExpression)(prefix, [namespace]), diagnostics)
End If
Dim result = New BoundXmlAttribute(syntax, prefix, [namespace], matchesImport, objectCreation, objectCreation.Type, hasErrors)
If compilerGenerated Then
result.SetWasCompilerGenerated()
End If
Return result
End Function
Private Function BindXmlAttribute(
syntax As XmlAttributeSyntax,
rootInfo As XmlElementRootInfo,
<Out()> ByRef xmlName As XmlName,
diagnostics As BindingDiagnosticBag) As BoundXmlAttribute
Dim nameSyntax = syntax.Name
Dim name As BoundExpression
If nameSyntax.Kind = SyntaxKind.XmlEmbeddedExpression Then
name = BindXmlEmbeddedExpression(DirectCast(nameSyntax, XmlEmbeddedExpressionSyntax), diagnostics:=diagnostics)
xmlName = Nothing
Else
Dim fromImports = False
Dim prefix As String = Nothing
Dim localName As String = Nothing
Dim [namespace] As String = Nothing
name = BindXmlName(
DirectCast(nameSyntax, XmlNameSyntax),
forElement:=False,
rootInfoOpt:=rootInfo,
fromImports:=fromImports,
prefix:=prefix,
localName:=localName,
[namespace]:=[namespace],
diagnostics:=diagnostics)
If fromImports Then
AddImportedNamespaceIfNecessary(rootInfo.ImportedNamespaces, prefix, [namespace], forElement:=False)
End If
xmlName = New XmlName(localName, [namespace])
End If
Dim value As BoundExpression
Dim objectCreation As BoundExpression
Dim valueSyntax = syntax.Value
Dim matchesImport As Boolean = False
If valueSyntax.Kind = SyntaxKind.XmlEmbeddedExpression Then
' Use InternalXmlHelper.CreateAttribute rather than 'New XAttribute()' for attributes
' with embedded expression values since CreateAttribute handles Nothing values.
value = BindXmlEmbeddedExpression(DirectCast(valueSyntax, XmlEmbeddedExpressionSyntax), diagnostics)
Dim group = GetXmlMethodOrPropertyGroup(valueSyntax,
GetInternalXmlHelperType(syntax, diagnostics),
StringConstants.XmlCreateAttributeMethodName,
Nothing,
diagnostics)
objectCreation = BindInvocationExpressionIfGroupNotNothing(valueSyntax,
group,
ImmutableArray.Create(Of BoundExpression)(name, value),
diagnostics)
Else
Dim str = GetXmlString(DirectCast(valueSyntax, XmlStringSyntax).TextTokens)
' Mark if this attribute is an xmlns declaration that matches an Imports,
' since xmlns declarations from Imports will be added directly at the
' XmlElement root, and this attribute can be dropped then.
matchesImport = (nameSyntax.Kind = SyntaxKind.XmlName) AndAlso MatchesXmlnsImport(DirectCast(nameSyntax, XmlNameSyntax), str)
value = CreateStringLiteral(valueSyntax, str, compilerGenerated:=False, diagnostics:=diagnostics)
objectCreation = BindObjectCreationExpression(nameSyntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XAttribute, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(name, value),
diagnostics)
End If
Return New BoundXmlAttribute(syntax, name, value, matchesImport, objectCreation, objectCreation.Type)
End Function
''' <summary>
''' Returns True if the xmlns { prefix, namespace } pair matches
''' an Imports declaration and there aren't any xmlns declarations
''' for the same prefix on any outer XElement scopes.
''' </summary>
Private Function MatchesXmlnsImport(prefix As String, [namespace] As String) As Boolean
Dim fromImports As Boolean = False
Dim otherNamespace As String = Nothing
Return LookupXmlNamespace(prefix, False, otherNamespace, fromImports) AndAlso
fromImports AndAlso
([namespace] = otherNamespace)
End Function
Private Function MatchesXmlnsImport(name As XmlNameSyntax, value As String) As Boolean
Dim prefix As String = Nothing
TryGetXmlnsPrefix(name, prefix, BindingDiagnosticBag.Discarded)
If prefix Is Nothing Then
Return False
End If
' Match using containing Binder since this Binder
' contains this xmlns attribute in XmlNamespaces.
Return ContainingBinder.MatchesXmlnsImport(prefix, value)
End Function
''' <summary>
''' Bind the expression within the XmlEmbeddedExpressionSyntax,
''' and wrap in a BoundXmlEmbeddedExpression.
''' </summary>
Private Function BindXmlEmbeddedExpression(syntax As XmlEmbeddedExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim binder = New XmlEmbeddedExpressionBinder(Me)
Dim expr = binder.BindRValue(syntax.Expression, diagnostics)
Debug.Assert(expr IsNot Nothing)
Debug.Assert(expr.Type IsNot Nothing)
Return New BoundXmlEmbeddedExpression(syntax, expr, expr.Type)
End Function
Private Sub BindXmlAttributes(
<Out()> ByRef allAttributes As Dictionary(Of XmlName, BoundXmlAttribute),
attributes As ArrayBuilder(Of XmlNodeSyntax),
childNodeBuilder As ArrayBuilder(Of BoundExpression),
rootInfo As XmlElementRootInfo,
diagnostics As BindingDiagnosticBag)
For Each childSyntax In attributes
If childSyntax.Kind = SyntaxKind.XmlAttribute Then
Dim attributeSyntax = DirectCast(childSyntax, XmlAttributeSyntax)
Dim name As XmlName = Nothing
Dim attribute = BindXmlAttribute(attributeSyntax, rootInfo, name, diagnostics)
childNodeBuilder.Add(attribute)
' Name may be Nothing for embedded expressions.
' Otherwise, check for duplicates.
If name.LocalName IsNot Nothing Then
AddXmlAttributeIfNotDuplicate(attributeSyntax.Name, name, attribute, allAttributes, diagnostics)
End If
Else
Dim child = BindXmlContent(childSyntax, rootInfo, diagnostics)
childNodeBuilder.Add(child)
End If
Next
End Sub
Private Structure XmlName
Public Sub New(localName As String, [namespace] As String)
Me.LocalName = localName
Me.XmlNamespace = [namespace]
End Sub
Public ReadOnly LocalName As String
Public ReadOnly XmlNamespace As String
End Structure
Private NotInheritable Class XmlNameComparer
Implements IEqualityComparer(Of XmlName)
Public Shared ReadOnly Instance As New XmlNameComparer()
Private Function IEqualityComparer_Equals(x As XmlName, y As XmlName) As Boolean Implements IEqualityComparer(Of XmlName).Equals
Return String.Equals(x.LocalName, y.LocalName, StringComparison.Ordinal) AndAlso String.Equals(x.XmlNamespace, y.XmlNamespace, StringComparison.Ordinal)
End Function
Private Function IEqualityComparer_GetHashCode(obj As XmlName) As Integer Implements IEqualityComparer(Of XmlName).GetHashCode
Dim result = obj.LocalName.GetHashCode()
If obj.XmlNamespace IsNot Nothing Then
result = Hash.Combine(result, obj.XmlNamespace.GetHashCode())
End If
Return result
End Function
End Class
Private Sub BindXmlContent(content As SyntaxList(Of XmlNodeSyntax), childNodeBuilder As ArrayBuilder(Of BoundExpression), rootInfoOpt As XmlElementRootInfo, diagnostics As BindingDiagnosticBag)
For Each childSyntax In content
childNodeBuilder.Add(BindXmlContent(childSyntax, rootInfoOpt, diagnostics))
Next
End Sub
Private Function BindXmlContent(syntax As XmlNodeSyntax, rootInfoOpt As XmlElementRootInfo, diagnostics As BindingDiagnosticBag) As BoundExpression
Select Case syntax.Kind
Case SyntaxKind.XmlProcessingInstruction
Return BindXmlProcessingInstruction(DirectCast(syntax, XmlProcessingInstructionSyntax), diagnostics)
Case SyntaxKind.XmlComment
Return BindXmlComment(DirectCast(syntax, XmlCommentSyntax), rootInfoOpt, diagnostics)
Case SyntaxKind.XmlElement
Return BindXmlElement(DirectCast(syntax, XmlElementSyntax), rootInfoOpt, diagnostics)
Case SyntaxKind.XmlEmptyElement
Return BindXmlEmptyElement(DirectCast(syntax, XmlEmptyElementSyntax), rootInfoOpt, diagnostics)
Case SyntaxKind.XmlEmbeddedExpression
Return BindXmlEmbeddedExpression(DirectCast(syntax, XmlEmbeddedExpressionSyntax), diagnostics)
Case SyntaxKind.XmlCDataSection
Return BindXmlCData(DirectCast(syntax, XmlCDataSectionSyntax), rootInfoOpt, diagnostics)
Case SyntaxKind.XmlText
Return BindXmlText(DirectCast(syntax, XmlTextSyntax), diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(syntax.Kind)
End Select
End Function
Private Function BindXmlAttributeAccess(syntax As XmlMemberAccessExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
Dim receiver = BindXmlMemberAccessReceiver(syntax, diagnostics)
Dim nameSyntax = If(syntax.Name.Kind = SyntaxKind.XmlName,
DirectCast(syntax.Name, XmlNameSyntax),
DirectCast(syntax.Name, XmlBracketedNameSyntax).Name)
Dim name = BindXmlName(nameSyntax, forElement:=False, diagnostics:=diagnostics)
Dim receiverType = receiver.Type
Debug.Assert(receiverType IsNot Nothing)
Dim memberAccess As BoundExpression = Nothing
If receiverType.SpecialType = SpecialType.System_Object Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoXmlAxesLateBinding)
ElseIf Not receiverType.IsErrorType() Then
Dim group As BoundMethodOrPropertyGroup = Nothing
' Determine the appropriate overload, allowing
' XElement or IEnumerable(Of XElement) argument.
Dim xmlType = GetWellKnownType(WellKnownType.System_Xml_Linq_XElement, syntax, diagnostics)
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If receiverType.IsOrDerivedFrom(xmlType, useSiteInfo) OrElse receiverType.IsCompatibleWithGenericIEnumerableOfType(xmlType, useSiteInfo) Then
group = GetXmlMethodOrPropertyGroup(syntax,
GetInternalXmlHelperType(syntax, diagnostics),
StringConstants.XmlAttributeValueMethodName,
Nothing,
diagnostics)
End If
diagnostics.Add(syntax, useSiteInfo)
If group IsNot Nothing Then
memberAccess = BindInvocationExpressionIfGroupNotNothing(syntax, group, ImmutableArray.Create(Of BoundExpression)(receiver, name), diagnostics)
memberAccess = MakeValue(memberAccess, diagnostics)
Else
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_TypeDisallowsAttributes, receiverType)
End If
End If
If memberAccess Is Nothing Then
memberAccess = BadExpression(syntax, ImmutableArray.Create(receiver, name), Compilation.GetSpecialType(SpecialType.System_String))
End If
Return New BoundXmlMemberAccess(syntax, memberAccess, memberAccess.Type)
End Function
Private Function BindXmlElementAccess(syntax As XmlMemberAccessExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Return BindXmlElementAccess(syntax, StringConstants.XmlElementsMethodName, ERRID.ERR_TypeDisallowsElements, diagnostics)
End Function
Private Function BindXmlDescendantAccess(syntax As XmlMemberAccessExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
Return BindXmlElementAccess(syntax, StringConstants.XmlDescendantsMethodName, ERRID.ERR_TypeDisallowsDescendants, diagnostics)
End Function
Private Function BindXmlElementAccess(syntax As XmlMemberAccessExpressionSyntax, memberName As String, typeDisallowsError As ERRID, diagnostics As BindingDiagnosticBag) As BoundExpression
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
Dim receiver = BindXmlMemberAccessReceiver(syntax, diagnostics)
Dim name = BindXmlName(DirectCast(syntax.Name, XmlBracketedNameSyntax).Name, forElement:=True, diagnostics:=diagnostics)
Dim receiverType = receiver.Type
Debug.Assert(receiverType IsNot Nothing)
Dim memberAccess As BoundExpression = Nothing
If receiverType.SpecialType = SpecialType.System_Object Then
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_NoXmlAxesLateBinding)
ElseIf Not receiverType.IsErrorType() Then
Dim group As BoundMethodOrPropertyGroup = Nothing
Dim arguments As ImmutableArray(Of BoundExpression) = Nothing
' Determine the appropriate overload, allowing
' XContainer or IEnumerable(Of XContainer) argument.
Dim xmlType = GetWellKnownType(WellKnownType.System_Xml_Linq_XContainer, syntax, diagnostics)
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
If receiverType.IsOrDerivedFrom(xmlType, useSiteInfo) Then
group = GetXmlMethodOrPropertyGroup(syntax,
xmlType,
memberName,
receiver,
diagnostics)
arguments = ImmutableArray.Create(Of BoundExpression)(name)
ElseIf receiverType.IsCompatibleWithGenericIEnumerableOfType(xmlType, useSiteInfo) Then
group = GetXmlMethodOrPropertyGroup(syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_Extensions, syntax, diagnostics),
memberName,
Nothing,
diagnostics)
arguments = ImmutableArray.Create(Of BoundExpression)(receiver, name)
End If
diagnostics.Add(syntax, useSiteInfo)
If group IsNot Nothing Then
memberAccess = BindInvocationExpressionIfGroupNotNothing(syntax, group, arguments, diagnostics)
memberAccess = MakeRValue(memberAccess, diagnostics)
Else
ReportDiagnostic(diagnostics, syntax, typeDisallowsError, receiverType)
End If
End If
If memberAccess Is Nothing Then
memberAccess = BadExpression(syntax, ImmutableArray.Create(receiver, name), ErrorTypeSymbol.UnknownResultType)
End If
Return New BoundXmlMemberAccess(syntax, memberAccess, memberAccess.Type)
End Function
Private Function BindXmlMemberAccessReceiver(syntax As XmlMemberAccessExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
If syntax.Base Is Nothing Then
Dim receiver As BoundExpression
Dim conditionalAccess As ConditionalAccessExpressionSyntax = syntax.GetCorrespondingConditionalAccessExpression()
If conditionalAccess IsNot Nothing Then
receiver = GetConditionalAccessReceiver(conditionalAccess)
Else
receiver = TryBindOmittedLeftForXmlMemberAccess(syntax, diagnostics, Me)
End If
If receiver Is Nothing Then
Return ReportDiagnosticAndProduceBadExpression(diagnostics, syntax, ERRID.ERR_BadWithRef)
End If
Return receiver
Else
Dim receiver = BindValue(syntax.Base, diagnostics)
Debug.Assert(receiver IsNot Nothing)
Return AdjustReceiverValue(receiver, syntax, diagnostics)
End If
End Function
Private Function BindXmlName(
syntax As XmlNameSyntax,
forElement As Boolean,
diagnostics As BindingDiagnosticBag) As BoundExpression
Dim fromImports = False
Dim prefix As String = Nothing
Dim localName As String = Nothing
Dim [namespace] As String = Nothing
Return BindXmlName(syntax, forElement, Nothing, fromImports, prefix, localName, [namespace], diagnostics)
End Function
Private Function BindXmlName(
syntax As XmlNameSyntax,
forElement As Boolean,
rootInfoOpt As XmlElementRootInfo,
<Out()> ByRef fromImports As Boolean,
<Out()> ByRef prefix As String,
<Out()> ByRef localName As String,
<Out()> ByRef [namespace] As String,
diagnostics As BindingDiagnosticBag) As BoundExpression
Dim prefixSyntax = syntax.Prefix
Dim namespaceExpr As BoundLiteral
fromImports = False
localName = GetXmlName(syntax.LocalName)
[namespace] = Nothing
If prefixSyntax IsNot Nothing Then
Dim prefixToken = prefixSyntax.Name
prefix = GetXmlName(prefixToken)
If forElement AndAlso (prefix = StringConstants.XmlnsPrefix) Then
' "Element names cannot use the 'xmlns' prefix."
ReportDiagnostic(diagnostics, prefixToken, ERRID.ERR_IllegalXmlnsPrefix)
Return BadExpression(syntax, Compilation.GetSpecialType(SpecialType.System_String))
End If
If Not LookupXmlNamespace(prefix, False, [namespace], fromImports) Then
Return ReportXmlNamespacePrefixNotDefined(syntax, prefixSyntax.Name, prefix, compilerGenerated:=False, diagnostics:=diagnostics)
End If
namespaceExpr = CreateStringLiteral(prefixSyntax, [namespace], compilerGenerated:=False, diagnostics:=diagnostics)
Else
prefix = StringConstants.DefaultXmlnsPrefix
If forElement Then
Dim found = LookupXmlNamespace(prefix, False, [namespace], fromImports)
Debug.Assert(found)
Else
[namespace] = StringConstants.DefaultXmlNamespace
End If
namespaceExpr = CreateStringLiteral(syntax, [namespace], compilerGenerated:=True, diagnostics:=diagnostics)
End If
' LocalName is marked as CompilerGenerated to avoid confusing the semantic model
' with two BoundNodes (LocalName and entire XName) for the same syntax node.
Dim localNameExpr = CreateStringLiteral(syntax, localName, compilerGenerated:=True, diagnostics:=diagnostics)
Return BindXmlName(syntax, localNameExpr, namespaceExpr, diagnostics)
End Function
Private Shared Sub AddImportedNamespaceIfNecessary(
importedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String)),
prefix As String,
[namespace] As String,
forElement As Boolean)
Debug.Assert(prefix IsNot Nothing)
Debug.Assert([namespace] IsNot Nothing)
' If the namespace is the default, create an xmlns="" attribute
' if the reference was for an XmlElement name. Otherwise,
' avoid adding an attribute for the default namespace.
If [namespace] = StringConstants.DefaultXmlNamespace Then
If Not forElement OrElse (prefix = StringConstants.DefaultXmlnsPrefix) Then
Return
End If
prefix = StringConstants.DefaultXmlnsPrefix
End If
For Each pair In importedNamespaces
If pair.Key = prefix Then
Return
End If
Next
importedNamespaces.Add(New KeyValuePair(Of String, String)(prefix, [namespace]))
End Sub
Private Function BindXmlName(syntax As VisualBasicSyntaxNode, localName As BoundExpression, [namespace] As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim group = GetXmlMethodOrPropertyGroup(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XName, syntax, diagnostics),
StringConstants.XmlGetMethodName,
Nothing,
diagnostics)
Dim objectCreation = BindInvocationExpressionIfGroupNotNothing(syntax, group, ImmutableArray.Create(Of BoundExpression)(localName, [namespace]), diagnostics)
Return New BoundXmlName(syntax, [namespace], localName, objectCreation, objectCreation.Type)
End Function
Private Function BindGetXmlNamespace(syntax As GetXmlNamespaceExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
Dim nameSyntax = syntax.Name
Dim [namespace] As String = Nothing
Dim fromImports = False
Dim expr As BoundExpression
If nameSyntax IsNot Nothing Then
Dim prefixToken = nameSyntax.Name
Dim prefix = GetXmlName(prefixToken)
If LookupXmlNamespace(prefix, False, [namespace], fromImports) Then
expr = CreateStringLiteral(nameSyntax, [namespace], compilerGenerated:=False, diagnostics:=diagnostics)
Else
expr = ReportXmlNamespacePrefixNotDefined(nameSyntax, prefixToken, prefix, compilerGenerated:=False, diagnostics:=diagnostics)
End If
Else
Dim found = LookupXmlNamespace(StringConstants.DefaultXmlnsPrefix, False, [namespace], fromImports)
Debug.Assert(found)
expr = CreateStringLiteral(syntax, [namespace], compilerGenerated:=True, diagnostics:=diagnostics)
End If
Return BindXmlNamespace(syntax, expr, diagnostics)
End Function
Private Function BindXmlNamespace(syntax As VisualBasicSyntaxNode, [namespace] As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim group = GetXmlMethodOrPropertyGroup(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XNamespace, syntax, diagnostics),
StringConstants.XmlGetMethodName,
Nothing,
diagnostics)
Dim objectCreation = BindInvocationExpressionIfGroupNotNothing(syntax, group, ImmutableArray.Create(Of BoundExpression)([namespace]), diagnostics)
Return New BoundXmlNamespace(syntax, [namespace], objectCreation, objectCreation.Type)
End Function
Private Function ReportXmlNamespacePrefixNotDefined(syntax As VisualBasicSyntaxNode, prefixToken As SyntaxToken, prefix As String, compilerGenerated As Boolean, diagnostics As BindingDiagnosticBag) As BoundBadExpression
Debug.Assert(prefix IsNot Nothing)
Debug.Assert(prefix = GetXmlName(prefixToken))
' "XML namespace prefix '{0}' is not defined."
ReportDiagnostic(diagnostics, prefixToken, ERRID.ERR_UndefinedXmlPrefix, prefix)
Dim result = BadExpression(syntax, Compilation.GetSpecialType(SpecialType.System_String))
If compilerGenerated Then
result.SetWasCompilerGenerated()
End If
Return result
End Function
Private Function BindXmlCData(syntax As XmlCDataSectionSyntax, rootInfoOpt As XmlElementRootInfo, diagnostics As BindingDiagnosticBag) As BoundExpression
If rootInfoOpt Is Nothing Then
diagnostics = CheckXmlFeaturesAllowed(syntax, diagnostics)
End If
Dim value = CreateStringLiteral(syntax, GetXmlString(syntax.TextTokens), compilerGenerated:=True, diagnostics:=diagnostics)
Dim objectCreation = BindObjectCreationExpression(
syntax,
GetWellKnownType(WellKnownType.System_Xml_Linq_XCData, syntax, diagnostics),
ImmutableArray.Create(Of BoundExpression)(value),
diagnostics)
Return New BoundXmlCData(syntax, value, objectCreation, objectCreation.Type)
End Function
Private Function BindXmlText(syntax As XmlTextSyntax, diagnostics As BindingDiagnosticBag) As BoundLiteral
Return CreateStringLiteral(syntax, GetXmlString(syntax.TextTokens), compilerGenerated:=False, diagnostics:=diagnostics)
End Function
Friend Shared Function GetXmlString(tokens As SyntaxTokenList) As String
Dim n = tokens.Count
If n = 0 Then
Return String.Empty
ElseIf n = 1 Then
Return GetXmlString(tokens(0))
Else
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
For Each token In tokens
builder.Append(GetXmlString(token))
Next
Dim result = builder.ToString()
pooledBuilder.Free()
Return result
End If
End Function
Private Shared Function GetXmlString(token As SyntaxToken) As String
Select Case token.Kind
Case SyntaxKind.XmlTextLiteralToken, SyntaxKind.XmlEntityLiteralToken
Return token.ValueText
Case Else
Throw ExceptionUtilities.UnexpectedValue(token.Kind)
End Select
End Function
Private Function GetXmlMethodOrPropertyGroup(syntax As VisualBasicSyntaxNode, type As NamedTypeSymbol, memberName As String, receiverOpt As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundMethodOrPropertyGroup
If type.IsErrorType() Then
Return Nothing
End If
Debug.Assert((receiverOpt Is Nothing) OrElse
receiverOpt.Type.IsErrorType() OrElse
receiverOpt.Type.IsOrDerivedFrom(type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded))
Dim group As BoundMethodOrPropertyGroup = Nothing
Dim result = LookupResult.GetInstance()
' Match the lookup of XML members in the native compiler: consider members
' on this type only, not base types, and ignore extension methods or properties
' from the current scope. (Extension methods and properties will be included,
' as shared members, if the members are defined on 'type' however.)
Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics)
LookupMember(result,
type,
memberName,
arity:=0,
options:=LookupOptions.AllMethodsOfAnyArity Or LookupOptions.NoBaseClassLookup Or LookupOptions.IgnoreExtensionMethods,
useSiteInfo:=useSiteInfo)
diagnostics.Add(syntax, useSiteInfo)
If result.IsGood Then
Debug.Assert(result.Symbols.Count > 0)
Dim symbol0 = result.Symbols(0)
Select Case result.Symbols(0).Kind
Case SymbolKind.Method
group = New BoundMethodGroup(syntax,
Nothing,
result.Symbols.ToDowncastedImmutable(Of MethodSymbol),
result.Kind,
receiverOpt,
QualificationKind.QualifiedViaValue)
Case SymbolKind.Property
group = New BoundPropertyGroup(syntax,
result.Symbols.ToDowncastedImmutable(Of PropertySymbol),
result.Kind,
receiverOpt,
QualificationKind.QualifiedViaValue)
End Select
End If
If group Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
If(result.HasDiagnostic,
result.Diagnostic,
ErrorFactory.ErrorInfo(ERRID.ERR_NameNotMember2, memberName, type)))
End If
result.Free()
Return group
End Function
''' <summary>
''' If the method or property group is not Nothing, bind as an invocation expression.
''' Otherwise return a BoundBadExpression containing the arguments.
''' </summary>
Private Function BindInvocationExpressionIfGroupNotNothing(syntax As SyntaxNode, groupOpt As BoundMethodOrPropertyGroup, arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag) As BoundExpression
If groupOpt Is Nothing Then
Return BadExpression(syntax, arguments, ErrorTypeSymbol.UnknownResultType)
Else
Return BindInvocationExpression(syntax,
syntax,
TypeCharacter.None,
groupOpt,
arguments,
argumentNames:=Nothing,
diagnostics:=diagnostics,
callerInfoOpt:=Nothing)
End If
End Function
''' <summary>
''' Check if XML features are allowed. If not, report an error and return a
''' separate DiagnosticBag that can be used for binding sub-expressions.
''' </summary>
Private Function CheckXmlFeaturesAllowed(syntax As VisualBasicSyntaxNode, diagnostics As BindingDiagnosticBag) As BindingDiagnosticBag
' Check if XObject is available, which matches the native compiler.
Dim type = Compilation.GetWellKnownType(WellKnownType.System_Xml_Linq_XObject)
If type.IsErrorType() Then
' "XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core."
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_XmlFeaturesNotAvailable)
' DiagnosticBag does not need to be created from the pool
' since this is an error recovery scenario only.
Return BindingDiagnosticBag.Discarded
Else
Return diagnostics
End If
End Function
Private Function CreateStringLiteral(
syntax As VisualBasicSyntaxNode,
str As String,
compilerGenerated As Boolean,
diagnostics As BindingDiagnosticBag,
Optional hasErrors As Boolean = False) As BoundLiteral
Debug.Assert(syntax IsNot Nothing)
Dim result = New BoundLiteral(syntax, ConstantValue.Create(str), GetSpecialType(SpecialType.System_String, syntax, diagnostics), hasErrors:=hasErrors)
If compilerGenerated Then
result.SetWasCompilerGenerated()
End If
Return result
End Function
''' <summary>
''' Bind any xmlns declaration attributes and return the bound nodes plus a Dictionary
''' of { prefix, namespace } pairs that will be used for namespace lookup at and below
''' the containing XmlElement. Any xmlns declarations that are redundant with Imports
''' in scope (same prefix and namespace) are dropped, and instead, an entry is added
''' to the 'importedNamespaces' collection. When the root XmlElement is generated,
''' xmlns attributes will be added for all entries in importedNamespaces. Any attributes
''' other than xmlns are added to the 'otherAttributes' collection for binding by the caller.
''' </summary>
Private Function BindXmlnsAttributes(
attributes As SyntaxList(Of XmlNodeSyntax),
<Out()> ByRef allAttributes As Dictionary(Of XmlName, BoundXmlAttribute),
xmlnsAttributes As ArrayBuilder(Of BoundXmlAttribute),
otherAttributes As ArrayBuilder(Of XmlNodeSyntax),
importedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String)),
diagnostics As BindingDiagnosticBag) As Dictionary(Of String, String)
Debug.Assert(xmlnsAttributes.Count = 0)
Debug.Assert(otherAttributes.Count = 0)
Dim namespaces As Dictionary(Of String, String) = Nothing
For Each attribute In attributes
Dim syntax = TryCast(attribute, XmlAttributeSyntax)
Dim prefix As String = Nothing
Dim namespaceName As String = Nothing
Dim [namespace] As BoundExpression = Nothing
Dim hasErrors As Boolean = False
If (syntax IsNot Nothing) AndAlso
TryGetXmlnsAttribute(syntax, prefix, namespaceName, [namespace], hasErrors, fromImport:=False, diagnostics:=diagnostics) Then
Debug.Assert(prefix IsNot Nothing)
Debug.Assert(hasErrors OrElse (namespaceName IsNot Nothing))
Debug.Assert(hasErrors OrElse ([namespace] IsNot Nothing))
Dim matchesImport = Not hasErrors AndAlso MatchesXmlnsImport(prefix, namespaceName)
' Generate a BoundXmlAttribute, even if we'll drop the
' attribute, since the semantic model will need one.
Dim xmlnsAttribute = BindXmlnsAttribute(
syntax,
BindXmlnsName(syntax.Name, prefix, compilerGenerated:=False, diagnostics:=diagnostics),
[namespace],
useConstructor:=True,
matchesImport:=matchesImport,
compilerGenerated:=False,
hasErrors:=hasErrors,
diagnostics:=diagnostics)
xmlnsAttributes.Add(xmlnsAttribute)
If Not hasErrors Then
If matchesImport Then
AddImportedNamespaceIfNecessary(importedNamespaces, prefix, namespaceName, forElement:=False)
End If
' Check for duplicates.
If AddXmlAttributeIfNotDuplicate(syntax.Name, GetXmlnsXmlName(prefix), xmlnsAttribute, allAttributes, diagnostics) Then
If namespaces Is Nothing Then
namespaces = New Dictionary(Of String, String)
End If
namespaces.Add(prefix, namespaceName)
End If
End If
Else
' Not an xmlns attribute. Defer binding to the caller, to
' allow the caller to include any namespaces found here
' in the lookup of the prefix on this and other attributes.
otherAttributes.Add(attribute)
End If
Next
Return namespaces
End Function
Private Shared Function AddXmlAttributeIfNotDuplicate(
syntax As XmlNodeSyntax,
name As XmlName,
attribute As BoundXmlAttribute,
<Out()> ByRef allAttributes As Dictionary(Of XmlName, BoundXmlAttribute),
diagnostics As BindingDiagnosticBag) As Boolean
If allAttributes Is Nothing Then
allAttributes = New Dictionary(Of XmlName, BoundXmlAttribute)(XmlNameComparer.Instance)
End If
If allAttributes.ContainsKey(name) Then
' "Duplicate XML attribute '{0}'."
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_DuplicateXmlAttribute, syntax.ToString())
Return False
Else
allAttributes.Add(name, attribute)
Return True
End If
End Function
''' <summary>
''' If the attribute represents an xmlns declaration, populate 'prefix' and 'namespace',
''' and generate diagnostics and set hasErrors if there are errors. Returns True if this
''' is an xmlns declaration, even if there are errors. Unless this attribute is from an
''' Imports statement, generate the BoundExpression for the namespace as well.
''' (For Imports, binding is skipped, since a BoundNode is not needed, and in the
''' invalid case of "xmlns:p=<%= expr %>", expr may result in a cycle.
''' </summary>
Private Function TryGetXmlnsAttribute(
syntax As XmlAttributeSyntax,
<Out()> ByRef prefix As String,
<Out()> ByRef namespaceName As String,
<Out()> ByRef [namespace] As BoundExpression,
<Out()> ByRef hasErrors As Boolean,
fromImport As Boolean,
diagnostics As BindingDiagnosticBag) As Boolean
prefix = Nothing
namespaceName = Nothing
[namespace] = Nothing
hasErrors = False
' If the name is an embedded expression, it should not be treated as an
' "xmlns" declaration at compile-time, regardless of the expression value.
If syntax.Name.Kind = SyntaxKind.XmlEmbeddedExpression Then
Return False
End If
Debug.Assert(syntax.Name.Kind = SyntaxKind.XmlName)
Dim nameSyntax = DirectCast(syntax.Name, XmlNameSyntax)
If Not TryGetXmlnsPrefix(nameSyntax, prefix, diagnostics) Then
Return False
End If
Debug.Assert(prefix IsNot Nothing)
Dim valueSyntax = syntax.Value
If valueSyntax.Kind <> SyntaxKind.XmlString Then
Debug.Assert(valueSyntax.Kind = SyntaxKind.XmlEmbeddedExpression)
' "An embedded expression cannot be used here."
ReportDiagnostic(diagnostics, valueSyntax, ERRID.ERR_EmbeddedExpression)
hasErrors = True
' Avoid binding Imports since that might result in a cycle.
If Not fromImport Then
[namespace] = BindXmlEmbeddedExpression(DirectCast(valueSyntax, XmlEmbeddedExpressionSyntax), diagnostics)
End If
Else
namespaceName = GetXmlString(DirectCast(valueSyntax, XmlStringSyntax).TextTokens)
Debug.Assert(namespaceName IsNot Nothing)
If (prefix = StringConstants.XmlnsPrefix) OrElse
((prefix = StringConstants.XmlPrefix) AndAlso (namespaceName <> StringConstants.XmlNamespace)) Then
' "XML namespace prefix '{0}' is reserved for use by XML and the namespace URI cannot be changed."
ReportDiagnostic(diagnostics, nameSyntax.LocalName, ERRID.ERR_ReservedXmlPrefix, prefix)
hasErrors = True
ElseIf Not fromImport AndAlso
String.IsNullOrEmpty(namespaceName) AndAlso
Not String.IsNullOrEmpty(prefix) Then
' "Namespace declaration with prefix cannot have an empty value inside an XML literal."
ReportDiagnostic(diagnostics, nameSyntax.LocalName, ERRID.ERR_IllegalDefaultNamespace)
hasErrors = True
ElseIf RedefinesReservedXmlNamespace(syntax.Value, prefix, StringConstants.XmlnsPrefix, namespaceName, StringConstants.XmlnsNamespace, diagnostics) OrElse
RedefinesReservedXmlNamespace(syntax.Value, prefix, StringConstants.XmlPrefix, namespaceName, StringConstants.XmlNamespace, diagnostics) Then
hasErrors = True
End If
If Not fromImport Then
[namespace] = CreateStringLiteral(
valueSyntax,
namespaceName,
compilerGenerated:=False,
diagnostics:=diagnostics)
End If
End If
Return True
End Function
Private Shared Function RedefinesReservedXmlNamespace(syntax As VisualBasicSyntaxNode, prefix As String, reservedPrefix As String, [namespace] As String, reservedNamespace As String, diagnostics As BindingDiagnosticBag) As Boolean
If ([namespace] = reservedNamespace) AndAlso (prefix <> reservedPrefix) Then
' "Prefix '{0}' cannot be bound to namespace name reserved for '{1}'."
ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ReservedXmlNamespace, prefix, reservedPrefix)
Return True
End If
Return False
End Function
''' <summary>
''' If name is "xmlns", set prefix to String.Empty and return True.
''' If name is "xmlns:p", set prefix to p and return True.
''' Otherwise return False.
''' </summary>
Private Function TryGetXmlnsPrefix(syntax As XmlNameSyntax, <Out()> ByRef prefix As String, diagnostics As BindingDiagnosticBag) As Boolean
Dim localName = GetXmlName(syntax.LocalName)
Dim prefixName As String = Nothing
If syntax.Prefix IsNot Nothing Then
prefixName = GetXmlName(syntax.Prefix.Name)
If prefixName = StringConstants.XmlnsPrefix Then
prefix = localName
Return True
End If
End If
If localName = StringConstants.XmlnsPrefix Then
' Dev11 treats as p:xmlns="..." as an xmlns declaration, and ignores 'p',
' treating it as a declaration of the default namespace in all cases. Since
' the user probably intended to write xmlns:p="...", we now issue a warning.
If Not String.IsNullOrEmpty(prefixName) Then
' If 'p' maps to the empty namespace, we'll end up generating an attribute
' with local name "xmlns" in the empty namespace, which the runtime will
' interpret as an xmlns declaration of the default namespace. So, in that
' case, we treat p:xmlns="..." as an xmlns declaration as in Dev11.
Dim fromImports = False
Dim [namespace] As String = Nothing
' Lookup can ignore namespaces defined on XElements since we're interested
' in the default namespace and that can only be defined with Imports.
If LookupXmlNamespace(prefixName, True, [namespace], fromImports) AndAlso ([namespace] = StringConstants.DefaultXmlNamespace) Then
ReportDiagnostic(diagnostics, syntax, ERRID.WRN_EmptyPrefixAndXmlnsLocalName)
Else
ReportDiagnostic(diagnostics, syntax, ERRID.WRN_PrefixAndXmlnsLocalName, prefixName)
prefix = Nothing
Return False
End If
End If
prefix = String.Empty
Return True
End If
prefix = Nothing
Return False
End Function
Private Shared Function GetXmlName(token As SyntaxToken) As String
Select Case token.Kind
Case SyntaxKind.XmlNameToken
Return token.ValueText
Case Else
Throw ExceptionUtilities.UnexpectedValue(token.Kind)
End Select
End Function
''' <summary>
''' State tracked for the root XmlElement while binding nodes within the
''' tree. This state is mutable since it includes the set of namespaces from
''' Imports referenced within the tree. Ideally, this state would be part of the
''' XmlRootElementBinder, but since this state is mutable, there would be
''' issues caching and reusing the Binder. Instead, the state is passed
''' explicitly as an argument to each binding method.
''' </summary>
Private NotInheritable Class XmlElementRootInfo
Private ReadOnly _binder As Binder
Private ReadOnly _syntax As XmlNodeSyntax
Private ReadOnly _importedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String))
Private _xmlnsAttributesPlaceholder As BoundRValuePlaceholder
Private _removeNamespacesGroup As BoundMethodOrPropertyGroup
Public Sub New(binder As Binder, syntax As XmlNodeSyntax, importedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String)))
_binder = binder
_syntax = syntax
_importedNamespaces = importedNamespaces
End Sub
Public ReadOnly Property Syntax As XmlNodeSyntax
Get
Return _syntax
End Get
End Property
Public ReadOnly Property ImportedNamespaces As ArrayBuilder(Of KeyValuePair(Of String, String))
Get
Return _importedNamespaces
End Get
End Property
Public ReadOnly Property XmlnsAttributesPlaceholder As BoundRValuePlaceholder
Get
Return _xmlnsAttributesPlaceholder
End Get
End Property
Public Function BindRemoveNamespaceAttributesInvocation(
expr As BoundExpression,
prefixes As BoundRValuePlaceholder,
namespaces As BoundRValuePlaceholder,
diagnostics As BindingDiagnosticBag) As BoundExpression
Return _binder.BindRemoveNamespaceAttributesInvocation(
_syntax,
expr,
prefixes,
namespaces,
_xmlnsAttributesPlaceholder,
_removeNamespacesGroup,
diagnostics)
End Function
End Class
End Class
''' <summary>
''' Binding state used by the rewriter for XContainer derived types.
''' </summary>
Friend NotInheritable Class BoundXmlContainerRewriterInfo
Public Sub New(objectCreation As BoundExpression)
Debug.Assert(objectCreation IsNot Nothing)
Me.ObjectCreation = objectCreation
Me.SideEffects = ImmutableArray(Of BoundExpression).Empty
Me.HasErrors = objectCreation.HasErrors
End Sub
Public Sub New(isRoot As Boolean,
placeholder As BoundRValuePlaceholder,
objectCreation As BoundExpression,
xmlnsAttributesPlaceholder As BoundRValuePlaceholder,
xmlnsAttributes As BoundExpression,
prefixesPlaceholder As BoundRValuePlaceholder,
namespacesPlaceholder As BoundRValuePlaceholder,
importedNamespaces As ImmutableArray(Of KeyValuePair(Of String, String)),
inScopeXmlNamespaces As ImmutableArray(Of KeyValuePair(Of String, String)),
sideEffects As ImmutableArray(Of BoundExpression))
Debug.Assert(isRoot = Not importedNamespaces.IsDefault)
Debug.Assert(placeholder IsNot Nothing)
Debug.Assert(objectCreation IsNot Nothing)
Debug.Assert((xmlnsAttributesPlaceholder IsNot Nothing) = (xmlnsAttributes IsNot Nothing))
Debug.Assert((prefixesPlaceholder IsNot Nothing) = (namespacesPlaceholder IsNot Nothing))
Debug.Assert(Not sideEffects.IsDefault)
Me.IsRoot = isRoot
Me.Placeholder = placeholder
Me.ObjectCreation = objectCreation
Me.XmlnsAttributesPlaceholder = xmlnsAttributesPlaceholder
Me.XmlnsAttributes = xmlnsAttributes
Me.PrefixesPlaceholder = prefixesPlaceholder
Me.NamespacesPlaceholder = namespacesPlaceholder
Me.ImportedNamespaces = importedNamespaces
Me.InScopeXmlNamespaces = inScopeXmlNamespaces
Me.SideEffects = sideEffects
Me.HasErrors = objectCreation.HasErrors OrElse sideEffects.Any(Function(s) s.HasErrors)
End Sub
Public ReadOnly IsRoot As Boolean
Public ReadOnly Placeholder As BoundRValuePlaceholder
Public ReadOnly ObjectCreation As BoundExpression
Public ReadOnly XmlnsAttributesPlaceholder As BoundRValuePlaceholder
Public ReadOnly XmlnsAttributes As BoundExpression
Public ReadOnly PrefixesPlaceholder As BoundRValuePlaceholder
Public ReadOnly NamespacesPlaceholder As BoundRValuePlaceholder
Public ReadOnly ImportedNamespaces As ImmutableArray(Of KeyValuePair(Of String, String))
Public ReadOnly InScopeXmlNamespaces As ImmutableArray(Of KeyValuePair(Of String, String))
Public ReadOnly SideEffects As ImmutableArray(Of BoundExpression)
Public ReadOnly HasErrors As Boolean
End Class
''' <summary>
''' A binder to expose namespaces from Imports<xmlns:...> statements.
''' </summary>
Friend NotInheritable Class XmlNamespaceImportsBinder
Inherits Binder
Private ReadOnly _namespaces As IReadOnlyDictionary(Of String, XmlNamespaceAndImportsClausePosition)
Public Sub New(containingBinder As Binder, namespaces As IReadOnlyDictionary(Of String, XmlNamespaceAndImportsClausePosition))
MyBase.New(containingBinder)
Debug.Assert(namespaces IsNot Nothing)
Debug.Assert(namespaces.Count > 0)
_namespaces = namespaces
End Sub
Friend Overrides ReadOnly Property HasImportedXmlNamespaces As Boolean
Get
Return True
End Get
End Property
Friend Overrides Function LookupXmlNamespace(prefix As String,
ignoreXmlNodes As Boolean,
<Out()> ByRef [namespace] As String,
<Out()> ByRef fromImports As Boolean) As Boolean
Dim result As XmlNamespaceAndImportsClausePosition = Nothing
If _namespaces.TryGetValue(prefix, result) Then
[namespace] = result.XmlNamespace
Me.Compilation.MarkImportDirectiveAsUsed(Me.SyntaxTree, result.ImportsClausePosition)
fromImports = True
Return True
End If
Return MyBase.LookupXmlNamespace(prefix, ignoreXmlNodes, [namespace], fromImports)
End Function
End Class
Friend NotInheritable Class XmlRootElementBinder
Inherits Binder
Public Sub New(containingBinder As Binder)
MyBase.New(containingBinder)
End Sub
Friend Overrides Sub GetInScopeXmlNamespaces(builder As ArrayBuilder(Of KeyValuePair(Of String, String)))
End Sub
End Class
''' <summary>
''' A binder for XmlElement declarations.
''' </summary>
Friend NotInheritable Class XmlElementBinder
Inherits Binder
Private ReadOnly _namespaces As Dictionary(Of String, String)
Public Sub New(containingBinder As Binder, namespaces As Dictionary(Of String, String))
MyBase.New(containingBinder)
Debug.Assert(namespaces IsNot Nothing)
Debug.Assert(namespaces.Count > 0)
_namespaces = namespaces
End Sub
Friend Overrides Function LookupXmlNamespace(prefix As String, ignoreXmlNodes As Boolean, <Out()> ByRef [namespace] As String, <Out()> ByRef fromImports As Boolean) As Boolean
If Not ignoreXmlNodes Then
If _namespaces.TryGetValue(prefix, [namespace]) Then
fromImports = False
Return True
End If
End If
Return MyBase.LookupXmlNamespace(prefix, ignoreXmlNodes, [namespace], fromImports)
End Function
Friend Overrides Sub GetInScopeXmlNamespaces(builder As ArrayBuilder(Of KeyValuePair(Of String, String)))
builder.AddRange(_namespaces)
ContainingBinder.GetInScopeXmlNamespaces(builder)
End Sub
End Class
Friend NotInheritable Class XmlEmbeddedExpressionBinder
Inherits Binder
Public Sub New(containingBinder As Binder)
MyBase.New(containingBinder)
End Sub
Friend Overrides Function LookupXmlNamespace(prefix As String, ignoreXmlNodes As Boolean, <Out()> ByRef [namespace] As String, <Out()> ByRef fromImports As Boolean) As Boolean
' Perform further namespace lookup on the nearest containing binder
' that is outside any XML to avoid inheriting xmlns declarations
' from XML nodes outside of the embedded expression.
Return MyBase.LookupXmlNamespace(prefix, True, [namespace], fromImports)
End Function
Friend Overrides Sub GetInScopeXmlNamespaces(builder As ArrayBuilder(Of KeyValuePair(Of String, String)))
End Sub
End Class
''' <summary>
''' An extension property in reduced form, with first parameter
''' removed and exposed as an explicit receiver type.
''' </summary>
Friend NotInheritable Class ReducedExtensionPropertySymbol
Inherits PropertySymbol
Private ReadOnly _originalDefinition As PropertySymbol
Public Sub New(originalDefinition As PropertySymbol)
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsShared)
Debug.Assert(originalDefinition.ParameterCount = 1)
_originalDefinition = originalDefinition
End Sub
Friend Overrides ReadOnly Property ReducedFrom As PropertySymbol
Get
Return _originalDefinition
End Get
End Property
Friend Overrides ReadOnly Property ReducedFromDefinition As PropertySymbol
Get
Return _originalDefinition
End Get
End Property
Friend Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return _originalDefinition.Parameters(0).Type
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _originalDefinition.Name
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return _originalDefinition.HasSpecialName
End Get
End Property
Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
Get
Return _originalDefinition.CallingConvention
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _originalDefinition.ContainingSymbol
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return _originalDefinition.DeclaredAccessibility
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return _originalDefinition.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol)
Get
Return ImmutableArray(Of PropertySymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property GetMethod As MethodSymbol
Get
Return ReduceAccessorIfAny(_originalDefinition.GetMethod)
End Get
End Property
Friend Overrides ReadOnly Property AssociatedField As FieldSymbol
Get
Return _originalDefinition.AssociatedField
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return _originalDefinition.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property IsDefault As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _originalDefinition.Locations
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return ImmutableArray(Of ParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property SetMethod As MethodSymbol
Get
Return ReduceAccessorIfAny(_originalDefinition.SetMethod)
End Get
End Property
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return _originalDefinition.ReturnsByRef
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return _originalDefinition.Type
End Get
End Property
Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return _originalDefinition.TypeCustomModifiers
End Get
End Property
Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return _originalDefinition.RefCustomModifiers
End Get
End Property
Private Function ReduceAccessorIfAny(methodOpt As MethodSymbol) As ReducedExtensionAccessorSymbol
Return If(methodOpt Is Nothing, Nothing, New ReducedExtensionAccessorSymbol(Me, methodOpt))
End Function
Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean
Get
Debug.Assert(Not _originalDefinition.IsMyGroupCollectionProperty)
Return False
End Get
End Property
Private NotInheritable Class ReducedExtensionAccessorSymbol
Inherits MethodSymbol
Private ReadOnly _associatedProperty As ReducedExtensionPropertySymbol
Private ReadOnly _originalDefinition As MethodSymbol
Private _lazyParameters As ImmutableArray(Of ParameterSymbol)
Public Sub New(associatedProperty As ReducedExtensionPropertySymbol, originalDefinition As MethodSymbol)
_associatedProperty = associatedProperty
_originalDefinition = originalDefinition
End Sub
Friend Overrides ReadOnly Property CallsiteReducedFromMethod As MethodSymbol
Get
Return _originalDefinition
End Get
End Property
Public Overrides ReadOnly Property ReducedFrom As MethodSymbol
Get
Return _originalDefinition
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return _associatedProperty
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return _originalDefinition.HasSpecialName
End Get
End Property
Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
Get
Return Microsoft.Cci.CallingConvention.HasThis
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _originalDefinition.ContainingSymbol
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return _originalDefinition.DeclaredAccessibility
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return _originalDefinition.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
Return ImmutableArray(Of MethodSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return _originalDefinition.IsExternalMethod
End Get
End Property
Public Overrides Function GetDllImportData() As DllImportData
Return _originalDefinition.GetDllImportData()
End Function
Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData
Get
Return _originalDefinition.ReturnTypeMarshallingInformation
End Get
End Property
Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return _originalDefinition.ImplementationAttributes
End Get
End Property
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return _originalDefinition.HasDeclarativeSecurity
End Get
End Property
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Return _originalDefinition.GetSecurityInformation()
End Function
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return _originalDefinition.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return _originalDefinition.IsSub
End Get
End Property
Public Overrides ReadOnly Property IsAsync As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsIterator As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsInitOnly As Boolean
Get
Return _originalDefinition.IsInitOnly
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return _originalDefinition.IsVararg
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return _originalDefinition.GetAppliedConditionalSymbols()
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _originalDefinition.Locations
End Get
End Property
Public Overrides ReadOnly Property MethodKind As MethodKind
Get
Return _originalDefinition.MethodKind
End Get
End Property
Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean
Get
Return _originalDefinition.IsMethodKindBasedOnSyntax
End Get
End Property
Friend Overrides ReadOnly Property ParameterCount As Integer
Get
Return _originalDefinition.ParameterCount - 1
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
If _lazyParameters.IsDefault Then
ImmutableInterlocked.InterlockedInitialize(_lazyParameters, ReducedAccessorParameterSymbol.MakeParameters(Me, _originalDefinition.Parameters))
End If
Return _lazyParameters
End Get
End Property
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return _originalDefinition.ReturnsByRef
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _originalDefinition.ReturnType
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return _originalDefinition.ReturnTypeCustomModifiers
End Get
End Property
Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return _originalDefinition.RefCustomModifiers
End Get
End Property
Friend Overrides ReadOnly Property Syntax As SyntaxNode
Get
Return _originalDefinition.Syntax
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
Return _originalDefinition.TypeArguments
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return _originalDefinition.TypeParameters
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return False
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return _originalDefinition.GenerateDebugInfo
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
End Class
Private NotInheritable Class ReducedAccessorParameterSymbol
Inherits ReducedParameterSymbolBase
Public Shared Function MakeParameters(propertyOrAccessor As Symbol, originalParameters As ImmutableArray(Of ParameterSymbol)) As ImmutableArray(Of ParameterSymbol)
Dim n = originalParameters.Length
If n <= 1 Then
Debug.Assert(n = 1)
Return ImmutableArray(Of ParameterSymbol).Empty
Else
Dim parameters(n - 2) As ParameterSymbol
For i = 0 To n - 2
parameters(i) = New ReducedAccessorParameterSymbol(propertyOrAccessor, originalParameters(i + 1))
Next
Return parameters.AsImmutableOrNull()
End If
End Function
Private ReadOnly _propertyOrAccessor As Symbol
Public Sub New(propertyOrAccessor As Symbol, underlyingParameter As ParameterSymbol)
MyBase.New(underlyingParameter)
_propertyOrAccessor = propertyOrAccessor
End Sub
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _propertyOrAccessor
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return m_CurriedFromParameter.Type
End Get
End Property
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/CSharp/Test/Symbol/Symbols/Source/CustomModifierCopyTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// Test that when metadata methods with custom modifiers in their signatures are overridden
/// or explicitly implemented, the custom modifiers are copied to the corresponding source
/// method. Secondarily, test that generated bridge methods have appropriate custom modifiers
/// in implicit implementation cases.
/// </summary>
public class CustomModifierCopyTests : CSharpTestBase
{
private const string ConstModOptType = "System.Runtime.CompilerServices.IsConst";
/// <summary>
/// Test implementing a single interface with custom modifiers.
/// </summary>
[Fact]
public void TestSingleInterfaceImplementation()
{
var text = @"
class Class : CppCli.CppInterface1
{
//copy modifiers (even though dev10 doesn't)
void CppCli.CppInterface1.Method1(int x) { }
//synthesize bridge method
public void Method2(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Class");
// explicit implementation copies custom modifiers
var classMethod1 = @class.GetMethod("CppCli.CppInterface1.Method1");
AssertAllParametersHaveConstModOpt(classMethod1);
// implicit implementation does not copy custom modifiers
var classMethod2 = @class.GetMethod("Method2");
AssertNoParameterHasModOpts(classMethod2);
// bridge method for implicit implementation has custom modifiers
var method2ExplicitImpl = @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Single();
Assert.Same(classMethod2, method2ExplicitImpl.ImplementingMethod);
AssertAllParametersHaveConstModOpt(method2ExplicitImpl);
}
/// <summary>
/// Test implementing multiple (identical) interfaces with custom modifiers.
/// </summary>
[Fact]
public void TestMultipleInterfaceImplementation()
{
var text = @"
class Class : CppCli.CppInterface1, CppCli.CppInterface2
{
//copy modifiers (even though dev10 doesn't)
void CppCli.CppInterface1.Method1(int x) { }
//copy modifiers (even though dev10 doesn't)
void CppCli.CppInterface2.Method1(int x) { }
//synthesize two bridge methods
public void Method2(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Class");
// explicit implementation copies custom modifiers
var classMethod1a = @class.GetMethod("CppCli.CppInterface1.Method1");
AssertAllParametersHaveConstModOpt(classMethod1a);
// explicit implementation copies custom modifiers
var classMethod1b = @class.GetMethod("CppCli.CppInterface2.Method1");
AssertAllParametersHaveConstModOpt(classMethod1b);
// implicit implementation does not copy custom modifiers
var classMethod2 = @class.GetMember<MethodSymbol>("Method2");
AssertNoParameterHasModOpts(classMethod2);
// bridge methods for implicit implementation have custom modifiers
var method2ExplicitImpls = @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods;
Assert.Equal(2, method2ExplicitImpls.Length);
foreach (var explicitImpl in method2ExplicitImpls)
{
Assert.Same(classMethod2, explicitImpl.ImplementingMethod);
AssertAllParametersHaveConstModOpt(explicitImpl);
}
}
/// <summary>
/// Test a direct override of a metadata method with custom modifiers.
/// Also confirm that a source method without custom modifiers can hide
/// a metadata method with custom modifiers (in the sense that "new" is
/// required) but does not copy the custom modifiers.
/// </summary>
[Fact]
public void TestSingleOverride()
{
var text = @"
class Class : CppCli.CppBase1
{
//copies custom modifiers
public override void VirtualMethod(int x) { }
//new required, does not copy custom modifiers
public new void NonVirtualMethod(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Class");
// override copies custom modifiers
var classVirtualMethod = @class.GetMember<MethodSymbol>("VirtualMethod");
AssertAllParametersHaveConstModOpt(classVirtualMethod);
// new does not copy custom modifiers
var classNonVirtualMethod = @class.GetMember<MethodSymbol>("NonVirtualMethod");
AssertNoParameterHasModOpts(classNonVirtualMethod);
// no bridge methods
Assert.Equal(0, @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
}
/// <summary>
/// Test overriding a source method that overrides a metadata method with
/// custom modifiers. The custom modifiers should propagate to the second
/// override as well.
/// </summary>
[Fact]
public void TestRepeatedOverride()
{
var text = @"
class Base : CppCli.CppBase1
{
//copies custom modifiers
public override void VirtualMethod(int x) { }
//new required, does not copy custom modifiers
public new virtual void NonVirtualMethod(int x) { }
}
class Derived : Base
{
//copies custom modifiers
public override void VirtualMethod(int x) { }
//would copy custom modifiers, but there are none
public override void NonVirtualMethod(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var baseClass = global.GetMember<SourceNamedTypeSymbol>("Base");
// override copies custom modifiers
var baseClassVirtualMethod = baseClass.GetMember<MethodSymbol>("VirtualMethod");
AssertAllParametersHaveConstModOpt(baseClassVirtualMethod);
// new does not copy custom modifiers
var baseClassNonVirtualMethod = baseClass.GetMember<MethodSymbol>("NonVirtualMethod");
AssertNoParameterHasModOpts(baseClassNonVirtualMethod);
// no bridge methods
Assert.Equal(0, baseClass.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
var derivedClass = global.GetMember<SourceNamedTypeSymbol>("Derived");
// override copies custom modifiers
var derivedClassVirtualMethod = derivedClass.GetMember<MethodSymbol>("VirtualMethod");
AssertAllParametersHaveConstModOpt(derivedClassVirtualMethod);
// new does not copy custom modifiers
var derivedClassNonVirtualMethod = derivedClass.GetMember<MethodSymbol>("NonVirtualMethod");
AssertNoParameterHasModOpts(derivedClassNonVirtualMethod);
// no bridge methods
Assert.Equal(0, derivedClass.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
}
/// <summary>
/// Test copying custom modifiers in/on parameters/return types.
/// </summary>
[Fact]
public void TestMethodOverrideCombinations()
{
var text = @"
class Derived : MethodCustomModifierCombinations
{
public override int[] Method1111(int[] a) { return a; }
public override int[] Method1110(int[] a) { return a; }
public override int[] Method1101(int[] a) { return a; }
public override int[] Method1100(int[] a) { return a; }
public override int[] Method1011(int[] a) { return a; }
public override int[] Method1010(int[] a) { return a; }
public override int[] Method1001(int[] a) { return a; }
public override int[] Method1000(int[] a) { return a; }
public override int[] Method0111(int[] a) { return a; }
public override int[] Method0110(int[] a) { return a; }
public override int[] Method0101(int[] a) { return a; }
public override int[] Method0100(int[] a) { return a; }
public override int[] Method0011(int[] a) { return a; }
public override int[] Method0010(int[] a) { return a; }
public override int[] Method0001(int[] a) { return a; }
public override int[] Method0000(int[] a) { return a; }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<NamedTypeSymbol>("Derived");
for (int i = 0; i < 0xf; i++)
{
CheckMethodCustomModifiers(
@class.GetMember<MethodSymbol>("Method" + Convert.ToString(i, 2).PadLeft(4, '0')),
inReturnType: (i & 0x8) != 0,
onReturnType: (i & 0x4) != 0,
inParameterType: (i & 0x2) != 0,
onParameterType: (i & 0x1) != 0);
}
}
/// <summary>
/// Test copying custom modifiers in/on property types.
/// </summary>
[Fact]
public void TestPropertyOverrideCombinations()
{
var text = @"
class Derived : PropertyCustomModifierCombinations
{
public override int[] Property11 { get; set; }
public override int[] Property10 { get; set; }
public override int[] Property01 { get; set; }
public override int[] Property00 { get; set; }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<NamedTypeSymbol>("Derived");
for (int i = 0; i < 0x4; i++)
{
PropertySymbol property = @class.GetMember<PropertySymbol>("Property" + Convert.ToString(i, 2).PadLeft(2, '0'));
bool inType = (i & 0x2) != 0;
bool onType = (i & 0x1) != 0;
CheckPropertyCustomModifiers(property, inType, onType);
CheckMethodCustomModifiers(
property.GetMethod,
inReturnType: inType,
onReturnType: onType,
inParameterType: false,
onParameterType: false);
CheckMethodCustomModifiers(
property.SetMethod,
inReturnType: false,
onReturnType: false,
inParameterType: inType,
onParameterType: onType);
}
}
/// <summary>
/// Helper method specifically for TestMethodOverrideCombinations and TestPropertyOverrideCombinations.
/// </summary>
/// <param name="method">Must have array return type (or void) and single array parameter (or none).</param>
/// <param name="inReturnType">True if a custom modifier is expected on the return type array element type.</param>
/// <param name="onReturnType">True if a custom modifier is expected on the return type.</param>
/// <param name="inParameterType">True if a custom modifier is expected on the parameter type array element type.</param>
/// <param name="onParameterType">True if a custom modifier is expected on the parameter type.</param>
private static void CheckMethodCustomModifiers(MethodSymbol method, bool inReturnType, bool onReturnType, bool inParameterType, bool onParameterType)
{
if (!method.ReturnsVoid)
{
CheckCustomModifier(inReturnType, ((ArrayTypeSymbol)method.ReturnType).ElementTypeWithAnnotations.CustomModifiers);
CheckCustomModifier(onReturnType, method.ReturnTypeWithAnnotations.CustomModifiers);
}
if (method.Parameters.Any())
{
CheckCustomModifier(inParameterType, ((ArrayTypeSymbol)method.Parameters.Single().Type).ElementTypeWithAnnotations.CustomModifiers);
CheckCustomModifier(onParameterType, method.Parameters.Single().TypeWithAnnotations.CustomModifiers);
}
}
/// <summary>
/// Helper method specifically for TestPropertyOverrideCombinations.
/// </summary>
/// <param name="property">Must have array type.</param>
/// <param name="inType">True if a custom modifier is expected on the return type array element type.</param>
/// <param name="onType">True if a custom modifier is expected on the return type.</param>
private static void CheckPropertyCustomModifiers(PropertySymbol property, bool inType, bool onType)
{
CheckCustomModifier(inType, ((ArrayTypeSymbol)property.Type).ElementTypeWithAnnotations.CustomModifiers);
CheckCustomModifier(onType, property.TypeWithAnnotations.CustomModifiers);
}
/// <summary>
/// True - assert that the list contains a single const modifier.
/// False - assert that the list is empty.
/// </summary>
private static void CheckCustomModifier(bool expectCustomModifier, ImmutableArray<CustomModifier> customModifiers)
{
if (expectCustomModifier)
{
Assert.Equal(ConstModOptType, customModifiers.Single().Modifier.ToTestDisplayString());
}
else
{
Assert.False(customModifiers.Any());
}
}
/// <summary>
/// Test the case of a source type extending a metadata type that could implicitly
/// implement a metadata interface with custom modifiers. If the source type does
/// not implement an interface method, the base method fills in and a bridge method
/// is synthesized in the source type. If the source type does implement an interface
/// method, no bridge method is synthesized.
/// </summary>
[Fact]
public void TestImplicitImplementationInBase()
{
var text = @"
class Class1 : CppCli.CppBase2, CppCli.CppInterface1
{
}
class Class2 : CppCli.CppBase2, CppCli.CppInterface1
{
//copies custom modifiers
public override void Method1(int x) { }
}
class Class3 : CppCli.CppBase2, CppCli.CppInterface1
{
//needs a bridge, since custom modifiers are not copied
public new void Method1(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var baseClass = global.GetMember<NamespaceSymbol>("CppCli").GetMember<NamedTypeSymbol>("CppBase2");
var class1 = global.GetMember<SourceNamedTypeSymbol>("Class1");
//both implementations are from the base class
var class1SynthesizedExplicitImpls = class1.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods;
Assert.Equal(1, class1SynthesizedExplicitImpls.Length); //Don't need a bridge method for the virtual base method.
foreach (var explicitImpl in class1SynthesizedExplicitImpls)
{
Assert.Same(baseClass, explicitImpl.ImplementingMethod.ContainingType);
AssertAllParametersHaveConstModOpt(explicitImpl, ignoreLast: explicitImpl.MethodKind == MethodKind.PropertySet);
}
var class2 = global.GetMember<SourceNamedTypeSymbol>("Class2");
//Method1 is implemented in the Class2, and no bridge is needed because the custom modifiers are copied
var class2Method1 = class2.GetMember<MethodSymbol>("Method1");
AssertAllParametersHaveConstModOpt(class2Method1);
//Method2 is implemented in the base class
var class2Method2SynthesizedExplicitImpl = class2.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Single();
Assert.Equal("Method2", class2Method2SynthesizedExplicitImpl.ExplicitInterfaceImplementations.Single().Name);
Assert.Same(baseClass, class2Method2SynthesizedExplicitImpl.ImplementingMethod.ContainingType);
AssertAllParametersHaveConstModOpt(class2Method2SynthesizedExplicitImpl);
var class3 = global.GetMember<SourceNamedTypeSymbol>("Class3");
//Method1 is implemented in Class3, but a bridge is needed because custom modifiers are not copied
var class3Method1 = class3.GetMember<MethodSymbol>("Method1");
Assert.False(class3Method1.Parameters.Single().TypeWithAnnotations.CustomModifiers.Any());
// GetSynthesizedExplicitImplementations doesn't guarantee order, so sort to make the asserts easier to write.
var class3SynthesizedExplicitImpls = (from m in class3.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods orderby m.Name select m).ToArray();
Assert.Equal(2, class3SynthesizedExplicitImpls.Length);
var class3Method1SynthesizedExplicitImpl = class3SynthesizedExplicitImpls[0];
Assert.Equal("Method1", class3Method1SynthesizedExplicitImpl.ExplicitInterfaceImplementations.Single().Name);
Assert.Same(class3Method1, class3Method1SynthesizedExplicitImpl.ImplementingMethod);
AssertAllParametersHaveConstModOpt(class3Method1SynthesizedExplicitImpl);
//Method2 is implemented in the base class
var class3Method2SynthesizedExplicitImpl = class3SynthesizedExplicitImpls[1];
Assert.Equal("Method2", class3Method2SynthesizedExplicitImpl.ExplicitInterfaceImplementations.Single().Name);
Assert.Same(baseClass, class3Method2SynthesizedExplicitImpl.ImplementingMethod.ContainingType);
AssertAllParametersHaveConstModOpt(class3Method2SynthesizedExplicitImpl);
}
/// <summary>
/// Test copying more than one custom modifier on the same element
/// </summary>
[Fact]
public void TestCopyMultipleCustomModifiers()
{
var text = @"
class Class : I2
{
//copy (both) modifiers (even though dev10 doesn't)
void I2.M1(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Class");
// explicit implementation copies custom modifiers
var classMethod1 = @class.GetMethod("I2.M1");
var classMethod1CustomModifiers = classMethod1.Parameters.Single().TypeWithAnnotations.CustomModifiers;
Assert.Equal(2, classMethod1CustomModifiers.Length);
foreach (var customModifier in classMethod1CustomModifiers)
{
Assert.Equal(ConstModOptType, customModifier.Modifier.ToTestDisplayString());
}
//no bridge methods
Assert.False(@class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Any());
}
/// <summary>
/// The params keyword is inherited from the overridden method in the same way as
/// a custom modifier.
/// </summary>
[Fact]
public void TestParamsKeyword()
{
var text = @"
public class Base
{
public virtual void M(params int[] a) { }
public virtual void N(int[] a) { }
}
public class Derived : Base
{
public override void M(int[] a) { } //lost 'params'
public override void N(params int[] a) { } //gained 'params'
}
public class Derived2 : Derived
{
public override void M(params int[] a) { } //regained 'params'
public override void N(int[] a) { } //(re)lost 'params'
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseClass = global.GetMember<NamedTypeSymbol>("Base");
var baseM = baseClass.GetMember<MethodSymbol>("M");
var baseN = baseClass.GetMember<MethodSymbol>("N");
var derivedClass = global.GetMember<NamedTypeSymbol>("Derived");
var derivedM = derivedClass.GetMember<MethodSymbol>("M");
var derivedN = derivedClass.GetMember<MethodSymbol>("N");
var derived2Class = global.GetMember<NamedTypeSymbol>("Derived2");
var derived2M = derived2Class.GetMember<MethodSymbol>("M");
var derived2N = derived2Class.GetMember<MethodSymbol>("N");
Assert.True(baseM.Parameters.Single().IsParams, "Base.M.IsParams should be true");
Assert.False(baseN.Parameters.Single().IsParams, "Base.N.IsParams should be false");
Assert.True(derivedM.Parameters.Single().IsParams, "Derived.M.IsParams should be true"); //NB: does not reflect source
Assert.False(derivedN.Parameters.Single().IsParams, "Derived.N.IsParams should be false"); //NB: does not reflect source
Assert.True(derived2M.Parameters.Single().IsParams, "Derived2.M.IsParams should be true");
Assert.False(derived2N.Parameters.Single().IsParams, "Derived2.N.IsParams should be false");
}
/// <summary>
/// Test implementing a single interface with custom modifiers.
/// </summary>
[Fact]
public void TestIndexerExplicitInterfaceImplementation()
{
var text = @"
class Explicit : CppCli.CppIndexerInterface
{
int CppCli.CppIndexerInterface.this[int x]
{
get { return 0; }
set { }
}
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Explicit");
// explicit implementation copies custom modifiers
var classIndexer = (PropertySymbol)@class.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single();
AssertAllParametersHaveConstModOpt(classIndexer);
Assert.Equal(0, @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
}
/// <summary>
/// Test implementing a single interface with custom modifiers.
/// </summary>
[Fact]
public void TestIndexerImplicitInterfaceImplementation()
{
var text = @"
class Implicit : CppCli.CppIndexerInterface
{
public int this[int x]
{
get { return 0; }
set { }
}
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Implicit");
// implicit implementation does not copy custom modifiers
var classIndexer = (PropertySymbol)@class.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single();
AssertNoParameterHasModOpts(classIndexer);
// bridge methods for implicit implementations have custom modifiers
var explicitImpls = @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods;
Assert.Equal(2, explicitImpls.Length);
var explicitGetterImpl = explicitImpls.Where(impl => impl.ImplementingMethod.MethodKind == MethodKind.PropertyGet).Single();
AssertAllParametersHaveConstModOpt(explicitGetterImpl);
var explicitSetterImpl = explicitImpls.Where(impl => impl.ImplementingMethod.MethodKind == MethodKind.PropertySet).Single();
AssertAllParametersHaveConstModOpt(explicitSetterImpl, ignoreLast: true);
}
/// <summary>
/// Test overriding a base type indexer with custom modifiers.
/// </summary>
[Fact]
public void TestOverrideIndexer()
{
var text = @"
class Override : CppCli.CppIndexerBase
{
public override int this[int x]
{
get { return 0; }
set { }
}
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Override");
// implicit implementation does not copy custom modifiers
var classIndexer = (PropertySymbol)@class.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single();
AssertAllParametersHaveConstModOpt(classIndexer);
Assert.Equal(0, @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
}
/// <summary>
/// The params keyword is inherited from the overridden indexer in the same way as
/// a custom modifier.
/// </summary>
[Fact]
public void TestParamsKeywordOnIndexer()
{
var text = @"
public class Base
{
public virtual char this[params int[] a] { set { } }
public virtual char this[long[] a] { set { } }
}
public class Derived : Base
{
public override char this[int[] a] { set { } } //lost 'params'
public override char this[params long[] a] { set { } } //gained 'params'
}
public class Derived2 : Derived
{
public override char this[params int[] a] { set { } } //regained 'params'
public override char this[long[] a] { set { } } //(re)lost 'params'
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseClass = global.GetMember<NamedTypeSymbol>("Base");
var baseIndexer1 = (PropertySymbol)baseClass.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int32, isArrayType: true)).Single();
var baseIndexer2 = (PropertySymbol)baseClass.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int64, isArrayType: true)).Single();
var derivedClass = global.GetMember<NamedTypeSymbol>("Derived");
var derivedIndexer1 = (PropertySymbol)derivedClass.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int32, isArrayType: true)).Single();
var derivedIndexer2 = (PropertySymbol)derivedClass.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int64, isArrayType: true)).Single();
var derived2Class = global.GetMember<NamedTypeSymbol>("Derived2");
var derived2Indexer1 = (PropertySymbol)derived2Class.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int32, isArrayType: true)).Single();
var derived2Indexer2 = (PropertySymbol)derived2Class.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int64, isArrayType: true)).Single();
Assert.True(baseIndexer1.Parameters.Single().IsParams, "Base.Indexer1.IsParams should be true");
Assert.False(baseIndexer2.Parameters.Single().IsParams, "Base.Indexer2.IsParams should be false");
Assert.True(derivedIndexer1.Parameters.Single().IsParams, "Derived.Indexer1.IsParams should be true"); //Indexer2B: does not reflect source
Assert.False(derivedIndexer2.Parameters.Single().IsParams, "Derived.Indexer2.IsParams should be false"); //Indexer2B: does not reflect source
Assert.True(derived2Indexer1.Parameters.Single().IsParams, "Derived2.Indexer1.IsParams should be true");
Assert.False(derived2Indexer2.Parameters.Single().IsParams, "Derived2.Indexer2.IsParams should be false");
}
[ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))]
[WorkItem(18411, "https://github.com/dotnet/roslyn/issues/18411")]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void Repro819774()
{
var il = @"
.class interface public abstract auto ansi IBug813305
{
.method public hidebysig newslot abstract virtual
instance void M(object modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method IBug813305::M
} // end of class IBug813305
";
var source = @"
using System.Collections.Generic;
class Bug813305 : IBug813305
{
void IBug813305.M(dynamic x)
{
x.Goo();
System.Console.WriteLine(""Bug813305.M"");
}
public void Goo() {}
}
class Test
{
static void Main()
{
IBug813305 x = new Bug813305();
x.M(x);
}
}
";
var comp = CreateCompilationWithILAndMscorlib40(source, il,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All),
targetFramework: TargetFramework.Standard,
references: new[] { CSharpRef });
CompileAndVerify(comp, expectedOutput: "Bug813305.M",
symbolValidator: m =>
{
var Bug813305 = m.GlobalNamespace.GetTypeMember("Bug813305");
var method = Bug813305.GetMethod("IBug813305.M");
Assert.Equal("Bug813305.IBug813305.M(dynamic)", method.ToDisplayString());
});
}
[Fact]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void ObjectToDynamic_ImplementationParameter()
{
var il = @"
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance void M(object modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
}
}
";
var source = @"
class C : I
{
void I.M(dynamic x) { }
}
";
var comp = CreateCompilationWithILAndMscorlib40(source, il, targetFramework: TargetFramework.Standard);
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
Assert.Equal(SpecialType.System_Object, interfaceMethod.ParameterTypesWithAnnotations.Single().SpecialType);
Assert.Equal(TypeKind.Dynamic, classMethod.ParameterTypesWithAnnotations.Single().Type.TypeKind);
Assert.Equal("void C.I.M(dynamic modopt(System.Runtime.CompilerServices.IsLong) x)", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicToObject_ImplementationParameter()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance void M(object modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
.param [1]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[2](false true)}
}
}
";
var source = @"
class C : I
{
void I.M(object x) { }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<MethodSymbol>("I.M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
Assert.Equal(TypeKind.Dynamic, interfaceMethod.ParameterTypesWithAnnotations.Single().Type.TypeKind);
Assert.Equal(SpecialType.System_Object, classMethod.ParameterTypesWithAnnotations.Single().SpecialType);
Assert.Equal("void C.I.M(System.Object modopt(System.Runtime.CompilerServices.IsLong) x)", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void TupleWithCustomModifiersInInterfaceMethod()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 }
.assembly '<<GeneratedFileName>>' { }
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
M(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> x) cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 63 01 64 00 00 ) // .......c.d..
} // end of method I::M
} // end of class I
";
var source1 = @"
class C : I
{
(object a, object b) I.M((object c, object d) x) { return x; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp1 = CreateEmptyCompilation(source1, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp1.VerifyDiagnostics();
var interfaceMethod1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("I.M");
var classMethod1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> " +
"I.M(System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> x)",
interfaceMethod1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) I.M((object c, object d) x)",
interfaceMethod1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)interfaceMethod1.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)interfaceMethod1.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> " +
"C.I.M(System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> x)",
classMethod1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) C.M((object c, object d) x)",
classMethod1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod1.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod1.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source2 = @"
class C : I
{
(object a, object b) I.M((object, object) x) { return x; }
}
";
var comp2 = CreateEmptyCompilation(source2, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp2.VerifyDiagnostics(
// (4,28): error CS8141: The tuple element names in the signature of method 'C.I.M((object, object))' must match the tuple element names of interface method 'I.M((object c, object d))' (including on the return type).
// (object a, object b) I.M((object, object) x) { return x; }
Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M").WithArguments("C.I.M((object, object))", "I.M((object c, object d))").WithLocation(4, 28)
);
var classMethod2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> " +
"C.I.M(System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> x)",
classMethod2.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod2.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod2.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source3 = @"
class C : I
{
(object, object) I.M((object c, object d) x) { return x; }
}
";
var comp3 = CreateEmptyCompilation(source3, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp3.VerifyDiagnostics(
// (4,24): error CS8141: The tuple element names in the signature of method 'C.I.M((object c, object d))' must match the tuple element names of interface method 'I.M((object c, object d))' (including on the return type).
// (object, object) I.M((object c, object d) x) { return x; }
Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M").WithArguments("C.I.M((object c, object d))", "I.M((object c, object d))").WithLocation(4, 24)
);
var classMethod3 = comp3.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
AssertEx.Equal("(object, object) C.M((object c, object d) x)", classMethod3.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod3.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod3.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source4 = @"
class C : I
{
public (object a, object b) M((object c, object d) x) { return x; }
}
";
var comp4 = CreateEmptyCompilation(source4, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp4.VerifyDiagnostics();
var classMethod4 = comp4.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("M");
AssertEx.Equal("(object a, object b) C.M((object c, object d) x)", classMethod4.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("(System.Object, System.Object)", ((NamedTypeSymbol)classMethod4.ReturnType).TupleUnderlyingType.ToTestDisplayString()); // modopts not copied
Assert.Equal("(System.Object, System.Object)", ((NamedTypeSymbol)classMethod4.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString()); // modopts not copied
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void TupleWithCustomModifiersInInterfaceProperty()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 }
.assembly '<<GeneratedFileName>>' { }
.class interface public abstract auto ansi I
{
.method public hidebysig newslot specialname abstract virtual
instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
get_P() cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
} // end of method I::get_P
.method public hidebysig newslot specialname abstract virtual
instance void set_P(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> 'value') cil managed
{
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
} // end of method I::set_P
.property instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
P()
{
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.get instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> I::get_P()
.set instance void I::set_P(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>)
} // end of property I::P
} // end of class I
";
var source1 = @"
class C : I
{
(object a, object b) I.P { get; set; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp1 = CreateEmptyCompilation(source1, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp1.VerifyDiagnostics();
var interfaceProperty1 = comp1.GlobalNamespace.GetMember<PropertySymbol>("I.P");
var classProperty1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("I.P");
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> I.P { get; set; }",
interfaceProperty1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) I.P", interfaceProperty1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)interfaceProperty1.Type).TupleUnderlyingType.ToTestDisplayString());
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> C.I.P { get; set; }",
classProperty1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) C.P", classProperty1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classProperty1.Type).TupleUnderlyingType.ToTestDisplayString());
var source2 = @"
class C : I
{
(object, object) I.P { get; set; }
}
";
var comp2 = CreateEmptyCompilation(source2, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp2.VerifyDiagnostics();
var classProperty2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("I.P");
Assert.Equal("(System.Object, System.Object) C.I.P { get; set; }", classProperty2.ToTestDisplayString());
Assert.Equal("(System.Object, System.Object)", ((NamedTypeSymbol)classProperty2.Type).TupleUnderlyingType.ToTestDisplayString());
var source3 = @"
class C : I
{
public (object a, object b) P { get; set; }
}
";
var comp3 = CreateEmptyCompilation(source3, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp3.VerifyDiagnostics();
var classProperty3 = comp3.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("P");
Assert.Equal("(System.Object a, System.Object b) C.P { get; set; }", classProperty3.ToTestDisplayString());
Assert.Equal("(System.Object, System.Object)", ((NamedTypeSymbol)classProperty3.Type).TupleUnderlyingType.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void TupleWithCustomModifiersInOverride()
{
// This IL is based on this code, but with modopts added
//public class Base
//{
// public virtual (object a, object b) P { get; set; }
// public virtual (object a, object b) M((object c, object d) x) { return x; }
//}
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 }
.assembly '<<GeneratedFileName>>' { }
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.field private class [System.ValueTuple]System.ValueTuple`2<object,object> '<P>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 )
.method public hidebysig newslot specialname virtual
instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
get_P() cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld class [System.ValueTuple]System.ValueTuple`2<object,object> Base::'<P>k__BackingField'
IL_0006: ret
} // end of method Base::get_P
.method public hidebysig newslot specialname virtual
instance void set_P(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld class [System.ValueTuple]System.ValueTuple`2<object,object> Base::'<P>k__BackingField'
IL_0007: ret
} // end of method Base::set_P
.method public hidebysig newslot virtual
instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
M(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> x) cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 63 01 64 00 00 ) // .......c.d..
// Code size 7 (0x7)
.maxstack 1
.locals init (class [System.ValueTuple]System.ValueTuple`2<object,object> V_0)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
IL_0005: ldloc.0
IL_0006: ret
} // end of method Base::M
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Base::.ctor
.property instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
P()
{
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.get instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> Base::get_P()
.set instance void Base::set_P(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>)
} // end of property Base::P
} // end of class Base
";
var source1 = @"
class C : Base
{
public override (object a, object b) P { get; set; }
public override (object a, object b) M((object c, object d) y) { return y; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp1 = CreateEmptyCompilation(source1, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp1.VerifyDiagnostics();
var baseMethod1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("Base.M");
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> " +
"Base.M(System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> x)",
baseMethod1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) Base.M((object c, object d) x)",
baseMethod1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)baseMethod1.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)baseMethod1.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var baseProperty1 = comp1.GlobalNamespace.GetMember<PropertySymbol>("Base.P");
Assert.Equal("(object a, object b) Base.P", baseProperty1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)baseProperty1.Type).TupleUnderlyingType.ToTestDisplayString());
var classProperty1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("P");
var classMethod1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("M");
Assert.Equal("(object a, object b) C.P", classProperty1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classProperty1.Type).TupleUnderlyingType.ToTestDisplayString());
AssertEx.Equal("(object a, object b) C.M((object c, object d) y)", classMethod1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod1.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod1.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source2 = @"
class C : Base
{
public override (object, object) P { get; set; }
public override (object, object) M((object c, object d) y) { return y; }
}
";
var comp2 = CreateEmptyCompilation(source2, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp2.VerifyDiagnostics(
// (5,38): error CS8139: 'C.M((object c, object d))': cannot change tuple element names when overriding inherited member 'Base.M((object c, object d))'
// public override (object, object) M((object c, object d) y) { return y; }
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("C.M((object c, object d))", "Base.M((object c, object d))").WithLocation(5, 38)
);
var classProperty2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("P");
var classMethod2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("M");
Assert.Equal("(System.Object, System.Object) C.P { get; set; }", classProperty2.ToTestDisplayString());
Assert.Equal("(System.Object, System.Object)",
((NamedTypeSymbol)classProperty2.Type).TupleUnderlyingType.ToTestDisplayString());
AssertEx.Equal("(object, object) C.M((object c, object d) y)", classMethod2.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod2.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod2.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source3 = @"
class C : Base
{
public override (object a, object b) P { get; set; }
public override (object a, object b) M((object, object) y) { return y; }
}
";
var comp3 = CreateEmptyCompilation(source3, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp3.VerifyDiagnostics(
// (5,42): error CS8139: 'C.M((object, object))': cannot change tuple element names when overriding inherited member 'Base.M((object c, object d))'
// public override (object a, object b) M((object, object) y) { return y; }
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("C.M((object, object))", "Base.M((object c, object d))").WithLocation(5, 42)
);
var classMethod3 = comp3.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("M");
AssertEx.Equal("(object a, object b) C.M((object, object) y)", classMethod3.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod3.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod3.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicToObject_ImplementationReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance object modopt(int32) M() cil managed
{
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[2](false true)}
}
}
";
var source = @"
class C : I
{
object I.M() { throw null; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<MethodSymbol>("I.M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
Assert.Equal(TypeKind.Dynamic, interfaceMethod.ReturnType.TypeKind);
Assert.Equal(SpecialType.System_Object, classMethod.ReturnType.SpecialType);
Assert.Equal("System.Object modopt(System.Int32) C.I.M()", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void ObjectToDynamic_ImplementationReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance object modopt(int32) M() cil managed
{
}
}
";
var source = @"
class C : I
{
dynamic I.M() { throw null; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
Assert.Equal(SpecialType.System_Object, interfaceMethod.ReturnType.SpecialType);
Assert.Equal(TypeKind.Dynamic, classMethod.ReturnType.TypeKind);
Assert.Equal("dynamic modopt(System.Int32) C.I.M()", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicVsObjectComplexParameter()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I`2<T,U>
{
.method public hidebysig newslot abstract virtual
instance void M(class I`2<object modopt(int16) [],object modopt(int32) []>& modopt(int64) c) cil managed
{
.param [1]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[9](false false false false false false false false true)} // i.e. second occurrence of 'object' is really 'dynamic'.
}
}
";
var source = @"
public class C : I<byte, char>
{
void I<byte, char>.M(ref I<dynamic[], object[]> c) { } // object to dynamic and vice versa
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Single(
m => m.MethodKind == MethodKind.ExplicitInterfaceImplementation);
Assert.Equal("void I<T, U>.M(ref modopt(System.Int64) I<System.Object modopt(System.Int16) [], dynamic modopt(System.Int32) []> c)", interfaceMethod.ToTestDisplayString());
Assert.Equal("void C.I<System.Byte, System.Char>.M(ref modopt(System.Int64) I<dynamic modopt(System.Int16) [], System.Object modopt(System.Int32) []> c)", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicVsObjectComplexReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I`2<T,U>
{
.method public hidebysig newslot abstract virtual
instance class I`2<object modopt(int16) [],object modopt(int32) []> modopt(int64) M() cil managed
{
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[8](false false false false false false false true)} // i.e. second occurrence of 'object' is really 'dynamic'.
}
}
";
var source = @"
public class C : I<byte, char>
{
I<dynamic[], object[]> I<byte, char>.M() { throw null; } // object to dynamic and vice versa
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Single(
m => m.MethodKind == MethodKind.ExplicitInterfaceImplementation);
Assert.Equal("I<System.Object modopt(System.Int16) [], dynamic modopt(System.Int32) []> modopt(System.Int64) I<T, U>.M()", interfaceMethod.ToTestDisplayString());
Assert.Equal("I<dynamic modopt(System.Int16) [], System.Object modopt(System.Int32) []> modopt(System.Int64) C.I<System.Byte, System.Char>.M()", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicToObjectAndViceVersa_OverrideParameter()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual
instance void M(object modopt(int16) o,
object modopt(int32) d) cil managed
{
.param [2]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[2](false true)}
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override void M(dynamic o, object d) { }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseMethod = global.GetMember<NamedTypeSymbol>("Base").GetMember<MethodSymbol>("M");
var derivedMethod = global.GetMember<NamedTypeSymbol>("Derived").GetMember<MethodSymbol>("M");
Assert.Equal("void Base.M(System.Object modopt(System.Int16) o, dynamic modopt(System.Int32) d)", baseMethod.ToTestDisplayString());
Assert.Equal("void Derived.M(dynamic modopt(System.Int16) o, System.Object modopt(System.Int32) d)", derivedMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicToObject_OverrideReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual
instance object modopt(int32) M() cil managed
{
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[2](false true)}
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override object M() { throw null; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseMethod = global.GetMember<NamedTypeSymbol>("Base").GetMember<MethodSymbol>("M");
var derivedMethod = global.GetMember<NamedTypeSymbol>("Derived").GetMember<MethodSymbol>("M");
Assert.Equal("dynamic modopt(System.Int32) Base.M()", baseMethod.ToTestDisplayString());
Assert.Equal("System.Object modopt(System.Int32) Derived.M()", derivedMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void ObjectToDynamic_OverrideReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual
instance object modopt(int32) M() cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override dynamic M() { throw null; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseMethod = global.GetMember<NamedTypeSymbol>("Base").GetMember<MethodSymbol>("M");
var derivedMethod = global.GetMember<NamedTypeSymbol>("Derived").GetMember<MethodSymbol>("M");
Assert.Equal("System.Object modopt(System.Int32) Base.M()", baseMethod.ToTestDisplayString());
Assert.Equal("dynamic modopt(System.Int32) Derived.M()", derivedMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(830632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830632")]
public void AccessorsAddCustomModifiers_Override()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname virtual instance char modopt(int8)
get_P() cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual instance void
set_P(char modopt(int16) 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual instance int32 modopt(int8)
get_Item(bool modopt(int16) x) cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual instance void
set_Item(bool modopt(int32) x,
int32 modopt(int64) 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance char P()
{
.get instance char modopt(int8) Base::get_P()
.set instance void Base::set_P(char modopt(int16))
}
.property instance int32 Item(bool)
{
.get instance int32 modopt(int8) Base::get_Item(bool modopt(int16))
.set instance void Base::set_Item(bool modopt(int32),
int32 modopt(int64))
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override char P { get { return 'a'; } set { } }
public override int this[bool x] { get { return 0; } set { } }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseType = global.GetMember<NamedTypeSymbol>("Base");
var baseProperty = baseType.GetMember<PropertySymbol>("P");
var baseIndexer = baseType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var derivedType = global.GetMember<NamedTypeSymbol>("Derived");
var derivedProperty = derivedType.GetMember<PropertySymbol>("P");
var derivedIndexer = derivedType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var int8Type = comp.GetSpecialType(SpecialType.System_SByte);
var int16Type = comp.GetSpecialType(SpecialType.System_Int16);
var int32Type = comp.GetSpecialType(SpecialType.System_Int32);
var int64Type = comp.GetSpecialType(SpecialType.System_Int64);
// None of the properties have custom modifiers - only the accessors do.
Assert.Equal(0, baseProperty.CustomModifierCount());
Assert.Equal(0, baseIndexer.CustomModifierCount());
Assert.Equal(0, derivedProperty.CustomModifierCount());
Assert.Equal(0, derivedIndexer.CustomModifierCount());
Assert.Equal(int8Type, baseProperty.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, derivedProperty.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, baseProperty.SetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, derivedProperty.SetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, baseIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, derivedIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, baseIndexer.GetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, derivedIndexer.GetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int32Type, baseIndexer.SetMethod.Parameters[0].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int32Type, derivedIndexer.SetMethod.Parameters[0].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int64Type, baseIndexer.SetMethod.Parameters[1].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int64Type, derivedIndexer.SetMethod.Parameters[1].TypeWithAnnotations.CustomModifiers.Single().Modifier());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(830632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830632")]
public void AccessorsRemoveCustomModifiers_Override()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname virtual instance char
get_P() cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual instance void
set_P(char 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual instance int32
get_Item(bool x) cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual instance void
set_Item(bool x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance char modopt(int8) P()
{
.get instance char Base::get_P()
.set instance void Base::set_P(char)
}
.property instance int32 modopt(int8) Item(bool modopt(int16))
{
.get instance int32 Base::get_Item(bool)
.set instance void Base::set_Item(bool,
int32)
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override char P { get { return 'a'; } set { } }
public override int this[bool x] { get { return 0; } set { } }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseType = global.GetMember<NamedTypeSymbol>("Base");
var baseProperty = baseType.GetMember<PropertySymbol>("P");
var baseIndexer = baseType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var derivedType = global.GetMember<NamedTypeSymbol>("Derived");
var derivedProperty = derivedType.GetMember<PropertySymbol>("P");
var derivedIndexer = derivedType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var int8Type = comp.GetSpecialType(SpecialType.System_SByte);
var int16Type = comp.GetSpecialType(SpecialType.System_Int16);
// None of the accessors have custom modifiers - only the properties do.
Assert.Equal(0, baseProperty.GetMethod.CustomModifierCount());
Assert.Equal(0, baseProperty.SetMethod.CustomModifierCount());
Assert.Equal(0, baseIndexer.GetMethod.CustomModifierCount());
Assert.Equal(0, baseIndexer.SetMethod.CustomModifierCount());
Assert.Equal(0, derivedProperty.GetMethod.CustomModifierCount());
Assert.Equal(0, derivedProperty.SetMethod.CustomModifierCount());
Assert.Equal(0, derivedIndexer.GetMethod.CustomModifierCount());
Assert.Equal(0, derivedIndexer.SetMethod.CustomModifierCount());
Assert.Equal(int8Type, baseProperty.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, derivedProperty.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, baseIndexer.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, derivedIndexer.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, baseIndexer.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, derivedIndexer.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
CompileAndVerify(comp);
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(830632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830632")]
public void AccessorsAddCustomModifiers_ExplicitImplementation()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname abstract virtual instance char modopt(int8)
get_P() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
set_P(char modopt(int16) 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance int32 modopt(int8)
get_Item(bool modopt(int16) x) cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
set_Item(bool modopt(int32) x,
int32 modopt(int64) 'value') cil managed
{
}
.property instance char P()
{
.get instance char modopt(int8) I::get_P()
.set instance void I::set_P(char modopt(int16))
}
.property instance int32 Item(bool)
{
.get instance int32 modopt(int8) I::get_Item(bool modopt(int16))
.set instance void I::set_Item(bool modopt(int32),
int32 modopt(int64))
}
} // end of class Base
";
var source = @"
class Implementation : I
{
char I.P { get { return 'a'; } set { } }
int I.this[bool x] { get { return 0; } set { } }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceType = global.GetMember<NamedTypeSymbol>("I");
var interfaceProperty = interfaceType.GetMember<PropertySymbol>("P");
var interfaceIndexer = interfaceType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var implementationType = global.GetMember<NamedTypeSymbol>("Implementation");
var implementationProperty = (PropertySymbol)implementationType.FindImplementationForInterfaceMember(interfaceProperty);
var implementationIndexer = (PropertySymbol)implementationType.FindImplementationForInterfaceMember(interfaceIndexer);
var int8Type = comp.GetSpecialType(SpecialType.System_SByte);
var int16Type = comp.GetSpecialType(SpecialType.System_Int16);
var int32Type = comp.GetSpecialType(SpecialType.System_Int32);
var int64Type = comp.GetSpecialType(SpecialType.System_Int64);
// None of the properties have custom modifiers - only the accessors do.
Assert.Equal(0, interfaceProperty.CustomModifierCount());
Assert.Equal(0, interfaceIndexer.CustomModifierCount());
Assert.Equal(0, implementationProperty.CustomModifierCount());
Assert.Equal(0, implementationIndexer.CustomModifierCount());
Assert.Equal(int8Type, interfaceProperty.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, implementationProperty.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, interfaceProperty.SetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, implementationProperty.SetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, interfaceIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, implementationIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, interfaceIndexer.GetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, implementationIndexer.GetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int32Type, interfaceIndexer.SetMethod.Parameters[0].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int32Type, implementationIndexer.SetMethod.Parameters[0].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int64Type, interfaceIndexer.SetMethod.Parameters[1].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int64Type, implementationIndexer.SetMethod.Parameters[1].TypeWithAnnotations.CustomModifiers.Single().Modifier());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(830632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830632")]
public void AccessorsRemoveCustomModifiers_ExplicitImplementation()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname abstract virtual instance char
get_P() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
set_P(char 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance int32
get_Item(bool x) cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
set_Item(bool x,
int32 'value') cil managed
{
}
.property instance char modopt(int8) P()
{
.get instance char I::get_P()
.set instance void I::set_P(char)
}
.property instance int32 modopt(int8) Item(bool modopt(int16))
{
.get instance int32 I::get_Item(bool)
.set instance void I::set_Item(bool,
int32)
}
} // end of class Base
";
var source = @"
class Implementation : I
{
char I.P { get { return 'a'; } set { } }
int I.this[bool x] { get { return 0; } set { } }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceType = global.GetMember<NamedTypeSymbol>("I");
var interfaceProperty = interfaceType.GetMember<PropertySymbol>("P");
var interfaceIndexer = interfaceType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var implementationType = global.GetMember<NamedTypeSymbol>("Implementation");
var implementationProperty = (PropertySymbol)implementationType.FindImplementationForInterfaceMember(interfaceProperty);
var implementationIndexer = (PropertySymbol)implementationType.FindImplementationForInterfaceMember(interfaceIndexer);
var int8Type = comp.GetSpecialType(SpecialType.System_SByte);
var int16Type = comp.GetSpecialType(SpecialType.System_Int16);
// None of the accessors have custom modifiers - only the properties do.
Assert.Equal(0, interfaceProperty.GetMethod.CustomModifierCount());
Assert.Equal(0, interfaceProperty.SetMethod.CustomModifierCount());
Assert.Equal(0, interfaceIndexer.GetMethod.CustomModifierCount());
Assert.Equal(0, interfaceIndexer.SetMethod.CustomModifierCount());
Assert.Equal(0, implementationProperty.GetMethod.CustomModifierCount());
Assert.Equal(0, implementationProperty.SetMethod.CustomModifierCount());
Assert.Equal(0, implementationIndexer.GetMethod.CustomModifierCount());
Assert.Equal(0, implementationIndexer.SetMethod.CustomModifierCount());
Assert.Equal(int8Type, interfaceProperty.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, implementationProperty.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, interfaceIndexer.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, implementationIndexer.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, interfaceIndexer.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, implementationIndexer.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
CompileAndVerify(comp);
}
private static Func<Symbol, bool> IsPropertyWithSingleParameter(SpecialType paramSpecialType, bool isArrayType = false)
{
return s =>
{
if (s.Kind != SymbolKind.Property)
{
return false;
}
var paramType = s.GetParameters().Single().Type;
var comparisonType = isArrayType ? ((ArrayTypeSymbol)paramType).ElementType : paramType;
return comparisonType.SpecialType == paramSpecialType;
};
}
private static void AssertAllParametersHaveConstModOpt(Symbol member, bool ignoreLast = false)
{
int numParameters = member.GetParameterCount();
var parameters = member.GetParameters();
for (int i = 0; i < numParameters; i++)
{
if (!(ignoreLast && i == numParameters - 1))
{
var param = parameters[i];
Assert.Equal(ConstModOptType, param.TypeWithAnnotations.CustomModifiers.Single().Modifier.ToTestDisplayString());
}
}
}
private static void AssertNoParameterHasModOpts(Symbol member)
{
foreach (var param in member.GetParameters())
{
Assert.Equal(0, param.TypeWithAnnotations.CustomModifiers.Length);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// Test that when metadata methods with custom modifiers in their signatures are overridden
/// or explicitly implemented, the custom modifiers are copied to the corresponding source
/// method. Secondarily, test that generated bridge methods have appropriate custom modifiers
/// in implicit implementation cases.
/// </summary>
public class CustomModifierCopyTests : CSharpTestBase
{
private const string ConstModOptType = "System.Runtime.CompilerServices.IsConst";
/// <summary>
/// Test implementing a single interface with custom modifiers.
/// </summary>
[Fact]
public void TestSingleInterfaceImplementation()
{
var text = @"
class Class : CppCli.CppInterface1
{
//copy modifiers (even though dev10 doesn't)
void CppCli.CppInterface1.Method1(int x) { }
//synthesize bridge method
public void Method2(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Class");
// explicit implementation copies custom modifiers
var classMethod1 = @class.GetMethod("CppCli.CppInterface1.Method1");
AssertAllParametersHaveConstModOpt(classMethod1);
// implicit implementation does not copy custom modifiers
var classMethod2 = @class.GetMethod("Method2");
AssertNoParameterHasModOpts(classMethod2);
// bridge method for implicit implementation has custom modifiers
var method2ExplicitImpl = @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Single();
Assert.Same(classMethod2, method2ExplicitImpl.ImplementingMethod);
AssertAllParametersHaveConstModOpt(method2ExplicitImpl);
}
/// <summary>
/// Test implementing multiple (identical) interfaces with custom modifiers.
/// </summary>
[Fact]
public void TestMultipleInterfaceImplementation()
{
var text = @"
class Class : CppCli.CppInterface1, CppCli.CppInterface2
{
//copy modifiers (even though dev10 doesn't)
void CppCli.CppInterface1.Method1(int x) { }
//copy modifiers (even though dev10 doesn't)
void CppCli.CppInterface2.Method1(int x) { }
//synthesize two bridge methods
public void Method2(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Class");
// explicit implementation copies custom modifiers
var classMethod1a = @class.GetMethod("CppCli.CppInterface1.Method1");
AssertAllParametersHaveConstModOpt(classMethod1a);
// explicit implementation copies custom modifiers
var classMethod1b = @class.GetMethod("CppCli.CppInterface2.Method1");
AssertAllParametersHaveConstModOpt(classMethod1b);
// implicit implementation does not copy custom modifiers
var classMethod2 = @class.GetMember<MethodSymbol>("Method2");
AssertNoParameterHasModOpts(classMethod2);
// bridge methods for implicit implementation have custom modifiers
var method2ExplicitImpls = @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods;
Assert.Equal(2, method2ExplicitImpls.Length);
foreach (var explicitImpl in method2ExplicitImpls)
{
Assert.Same(classMethod2, explicitImpl.ImplementingMethod);
AssertAllParametersHaveConstModOpt(explicitImpl);
}
}
/// <summary>
/// Test a direct override of a metadata method with custom modifiers.
/// Also confirm that a source method without custom modifiers can hide
/// a metadata method with custom modifiers (in the sense that "new" is
/// required) but does not copy the custom modifiers.
/// </summary>
[Fact]
public void TestSingleOverride()
{
var text = @"
class Class : CppCli.CppBase1
{
//copies custom modifiers
public override void VirtualMethod(int x) { }
//new required, does not copy custom modifiers
public new void NonVirtualMethod(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Class");
// override copies custom modifiers
var classVirtualMethod = @class.GetMember<MethodSymbol>("VirtualMethod");
AssertAllParametersHaveConstModOpt(classVirtualMethod);
// new does not copy custom modifiers
var classNonVirtualMethod = @class.GetMember<MethodSymbol>("NonVirtualMethod");
AssertNoParameterHasModOpts(classNonVirtualMethod);
// no bridge methods
Assert.Equal(0, @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
}
/// <summary>
/// Test overriding a source method that overrides a metadata method with
/// custom modifiers. The custom modifiers should propagate to the second
/// override as well.
/// </summary>
[Fact]
public void TestRepeatedOverride()
{
var text = @"
class Base : CppCli.CppBase1
{
//copies custom modifiers
public override void VirtualMethod(int x) { }
//new required, does not copy custom modifiers
public new virtual void NonVirtualMethod(int x) { }
}
class Derived : Base
{
//copies custom modifiers
public override void VirtualMethod(int x) { }
//would copy custom modifiers, but there are none
public override void NonVirtualMethod(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var baseClass = global.GetMember<SourceNamedTypeSymbol>("Base");
// override copies custom modifiers
var baseClassVirtualMethod = baseClass.GetMember<MethodSymbol>("VirtualMethod");
AssertAllParametersHaveConstModOpt(baseClassVirtualMethod);
// new does not copy custom modifiers
var baseClassNonVirtualMethod = baseClass.GetMember<MethodSymbol>("NonVirtualMethod");
AssertNoParameterHasModOpts(baseClassNonVirtualMethod);
// no bridge methods
Assert.Equal(0, baseClass.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
var derivedClass = global.GetMember<SourceNamedTypeSymbol>("Derived");
// override copies custom modifiers
var derivedClassVirtualMethod = derivedClass.GetMember<MethodSymbol>("VirtualMethod");
AssertAllParametersHaveConstModOpt(derivedClassVirtualMethod);
// new does not copy custom modifiers
var derivedClassNonVirtualMethod = derivedClass.GetMember<MethodSymbol>("NonVirtualMethod");
AssertNoParameterHasModOpts(derivedClassNonVirtualMethod);
// no bridge methods
Assert.Equal(0, derivedClass.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
}
/// <summary>
/// Test copying custom modifiers in/on parameters/return types.
/// </summary>
[Fact]
public void TestMethodOverrideCombinations()
{
var text = @"
class Derived : MethodCustomModifierCombinations
{
public override int[] Method1111(int[] a) { return a; }
public override int[] Method1110(int[] a) { return a; }
public override int[] Method1101(int[] a) { return a; }
public override int[] Method1100(int[] a) { return a; }
public override int[] Method1011(int[] a) { return a; }
public override int[] Method1010(int[] a) { return a; }
public override int[] Method1001(int[] a) { return a; }
public override int[] Method1000(int[] a) { return a; }
public override int[] Method0111(int[] a) { return a; }
public override int[] Method0110(int[] a) { return a; }
public override int[] Method0101(int[] a) { return a; }
public override int[] Method0100(int[] a) { return a; }
public override int[] Method0011(int[] a) { return a; }
public override int[] Method0010(int[] a) { return a; }
public override int[] Method0001(int[] a) { return a; }
public override int[] Method0000(int[] a) { return a; }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<NamedTypeSymbol>("Derived");
for (int i = 0; i < 0xf; i++)
{
CheckMethodCustomModifiers(
@class.GetMember<MethodSymbol>("Method" + Convert.ToString(i, 2).PadLeft(4, '0')),
inReturnType: (i & 0x8) != 0,
onReturnType: (i & 0x4) != 0,
inParameterType: (i & 0x2) != 0,
onParameterType: (i & 0x1) != 0);
}
}
/// <summary>
/// Test copying custom modifiers in/on property types.
/// </summary>
[Fact]
public void TestPropertyOverrideCombinations()
{
var text = @"
class Derived : PropertyCustomModifierCombinations
{
public override int[] Property11 { get; set; }
public override int[] Property10 { get; set; }
public override int[] Property01 { get; set; }
public override int[] Property00 { get; set; }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<NamedTypeSymbol>("Derived");
for (int i = 0; i < 0x4; i++)
{
PropertySymbol property = @class.GetMember<PropertySymbol>("Property" + Convert.ToString(i, 2).PadLeft(2, '0'));
bool inType = (i & 0x2) != 0;
bool onType = (i & 0x1) != 0;
CheckPropertyCustomModifiers(property, inType, onType);
CheckMethodCustomModifiers(
property.GetMethod,
inReturnType: inType,
onReturnType: onType,
inParameterType: false,
onParameterType: false);
CheckMethodCustomModifiers(
property.SetMethod,
inReturnType: false,
onReturnType: false,
inParameterType: inType,
onParameterType: onType);
}
}
/// <summary>
/// Helper method specifically for TestMethodOverrideCombinations and TestPropertyOverrideCombinations.
/// </summary>
/// <param name="method">Must have array return type (or void) and single array parameter (or none).</param>
/// <param name="inReturnType">True if a custom modifier is expected on the return type array element type.</param>
/// <param name="onReturnType">True if a custom modifier is expected on the return type.</param>
/// <param name="inParameterType">True if a custom modifier is expected on the parameter type array element type.</param>
/// <param name="onParameterType">True if a custom modifier is expected on the parameter type.</param>
private static void CheckMethodCustomModifiers(MethodSymbol method, bool inReturnType, bool onReturnType, bool inParameterType, bool onParameterType)
{
if (!method.ReturnsVoid)
{
CheckCustomModifier(inReturnType, ((ArrayTypeSymbol)method.ReturnType).ElementTypeWithAnnotations.CustomModifiers);
CheckCustomModifier(onReturnType, method.ReturnTypeWithAnnotations.CustomModifiers);
}
if (method.Parameters.Any())
{
CheckCustomModifier(inParameterType, ((ArrayTypeSymbol)method.Parameters.Single().Type).ElementTypeWithAnnotations.CustomModifiers);
CheckCustomModifier(onParameterType, method.Parameters.Single().TypeWithAnnotations.CustomModifiers);
}
}
/// <summary>
/// Helper method specifically for TestPropertyOverrideCombinations.
/// </summary>
/// <param name="property">Must have array type.</param>
/// <param name="inType">True if a custom modifier is expected on the return type array element type.</param>
/// <param name="onType">True if a custom modifier is expected on the return type.</param>
private static void CheckPropertyCustomModifiers(PropertySymbol property, bool inType, bool onType)
{
CheckCustomModifier(inType, ((ArrayTypeSymbol)property.Type).ElementTypeWithAnnotations.CustomModifiers);
CheckCustomModifier(onType, property.TypeWithAnnotations.CustomModifiers);
}
/// <summary>
/// True - assert that the list contains a single const modifier.
/// False - assert that the list is empty.
/// </summary>
private static void CheckCustomModifier(bool expectCustomModifier, ImmutableArray<CustomModifier> customModifiers)
{
if (expectCustomModifier)
{
Assert.Equal(ConstModOptType, customModifiers.Single().Modifier.ToTestDisplayString());
}
else
{
Assert.False(customModifiers.Any());
}
}
/// <summary>
/// Test the case of a source type extending a metadata type that could implicitly
/// implement a metadata interface with custom modifiers. If the source type does
/// not implement an interface method, the base method fills in and a bridge method
/// is synthesized in the source type. If the source type does implement an interface
/// method, no bridge method is synthesized.
/// </summary>
[Fact]
public void TestImplicitImplementationInBase()
{
var text = @"
class Class1 : CppCli.CppBase2, CppCli.CppInterface1
{
}
class Class2 : CppCli.CppBase2, CppCli.CppInterface1
{
//copies custom modifiers
public override void Method1(int x) { }
}
class Class3 : CppCli.CppBase2, CppCli.CppInterface1
{
//needs a bridge, since custom modifiers are not copied
public new void Method1(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var baseClass = global.GetMember<NamespaceSymbol>("CppCli").GetMember<NamedTypeSymbol>("CppBase2");
var class1 = global.GetMember<SourceNamedTypeSymbol>("Class1");
//both implementations are from the base class
var class1SynthesizedExplicitImpls = class1.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods;
Assert.Equal(1, class1SynthesizedExplicitImpls.Length); //Don't need a bridge method for the virtual base method.
foreach (var explicitImpl in class1SynthesizedExplicitImpls)
{
Assert.Same(baseClass, explicitImpl.ImplementingMethod.ContainingType);
AssertAllParametersHaveConstModOpt(explicitImpl, ignoreLast: explicitImpl.MethodKind == MethodKind.PropertySet);
}
var class2 = global.GetMember<SourceNamedTypeSymbol>("Class2");
//Method1 is implemented in the Class2, and no bridge is needed because the custom modifiers are copied
var class2Method1 = class2.GetMember<MethodSymbol>("Method1");
AssertAllParametersHaveConstModOpt(class2Method1);
//Method2 is implemented in the base class
var class2Method2SynthesizedExplicitImpl = class2.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Single();
Assert.Equal("Method2", class2Method2SynthesizedExplicitImpl.ExplicitInterfaceImplementations.Single().Name);
Assert.Same(baseClass, class2Method2SynthesizedExplicitImpl.ImplementingMethod.ContainingType);
AssertAllParametersHaveConstModOpt(class2Method2SynthesizedExplicitImpl);
var class3 = global.GetMember<SourceNamedTypeSymbol>("Class3");
//Method1 is implemented in Class3, but a bridge is needed because custom modifiers are not copied
var class3Method1 = class3.GetMember<MethodSymbol>("Method1");
Assert.False(class3Method1.Parameters.Single().TypeWithAnnotations.CustomModifiers.Any());
// GetSynthesizedExplicitImplementations doesn't guarantee order, so sort to make the asserts easier to write.
var class3SynthesizedExplicitImpls = (from m in class3.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods orderby m.Name select m).ToArray();
Assert.Equal(2, class3SynthesizedExplicitImpls.Length);
var class3Method1SynthesizedExplicitImpl = class3SynthesizedExplicitImpls[0];
Assert.Equal("Method1", class3Method1SynthesizedExplicitImpl.ExplicitInterfaceImplementations.Single().Name);
Assert.Same(class3Method1, class3Method1SynthesizedExplicitImpl.ImplementingMethod);
AssertAllParametersHaveConstModOpt(class3Method1SynthesizedExplicitImpl);
//Method2 is implemented in the base class
var class3Method2SynthesizedExplicitImpl = class3SynthesizedExplicitImpls[1];
Assert.Equal("Method2", class3Method2SynthesizedExplicitImpl.ExplicitInterfaceImplementations.Single().Name);
Assert.Same(baseClass, class3Method2SynthesizedExplicitImpl.ImplementingMethod.ContainingType);
AssertAllParametersHaveConstModOpt(class3Method2SynthesizedExplicitImpl);
}
/// <summary>
/// Test copying more than one custom modifier on the same element
/// </summary>
[Fact]
public void TestCopyMultipleCustomModifiers()
{
var text = @"
class Class : I2
{
//copy (both) modifiers (even though dev10 doesn't)
void I2.M1(int x) { }
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Class");
// explicit implementation copies custom modifiers
var classMethod1 = @class.GetMethod("I2.M1");
var classMethod1CustomModifiers = classMethod1.Parameters.Single().TypeWithAnnotations.CustomModifiers;
Assert.Equal(2, classMethod1CustomModifiers.Length);
foreach (var customModifier in classMethod1CustomModifiers)
{
Assert.Equal(ConstModOptType, customModifier.Modifier.ToTestDisplayString());
}
//no bridge methods
Assert.False(@class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Any());
}
/// <summary>
/// The params keyword is inherited from the overridden method in the same way as
/// a custom modifier.
/// </summary>
[Fact]
public void TestParamsKeyword()
{
var text = @"
public class Base
{
public virtual void M(params int[] a) { }
public virtual void N(int[] a) { }
}
public class Derived : Base
{
public override void M(int[] a) { } //lost 'params'
public override void N(params int[] a) { } //gained 'params'
}
public class Derived2 : Derived
{
public override void M(params int[] a) { } //regained 'params'
public override void N(int[] a) { } //(re)lost 'params'
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseClass = global.GetMember<NamedTypeSymbol>("Base");
var baseM = baseClass.GetMember<MethodSymbol>("M");
var baseN = baseClass.GetMember<MethodSymbol>("N");
var derivedClass = global.GetMember<NamedTypeSymbol>("Derived");
var derivedM = derivedClass.GetMember<MethodSymbol>("M");
var derivedN = derivedClass.GetMember<MethodSymbol>("N");
var derived2Class = global.GetMember<NamedTypeSymbol>("Derived2");
var derived2M = derived2Class.GetMember<MethodSymbol>("M");
var derived2N = derived2Class.GetMember<MethodSymbol>("N");
Assert.True(baseM.Parameters.Single().IsParams, "Base.M.IsParams should be true");
Assert.False(baseN.Parameters.Single().IsParams, "Base.N.IsParams should be false");
Assert.True(derivedM.Parameters.Single().IsParams, "Derived.M.IsParams should be true"); //NB: does not reflect source
Assert.False(derivedN.Parameters.Single().IsParams, "Derived.N.IsParams should be false"); //NB: does not reflect source
Assert.True(derived2M.Parameters.Single().IsParams, "Derived2.M.IsParams should be true");
Assert.False(derived2N.Parameters.Single().IsParams, "Derived2.N.IsParams should be false");
}
/// <summary>
/// Test implementing a single interface with custom modifiers.
/// </summary>
[Fact]
public void TestIndexerExplicitInterfaceImplementation()
{
var text = @"
class Explicit : CppCli.CppIndexerInterface
{
int CppCli.CppIndexerInterface.this[int x]
{
get { return 0; }
set { }
}
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Explicit");
// explicit implementation copies custom modifiers
var classIndexer = (PropertySymbol)@class.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single();
AssertAllParametersHaveConstModOpt(classIndexer);
Assert.Equal(0, @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
}
/// <summary>
/// Test implementing a single interface with custom modifiers.
/// </summary>
[Fact]
public void TestIndexerImplicitInterfaceImplementation()
{
var text = @"
class Implicit : CppCli.CppIndexerInterface
{
public int this[int x]
{
get { return 0; }
set { }
}
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Implicit");
// implicit implementation does not copy custom modifiers
var classIndexer = (PropertySymbol)@class.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single();
AssertNoParameterHasModOpts(classIndexer);
// bridge methods for implicit implementations have custom modifiers
var explicitImpls = @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods;
Assert.Equal(2, explicitImpls.Length);
var explicitGetterImpl = explicitImpls.Where(impl => impl.ImplementingMethod.MethodKind == MethodKind.PropertyGet).Single();
AssertAllParametersHaveConstModOpt(explicitGetterImpl);
var explicitSetterImpl = explicitImpls.Where(impl => impl.ImplementingMethod.MethodKind == MethodKind.PropertySet).Single();
AssertAllParametersHaveConstModOpt(explicitSetterImpl, ignoreLast: true);
}
/// <summary>
/// Test overriding a base type indexer with custom modifiers.
/// </summary>
[Fact]
public void TestOverrideIndexer()
{
var text = @"
class Override : CppCli.CppIndexerBase
{
public override int this[int x]
{
get { return 0; }
set { }
}
}
";
var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll;
var comp = CreateCompilation(text, new MetadataReference[] { ilAssemblyReference });
var global = comp.GlobalNamespace;
comp.VerifyDiagnostics();
var @class = global.GetMember<SourceNamedTypeSymbol>("Override");
// implicit implementation does not copy custom modifiers
var classIndexer = (PropertySymbol)@class.GetMembers().Where(s => s.Kind == SymbolKind.Property).Single();
AssertAllParametersHaveConstModOpt(classIndexer);
Assert.Equal(0, @class.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods.Length);
}
/// <summary>
/// The params keyword is inherited from the overridden indexer in the same way as
/// a custom modifier.
/// </summary>
[Fact]
public void TestParamsKeywordOnIndexer()
{
var text = @"
public class Base
{
public virtual char this[params int[] a] { set { } }
public virtual char this[long[] a] { set { } }
}
public class Derived : Base
{
public override char this[int[] a] { set { } } //lost 'params'
public override char this[params long[] a] { set { } } //gained 'params'
}
public class Derived2 : Derived
{
public override char this[params int[] a] { set { } } //regained 'params'
public override char this[long[] a] { set { } } //(re)lost 'params'
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseClass = global.GetMember<NamedTypeSymbol>("Base");
var baseIndexer1 = (PropertySymbol)baseClass.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int32, isArrayType: true)).Single();
var baseIndexer2 = (PropertySymbol)baseClass.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int64, isArrayType: true)).Single();
var derivedClass = global.GetMember<NamedTypeSymbol>("Derived");
var derivedIndexer1 = (PropertySymbol)derivedClass.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int32, isArrayType: true)).Single();
var derivedIndexer2 = (PropertySymbol)derivedClass.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int64, isArrayType: true)).Single();
var derived2Class = global.GetMember<NamedTypeSymbol>("Derived2");
var derived2Indexer1 = (PropertySymbol)derived2Class.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int32, isArrayType: true)).Single();
var derived2Indexer2 = (PropertySymbol)derived2Class.GetMembers().Where(IsPropertyWithSingleParameter(SpecialType.System_Int64, isArrayType: true)).Single();
Assert.True(baseIndexer1.Parameters.Single().IsParams, "Base.Indexer1.IsParams should be true");
Assert.False(baseIndexer2.Parameters.Single().IsParams, "Base.Indexer2.IsParams should be false");
Assert.True(derivedIndexer1.Parameters.Single().IsParams, "Derived.Indexer1.IsParams should be true"); //Indexer2B: does not reflect source
Assert.False(derivedIndexer2.Parameters.Single().IsParams, "Derived.Indexer2.IsParams should be false"); //Indexer2B: does not reflect source
Assert.True(derived2Indexer1.Parameters.Single().IsParams, "Derived2.Indexer1.IsParams should be true");
Assert.False(derived2Indexer2.Parameters.Single().IsParams, "Derived2.Indexer2.IsParams should be false");
}
[ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))]
[WorkItem(18411, "https://github.com/dotnet/roslyn/issues/18411")]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void Repro819774()
{
var il = @"
.class interface public abstract auto ansi IBug813305
{
.method public hidebysig newslot abstract virtual
instance void M(object modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
} // end of method IBug813305::M
} // end of class IBug813305
";
var source = @"
using System.Collections.Generic;
class Bug813305 : IBug813305
{
void IBug813305.M(dynamic x)
{
x.Goo();
System.Console.WriteLine(""Bug813305.M"");
}
public void Goo() {}
}
class Test
{
static void Main()
{
IBug813305 x = new Bug813305();
x.M(x);
}
}
";
var comp = CreateCompilationWithILAndMscorlib40(source, il,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All),
targetFramework: TargetFramework.Standard,
references: new[] { CSharpRef });
CompileAndVerify(comp, expectedOutput: "Bug813305.M",
symbolValidator: m =>
{
var Bug813305 = m.GlobalNamespace.GetTypeMember("Bug813305");
var method = Bug813305.GetMethod("IBug813305.M");
Assert.Equal("Bug813305.IBug813305.M(dynamic)", method.ToDisplayString());
});
}
[Fact]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void ObjectToDynamic_ImplementationParameter()
{
var il = @"
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance void M(object modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
}
}
";
var source = @"
class C : I
{
void I.M(dynamic x) { }
}
";
var comp = CreateCompilationWithILAndMscorlib40(source, il, targetFramework: TargetFramework.Standard);
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
Assert.Equal(SpecialType.System_Object, interfaceMethod.ParameterTypesWithAnnotations.Single().SpecialType);
Assert.Equal(TypeKind.Dynamic, classMethod.ParameterTypesWithAnnotations.Single().Type.TypeKind);
Assert.Equal("void C.I.M(dynamic modopt(System.Runtime.CompilerServices.IsLong) x)", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicToObject_ImplementationParameter()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance void M(object modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed
{
.param [1]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[2](false true)}
}
}
";
var source = @"
class C : I
{
void I.M(object x) { }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<MethodSymbol>("I.M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
Assert.Equal(TypeKind.Dynamic, interfaceMethod.ParameterTypesWithAnnotations.Single().Type.TypeKind);
Assert.Equal(SpecialType.System_Object, classMethod.ParameterTypesWithAnnotations.Single().SpecialType);
Assert.Equal("void C.I.M(System.Object modopt(System.Runtime.CompilerServices.IsLong) x)", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void TupleWithCustomModifiersInInterfaceMethod()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 }
.assembly '<<GeneratedFileName>>' { }
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
M(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> x) cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 63 01 64 00 00 ) // .......c.d..
} // end of method I::M
} // end of class I
";
var source1 = @"
class C : I
{
(object a, object b) I.M((object c, object d) x) { return x; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp1 = CreateEmptyCompilation(source1, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp1.VerifyDiagnostics();
var interfaceMethod1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("I.M");
var classMethod1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> " +
"I.M(System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> x)",
interfaceMethod1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) I.M((object c, object d) x)",
interfaceMethod1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)interfaceMethod1.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)interfaceMethod1.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> " +
"C.I.M(System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> x)",
classMethod1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) C.M((object c, object d) x)",
classMethod1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod1.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod1.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source2 = @"
class C : I
{
(object a, object b) I.M((object, object) x) { return x; }
}
";
var comp2 = CreateEmptyCompilation(source2, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp2.VerifyDiagnostics(
// (4,28): error CS8141: The tuple element names in the signature of method 'C.I.M((object, object))' must match the tuple element names of interface method 'I.M((object c, object d))' (including on the return type).
// (object a, object b) I.M((object, object) x) { return x; }
Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M").WithArguments("C.I.M((object, object))", "I.M((object c, object d))").WithLocation(4, 28)
);
var classMethod2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> " +
"C.I.M(System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> x)",
classMethod2.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod2.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod2.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source3 = @"
class C : I
{
(object, object) I.M((object c, object d) x) { return x; }
}
";
var comp3 = CreateEmptyCompilation(source3, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp3.VerifyDiagnostics(
// (4,24): error CS8141: The tuple element names in the signature of method 'C.I.M((object c, object d))' must match the tuple element names of interface method 'I.M((object c, object d))' (including on the return type).
// (object, object) I.M((object c, object d) x) { return x; }
Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M").WithArguments("C.I.M((object c, object d))", "I.M((object c, object d))").WithLocation(4, 24)
);
var classMethod3 = comp3.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
AssertEx.Equal("(object, object) C.M((object c, object d) x)", classMethod3.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod3.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod3.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source4 = @"
class C : I
{
public (object a, object b) M((object c, object d) x) { return x; }
}
";
var comp4 = CreateEmptyCompilation(source4, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp4.VerifyDiagnostics();
var classMethod4 = comp4.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("M");
AssertEx.Equal("(object a, object b) C.M((object c, object d) x)", classMethod4.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("(System.Object, System.Object)", ((NamedTypeSymbol)classMethod4.ReturnType).TupleUnderlyingType.ToTestDisplayString()); // modopts not copied
Assert.Equal("(System.Object, System.Object)", ((NamedTypeSymbol)classMethod4.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString()); // modopts not copied
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void TupleWithCustomModifiersInInterfaceProperty()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 }
.assembly '<<GeneratedFileName>>' { }
.class interface public abstract auto ansi I
{
.method public hidebysig newslot specialname abstract virtual
instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
get_P() cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
} // end of method I::get_P
.method public hidebysig newslot specialname abstract virtual
instance void set_P(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> 'value') cil managed
{
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
} // end of method I::set_P
.property instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong), object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
P()
{
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.get instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> I::get_P()
.set instance void I::set_P(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>)
} // end of property I::P
} // end of class I
";
var source1 = @"
class C : I
{
(object a, object b) I.P { get; set; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp1 = CreateEmptyCompilation(source1, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp1.VerifyDiagnostics();
var interfaceProperty1 = comp1.GlobalNamespace.GetMember<PropertySymbol>("I.P");
var classProperty1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("I.P");
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> I.P { get; set; }",
interfaceProperty1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) I.P", interfaceProperty1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)interfaceProperty1.Type).TupleUnderlyingType.ToTestDisplayString());
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> C.I.P { get; set; }",
classProperty1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) C.P", classProperty1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classProperty1.Type).TupleUnderlyingType.ToTestDisplayString());
var source2 = @"
class C : I
{
(object, object) I.P { get; set; }
}
";
var comp2 = CreateEmptyCompilation(source2, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp2.VerifyDiagnostics();
var classProperty2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("I.P");
Assert.Equal("(System.Object, System.Object) C.I.P { get; set; }", classProperty2.ToTestDisplayString());
Assert.Equal("(System.Object, System.Object)", ((NamedTypeSymbol)classProperty2.Type).TupleUnderlyingType.ToTestDisplayString());
var source3 = @"
class C : I
{
public (object a, object b) P { get; set; }
}
";
var comp3 = CreateEmptyCompilation(source3, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp3.VerifyDiagnostics();
var classProperty3 = comp3.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("P");
Assert.Equal("(System.Object a, System.Object b) C.P { get; set; }", classProperty3.ToTestDisplayString());
Assert.Equal("(System.Object, System.Object)", ((NamedTypeSymbol)classProperty3.Type).TupleUnderlyingType.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void TupleWithCustomModifiersInOverride()
{
// This IL is based on this code, but with modopts added
//public class Base
//{
// public virtual (object a, object b) P { get; set; }
// public virtual (object a, object b) M((object c, object d) x) { return x; }
//}
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 }
.assembly '<<GeneratedFileName>>' { }
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.field private class [System.ValueTuple]System.ValueTuple`2<object,object> '<P>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 )
.method public hidebysig newslot specialname virtual
instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
get_P() cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld class [System.ValueTuple]System.ValueTuple`2<object,object> Base::'<P>k__BackingField'
IL_0006: ret
} // end of method Base::get_P
.method public hidebysig newslot specialname virtual
instance void set_P(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld class [System.ValueTuple]System.ValueTuple`2<object,object> Base::'<P>k__BackingField'
IL_0007: ret
} // end of method Base::set_P
.method public hidebysig newslot virtual
instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
M(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> x) cil managed
{
.param [0]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.param [1]
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 63 01 64 00 00 ) // .......c.d..
// Code size 7 (0x7)
.maxstack 1
.locals init (class [System.ValueTuple]System.ValueTuple`2<object,object> V_0)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
IL_0005: ldloc.0
IL_0006: ret
} // end of method Base::M
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Base::.ctor
.property instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>
P()
{
.custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // .......a.b..
.get instance class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> Base::get_P()
.set instance void Base::set_P(class [System.ValueTuple]System.ValueTuple`2<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong),object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)>)
} // end of property Base::P
} // end of class Base
";
var source1 = @"
class C : Base
{
public override (object a, object b) P { get; set; }
public override (object a, object b) M((object c, object d) y) { return y; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp1 = CreateEmptyCompilation(source1, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp1.VerifyDiagnostics();
var baseMethod1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("Base.M");
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> " +
"Base.M(System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)> x)",
baseMethod1.ToTestDisplayString());
AssertEx.Equal("(object a, object b) Base.M((object c, object d) x)",
baseMethod1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)baseMethod1.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)baseMethod1.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var baseProperty1 = comp1.GlobalNamespace.GetMember<PropertySymbol>("Base.P");
Assert.Equal("(object a, object b) Base.P", baseProperty1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)baseProperty1.Type).TupleUnderlyingType.ToTestDisplayString());
var classProperty1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("P");
var classMethod1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("M");
Assert.Equal("(object a, object b) C.P", classProperty1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classProperty1.Type).TupleUnderlyingType.ToTestDisplayString());
AssertEx.Equal("(object a, object b) C.M((object c, object d) y)", classMethod1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod1.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod1.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source2 = @"
class C : Base
{
public override (object, object) P { get; set; }
public override (object, object) M((object c, object d) y) { return y; }
}
";
var comp2 = CreateEmptyCompilation(source2, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp2.VerifyDiagnostics(
// (5,38): error CS8139: 'C.M((object c, object d))': cannot change tuple element names when overriding inherited member 'Base.M((object c, object d))'
// public override (object, object) M((object c, object d) y) { return y; }
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("C.M((object c, object d))", "Base.M((object c, object d))").WithLocation(5, 38)
);
var classProperty2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetProperty("P");
var classMethod2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("M");
Assert.Equal("(System.Object, System.Object) C.P { get; set; }", classProperty2.ToTestDisplayString());
Assert.Equal("(System.Object, System.Object)",
((NamedTypeSymbol)classProperty2.Type).TupleUnderlyingType.ToTestDisplayString());
AssertEx.Equal("(object, object) C.M((object c, object d) y)", classMethod2.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod2.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod2.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
var source3 = @"
class C : Base
{
public override (object a, object b) P { get; set; }
public override (object a, object b) M((object, object) y) { return y; }
}
";
var comp3 = CreateEmptyCompilation(source3, new[] { MscorlibRef, SystemCoreRef, ilRef, ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef });
comp3.VerifyDiagnostics(
// (5,42): error CS8139: 'C.M((object, object))': cannot change tuple element names when overriding inherited member 'Base.M((object c, object d))'
// public override (object a, object b) M((object, object) y) { return y; }
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("C.M((object, object))", "Base.M((object c, object d))").WithLocation(5, 42)
);
var classMethod3 = comp3.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMethod("M");
AssertEx.Equal("(object a, object b) C.M((object, object) y)", classMethod3.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
AssertEx.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod3.ReturnType).TupleUnderlyingType.ToTestDisplayString());
Assert.Equal("System.ValueTuple<System.Object modopt(System.Runtime.CompilerServices.IsLong), System.Object modopt(System.Runtime.CompilerServices.IsLong)>",
((NamedTypeSymbol)classMethod3.GetParameterType(0)).TupleUnderlyingType.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicToObject_ImplementationReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance object modopt(int32) M() cil managed
{
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[2](false true)}
}
}
";
var source = @"
class C : I
{
object I.M() { throw null; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<MethodSymbol>("I.M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
Assert.Equal(TypeKind.Dynamic, interfaceMethod.ReturnType.TypeKind);
Assert.Equal(SpecialType.System_Object, classMethod.ReturnType.SpecialType);
Assert.Equal("System.Object modopt(System.Int32) C.I.M()", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void ObjectToDynamic_ImplementationReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.method public hidebysig newslot abstract virtual
instance object modopt(int32) M() cil managed
{
}
}
";
var source = @"
class C : I
{
dynamic I.M() { throw null; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
Assert.Equal(SpecialType.System_Object, interfaceMethod.ReturnType.SpecialType);
Assert.Equal(TypeKind.Dynamic, classMethod.ReturnType.TypeKind);
Assert.Equal("dynamic modopt(System.Int32) C.I.M()", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicVsObjectComplexParameter()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I`2<T,U>
{
.method public hidebysig newslot abstract virtual
instance void M(class I`2<object modopt(int16) [],object modopt(int32) []>& modopt(int64) c) cil managed
{
.param [1]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[9](false false false false false false false false true)} // i.e. second occurrence of 'object' is really 'dynamic'.
}
}
";
var source = @"
public class C : I<byte, char>
{
void I<byte, char>.M(ref I<dynamic[], object[]> c) { } // object to dynamic and vice versa
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Single(
m => m.MethodKind == MethodKind.ExplicitInterfaceImplementation);
Assert.Equal("void I<T, U>.M(ref modopt(System.Int64) I<System.Object modopt(System.Int16) [], dynamic modopt(System.Int32) []> c)", interfaceMethod.ToTestDisplayString());
Assert.Equal("void C.I<System.Byte, System.Char>.M(ref modopt(System.Int64) I<dynamic modopt(System.Int16) [], System.Object modopt(System.Int32) []> c)", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicVsObjectComplexReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I`2<T,U>
{
.method public hidebysig newslot abstract virtual
instance class I`2<object modopt(int16) [],object modopt(int32) []> modopt(int64) M() cil managed
{
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[8](false false false false false false false true)} // i.e. second occurrence of 'object' is really 'dynamic'.
}
}
";
var source = @"
public class C : I<byte, char>
{
I<dynamic[], object[]> I<byte, char>.M() { throw null; } // object to dynamic and vice versa
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceMethod = global.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("M");
var classMethod = global.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Single(
m => m.MethodKind == MethodKind.ExplicitInterfaceImplementation);
Assert.Equal("I<System.Object modopt(System.Int16) [], dynamic modopt(System.Int32) []> modopt(System.Int64) I<T, U>.M()", interfaceMethod.ToTestDisplayString());
Assert.Equal("I<dynamic modopt(System.Int16) [], System.Object modopt(System.Int32) []> modopt(System.Int64) C.I<System.Byte, System.Char>.M()", classMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicToObjectAndViceVersa_OverrideParameter()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual
instance void M(object modopt(int16) o,
object modopt(int32) d) cil managed
{
.param [2]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[2](false true)}
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override void M(dynamic o, object d) { }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseMethod = global.GetMember<NamedTypeSymbol>("Base").GetMember<MethodSymbol>("M");
var derivedMethod = global.GetMember<NamedTypeSymbol>("Derived").GetMember<MethodSymbol>("M");
Assert.Equal("void Base.M(System.Object modopt(System.Int16) o, dynamic modopt(System.Int32) d)", baseMethod.ToTestDisplayString());
Assert.Equal("void Derived.M(dynamic modopt(System.Int16) o, System.Object modopt(System.Int32) d)", derivedMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void DynamicToObject_OverrideReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly extern System.Core {}
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual
instance object modopt(int32) M() cil managed
{
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[])
= {bool[2](false true)}
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override object M() { throw null; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseMethod = global.GetMember<NamedTypeSymbol>("Base").GetMember<MethodSymbol>("M");
var derivedMethod = global.GetMember<NamedTypeSymbol>("Derived").GetMember<MethodSymbol>("M");
Assert.Equal("dynamic modopt(System.Int32) Base.M()", baseMethod.ToTestDisplayString());
Assert.Equal("System.Object modopt(System.Int32) Derived.M()", derivedMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(819774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/819774")]
public void ObjectToDynamic_OverrideReturn()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual
instance object modopt(int32) M() cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override dynamic M() { throw null; }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseMethod = global.GetMember<NamedTypeSymbol>("Base").GetMember<MethodSymbol>("M");
var derivedMethod = global.GetMember<NamedTypeSymbol>("Derived").GetMember<MethodSymbol>("M");
Assert.Equal("System.Object modopt(System.Int32) Base.M()", baseMethod.ToTestDisplayString());
Assert.Equal("dynamic modopt(System.Int32) Derived.M()", derivedMethod.ToTestDisplayString());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(830632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830632")]
public void AccessorsAddCustomModifiers_Override()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname virtual instance char modopt(int8)
get_P() cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual instance void
set_P(char modopt(int16) 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual instance int32 modopt(int8)
get_Item(bool modopt(int16) x) cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual instance void
set_Item(bool modopt(int32) x,
int32 modopt(int64) 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance char P()
{
.get instance char modopt(int8) Base::get_P()
.set instance void Base::set_P(char modopt(int16))
}
.property instance int32 Item(bool)
{
.get instance int32 modopt(int8) Base::get_Item(bool modopt(int16))
.set instance void Base::set_Item(bool modopt(int32),
int32 modopt(int64))
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override char P { get { return 'a'; } set { } }
public override int this[bool x] { get { return 0; } set { } }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseType = global.GetMember<NamedTypeSymbol>("Base");
var baseProperty = baseType.GetMember<PropertySymbol>("P");
var baseIndexer = baseType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var derivedType = global.GetMember<NamedTypeSymbol>("Derived");
var derivedProperty = derivedType.GetMember<PropertySymbol>("P");
var derivedIndexer = derivedType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var int8Type = comp.GetSpecialType(SpecialType.System_SByte);
var int16Type = comp.GetSpecialType(SpecialType.System_Int16);
var int32Type = comp.GetSpecialType(SpecialType.System_Int32);
var int64Type = comp.GetSpecialType(SpecialType.System_Int64);
// None of the properties have custom modifiers - only the accessors do.
Assert.Equal(0, baseProperty.CustomModifierCount());
Assert.Equal(0, baseIndexer.CustomModifierCount());
Assert.Equal(0, derivedProperty.CustomModifierCount());
Assert.Equal(0, derivedIndexer.CustomModifierCount());
Assert.Equal(int8Type, baseProperty.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, derivedProperty.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, baseProperty.SetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, derivedProperty.SetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, baseIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, derivedIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, baseIndexer.GetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, derivedIndexer.GetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int32Type, baseIndexer.SetMethod.Parameters[0].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int32Type, derivedIndexer.SetMethod.Parameters[0].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int64Type, baseIndexer.SetMethod.Parameters[1].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int64Type, derivedIndexer.SetMethod.Parameters[1].TypeWithAnnotations.CustomModifiers.Single().Modifier());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(830632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830632")]
public void AccessorsRemoveCustomModifiers_Override()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname virtual instance char
get_P() cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual instance void
set_P(char 'value') cil managed
{
ret
}
.method public hidebysig newslot specialname virtual instance int32
get_Item(bool x) cil managed
{
ldnull
ret
}
.method public hidebysig newslot specialname virtual instance void
set_Item(bool x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance char modopt(int8) P()
{
.get instance char Base::get_P()
.set instance void Base::set_P(char)
}
.property instance int32 modopt(int8) Item(bool modopt(int16))
{
.get instance int32 Base::get_Item(bool)
.set instance void Base::set_Item(bool,
int32)
}
} // end of class Base
";
var source = @"
class Derived : Base
{
public override char P { get { return 'a'; } set { } }
public override int this[bool x] { get { return 0; } set { } }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var baseType = global.GetMember<NamedTypeSymbol>("Base");
var baseProperty = baseType.GetMember<PropertySymbol>("P");
var baseIndexer = baseType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var derivedType = global.GetMember<NamedTypeSymbol>("Derived");
var derivedProperty = derivedType.GetMember<PropertySymbol>("P");
var derivedIndexer = derivedType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var int8Type = comp.GetSpecialType(SpecialType.System_SByte);
var int16Type = comp.GetSpecialType(SpecialType.System_Int16);
// None of the accessors have custom modifiers - only the properties do.
Assert.Equal(0, baseProperty.GetMethod.CustomModifierCount());
Assert.Equal(0, baseProperty.SetMethod.CustomModifierCount());
Assert.Equal(0, baseIndexer.GetMethod.CustomModifierCount());
Assert.Equal(0, baseIndexer.SetMethod.CustomModifierCount());
Assert.Equal(0, derivedProperty.GetMethod.CustomModifierCount());
Assert.Equal(0, derivedProperty.SetMethod.CustomModifierCount());
Assert.Equal(0, derivedIndexer.GetMethod.CustomModifierCount());
Assert.Equal(0, derivedIndexer.SetMethod.CustomModifierCount());
Assert.Equal(int8Type, baseProperty.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, derivedProperty.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, baseIndexer.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, derivedIndexer.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, baseIndexer.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, derivedIndexer.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
CompileAndVerify(comp);
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(830632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830632")]
public void AccessorsAddCustomModifiers_ExplicitImplementation()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname abstract virtual instance char modopt(int8)
get_P() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
set_P(char modopt(int16) 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance int32 modopt(int8)
get_Item(bool modopt(int16) x) cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
set_Item(bool modopt(int32) x,
int32 modopt(int64) 'value') cil managed
{
}
.property instance char P()
{
.get instance char modopt(int8) I::get_P()
.set instance void I::set_P(char modopt(int16))
}
.property instance int32 Item(bool)
{
.get instance int32 modopt(int8) I::get_Item(bool modopt(int16))
.set instance void I::set_Item(bool modopt(int32),
int32 modopt(int64))
}
} // end of class Base
";
var source = @"
class Implementation : I
{
char I.P { get { return 'a'; } set { } }
int I.this[bool x] { get { return 0; } set { } }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceType = global.GetMember<NamedTypeSymbol>("I");
var interfaceProperty = interfaceType.GetMember<PropertySymbol>("P");
var interfaceIndexer = interfaceType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var implementationType = global.GetMember<NamedTypeSymbol>("Implementation");
var implementationProperty = (PropertySymbol)implementationType.FindImplementationForInterfaceMember(interfaceProperty);
var implementationIndexer = (PropertySymbol)implementationType.FindImplementationForInterfaceMember(interfaceIndexer);
var int8Type = comp.GetSpecialType(SpecialType.System_SByte);
var int16Type = comp.GetSpecialType(SpecialType.System_Int16);
var int32Type = comp.GetSpecialType(SpecialType.System_Int32);
var int64Type = comp.GetSpecialType(SpecialType.System_Int64);
// None of the properties have custom modifiers - only the accessors do.
Assert.Equal(0, interfaceProperty.CustomModifierCount());
Assert.Equal(0, interfaceIndexer.CustomModifierCount());
Assert.Equal(0, implementationProperty.CustomModifierCount());
Assert.Equal(0, implementationIndexer.CustomModifierCount());
Assert.Equal(int8Type, interfaceProperty.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, implementationProperty.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, interfaceProperty.SetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, implementationProperty.SetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, interfaceIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, implementationIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, interfaceIndexer.GetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, implementationIndexer.GetMethod.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int32Type, interfaceIndexer.SetMethod.Parameters[0].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int32Type, implementationIndexer.SetMethod.Parameters[0].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int64Type, interfaceIndexer.SetMethod.Parameters[1].TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int64Type, implementationIndexer.SetMethod.Parameters[1].TypeWithAnnotations.CustomModifiers.Single().Modifier());
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
[WorkItem(830632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/830632")]
public void AccessorsRemoveCustomModifiers_ExplicitImplementation()
{
var il = @"
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>'
{
}
.class interface public abstract auto ansi I
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname abstract virtual instance char
get_P() cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
set_P(char 'value') cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance int32
get_Item(bool x) cil managed
{
}
.method public hidebysig newslot specialname abstract virtual instance void
set_Item(bool x,
int32 'value') cil managed
{
}
.property instance char modopt(int8) P()
{
.get instance char I::get_P()
.set instance void I::set_P(char)
}
.property instance int32 modopt(int8) Item(bool modopt(int16))
{
.get instance int32 I::get_Item(bool)
.set instance void I::set_Item(bool,
int32)
}
} // end of class Base
";
var source = @"
class Implementation : I
{
char I.P { get { return 'a'; } set { } }
int I.this[bool x] { get { return 0; } set { } }
}
";
var ilRef = CompileIL(il, prependDefaultHeader: false);
var comp = CreateEmptyCompilation(source, new[] { MscorlibRef, SystemCoreRef, ilRef });
comp.VerifyDiagnostics();
var global = comp.GlobalNamespace;
var interfaceType = global.GetMember<NamedTypeSymbol>("I");
var interfaceProperty = interfaceType.GetMember<PropertySymbol>("P");
var interfaceIndexer = interfaceType.GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
var implementationType = global.GetMember<NamedTypeSymbol>("Implementation");
var implementationProperty = (PropertySymbol)implementationType.FindImplementationForInterfaceMember(interfaceProperty);
var implementationIndexer = (PropertySymbol)implementationType.FindImplementationForInterfaceMember(interfaceIndexer);
var int8Type = comp.GetSpecialType(SpecialType.System_SByte);
var int16Type = comp.GetSpecialType(SpecialType.System_Int16);
// None of the accessors have custom modifiers - only the properties do.
Assert.Equal(0, interfaceProperty.GetMethod.CustomModifierCount());
Assert.Equal(0, interfaceProperty.SetMethod.CustomModifierCount());
Assert.Equal(0, interfaceIndexer.GetMethod.CustomModifierCount());
Assert.Equal(0, interfaceIndexer.SetMethod.CustomModifierCount());
Assert.Equal(0, implementationProperty.GetMethod.CustomModifierCount());
Assert.Equal(0, implementationProperty.SetMethod.CustomModifierCount());
Assert.Equal(0, implementationIndexer.GetMethod.CustomModifierCount());
Assert.Equal(0, implementationIndexer.SetMethod.CustomModifierCount());
Assert.Equal(int8Type, interfaceProperty.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, implementationProperty.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, interfaceIndexer.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int8Type, implementationIndexer.TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, interfaceIndexer.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
Assert.Equal(int16Type, implementationIndexer.Parameters.Single().TypeWithAnnotations.CustomModifiers.Single().Modifier());
CompileAndVerify(comp);
}
private static Func<Symbol, bool> IsPropertyWithSingleParameter(SpecialType paramSpecialType, bool isArrayType = false)
{
return s =>
{
if (s.Kind != SymbolKind.Property)
{
return false;
}
var paramType = s.GetParameters().Single().Type;
var comparisonType = isArrayType ? ((ArrayTypeSymbol)paramType).ElementType : paramType;
return comparisonType.SpecialType == paramSpecialType;
};
}
private static void AssertAllParametersHaveConstModOpt(Symbol member, bool ignoreLast = false)
{
int numParameters = member.GetParameterCount();
var parameters = member.GetParameters();
for (int i = 0; i < numParameters; i++)
{
if (!(ignoreLast && i == numParameters - 1))
{
var param = parameters[i];
Assert.Equal(ConstModOptType, param.TypeWithAnnotations.CustomModifiers.Single().Modifier.ToTestDisplayString());
}
}
}
private static void AssertNoParameterHasModOpts(Symbol member)
{
foreach (var param in member.GetParameters())
{
Assert.Equal(0, param.TypeWithAnnotations.CustomModifiers.Length);
}
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_Experimental.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.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_Experimental : CSharpTestBase
{
private const string DeprecatedAttributeSource =
@"using System;
namespace Windows.Foundation.Metadata
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true)]
public sealed class DeprecatedAttribute : Attribute
{
public DeprecatedAttribute(System.String message, DeprecationType type, System.UInt32 version)
{
}
}
public enum DeprecationType
{
Deprecate = 0,
Remove = 1
}
}";
private const string ExperimentalAttributeSource =
@"using System;
namespace Windows.Foundation.Metadata
{
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate,
AllowMultiple = false)]
public sealed class ExperimentalAttribute : Attribute
{
}
}";
[Fact]
public void TestExperimentalAttribute()
{
var source1 =
@"using Windows.Foundation.Metadata;
namespace N
{
[Experimental] public struct S { }
[Experimental] internal delegate void D<T>();
public class A<T>
{
[Experimental] public class B { }
static void M()
{
new B();
D<int> d = null;
d();
}
}
[Experimental] public enum E { A }
}";
var comp1 = CreateCompilation(new[] { Parse(ExperimentalAttributeSource), Parse(source1) });
comp1.VerifyDiagnostics(
// (11,17): warning CS8305: 'N.A<T>.B' is for evaluation purposes only and is subject to change or removal in future updates.
// new B();
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("N.A<T>.B").WithLocation(11, 17),
// (12,13): warning CS8305: 'N.D<int>' is for evaluation purposes only and is subject to change or removal in future updates.
// D<int> d = null;
Diagnostic(ErrorCode.WRN_Experimental, "D<int>").WithArguments("N.D<int>").WithLocation(12, 13));
var source2 =
@"using N;
using B = N.A<int>.B;
#pragma warning disable 219
class C
{
static void F()
{
object o = new B();
o = default(S);
var e = default(E);
e = E.A;
}
}";
var comp2A = CreateCompilation(source2, new[] { comp1.EmitToImageReference() });
comp2A.VerifyDiagnostics(
// (8,24): warning CS8305: 'N.A<int>.B' is for evaluation purposes only and is subject to change or removal in future updates.
// object o = new B();
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("N.A<int>.B").WithLocation(8, 24),
// (9,21): warning CS8305: 'N.S' is for evaluation purposes only and is subject to change or removal in future updates.
// o = default(S);
Diagnostic(ErrorCode.WRN_Experimental, "S").WithArguments("N.S").WithLocation(9, 21),
// (10,25): warning CS8305: 'N.E' is for evaluation purposes only and is subject to change or removal in future updates.
// var e = default(E);
Diagnostic(ErrorCode.WRN_Experimental, "E").WithArguments("N.E").WithLocation(10, 25),
// (11,13): warning CS8305: 'N.E' is for evaluation purposes only and is subject to change or removal in future updates.
// e = E.A;
Diagnostic(ErrorCode.WRN_Experimental, "E").WithArguments("N.E").WithLocation(11, 13));
var comp2B = CreateCompilation(source2, new[] { new CSharpCompilationReference(comp1) });
comp2B.VerifyDiagnostics(
// (8,24): warning CS8305: 'N.A<int>.B' is for evaluation purposes only and is subject to change or removal in future updates.
// object o = new B();
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("N.A<int>.B").WithLocation(8, 24),
// (9,21): warning CS8305: 'N.S' is for evaluation purposes only and is subject to change or removal in future updates.
// o = default(S);
Diagnostic(ErrorCode.WRN_Experimental, "S").WithArguments("N.S").WithLocation(9, 21),
// (10,25): warning CS8305: 'N.E' is for evaluation purposes only and is subject to change or removal in future updates.
// var e = default(E);
Diagnostic(ErrorCode.WRN_Experimental, "E").WithArguments("N.E").WithLocation(10, 25),
// (11,13): warning CS8305: 'N.E' is for evaluation purposes only and is subject to change or removal in future updates.
// e = E.A;
Diagnostic(ErrorCode.WRN_Experimental, "E").WithArguments("N.E").WithLocation(11, 13));
}
// [Experimental] applied to members even though
// AttributeUsage is types only.
[Fact]
public void TestExperimentalMembers()
{
var source0 =
@".class public Windows.Foundation.Metadata.ExperimentalAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 1C 14 00 00 01 00 54 02 0D 41 6C 6C 6F 77 // ........T..Allow
4D 75 6C 74 69 70 6C 65 00 ) // Multiple.
}
.class public E extends [mscorlib]System.Enum
{
.field public specialname rtspecialname int32 value__
.field public static literal valuetype E A = int32(0x00000000)
.custom instance void Windows.Foundation.Metadata.ExperimentalAttribute::.ctor() = ( 01 00 00 00 )
.field public static literal valuetype E B = int32(0x00000001)
}
.class interface public I
{
.method public abstract virtual instance void F()
{
.custom instance void Windows.Foundation.Metadata.ExperimentalAttribute::.ctor() = ( 01 00 00 00 )
}
}
.class public C implements I
{
.method public virtual final instance void F() { ret }
}";
var ref0 = CompileIL(source0);
var source1 =
@"#pragma warning disable 219
class Program
{
static void Main()
{
E e = default(E);
e = E.A; // warning CS8305: 'E.A' is for evaluation purposes only
e = E.B;
var o = default(C);
o.F();
((I)o).F(); // warning CS8305: 'I.F()' is for evaluation purposes only
}
}";
var comp1 = CreateCompilation(source1, new[] { ref0 });
comp1.VerifyDiagnostics(
// (7,13): warning CS8305: 'E.A' is for evaluation purposes only and is subject to change or removal in future updates.
// e = E.A; // warning CS8305: 'F.A' is for evaluation purposes only
Diagnostic(ErrorCode.WRN_Experimental, "E.A").WithArguments("E.A").WithLocation(7, 13),
// (11,9): warning CS8305: 'I.F()' is for evaluation purposes only and is subject to change or removal in future updates.
// ((I)o).F(); // warning CS8305: 'I.F()' is for evaluation purposes only
Diagnostic(ErrorCode.WRN_Experimental, "((I)o).F()").WithArguments("I.F()").WithLocation(11, 9));
}
[Fact]
public void TestExperimentalTypeWithDeprecatedAndObsoleteMembers()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Experimental]
class A
{
internal void F0() { }
[Deprecated("""", DeprecationType.Deprecate, 0)]
internal void F1() { }
[Deprecated("""", DeprecationType.Remove, 0)]
internal void F2() { }
[Obsolete("""", false)]
internal void F3() { }
[Obsolete("""", true)]
internal void F4() { }
[Experimental]
internal class B { }
}
class C
{
static void F(A a)
{
a.F0();
a.F1();
a.F2();
a.F3();
a.F4();
(new A.B()).ToString();
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(DeprecatedAttributeSource), Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (20,19): warning CS8305: 'A' is for evaluation purposes only and is subject to change or removal in future updates.
// static void F(A a)
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("A").WithLocation(20, 19),
// (23,9): warning CS0618: 'A.F1()' is obsolete: ''
// a.F1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "a.F1()").WithArguments("A.F1()", "").WithLocation(23, 9),
// (24,9): error CS0619: 'A.F2()' is obsolete: ''
// a.F2();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "a.F2()").WithArguments("A.F2()", "").WithLocation(24, 9),
// (25,9): warning CS0618: 'A.F3()' is obsolete: ''
// a.F3();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "a.F3()").WithArguments("A.F3()", "").WithLocation(25, 9),
// (26,9): error CS0619: 'A.F4()' is obsolete: ''
// a.F4();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "a.F4()").WithArguments("A.F4()", "").WithLocation(26, 9),
// (27,14): warning CS8305: 'A' is for evaluation purposes only and is subject to change or removal in future updates.
// (new A.B()).ToString();
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("A").WithLocation(27, 14),
// (27,14): warning CS8305: 'A.B' is for evaluation purposes only and is subject to change or removal in future updates.
// (new A.B()).ToString();
Diagnostic(ErrorCode.WRN_Experimental, "A.B").WithArguments("A.B").WithLocation(27, 14));
}
[Fact]
public void TestDeprecatedLocalFunctions()
{
var source =
@"
using Windows.Foundation.Metadata;
class A
{
void M()
{
local1(); // 1
local2(); // 2
[Deprecated("""", DeprecationType.Deprecate, 0)]
void local1() { }
[Deprecated("""", DeprecationType.Remove, 0)]
void local2() { }
#pragma warning disable 8321 // Unreferenced local function
[Deprecated("""", DeprecationType.Deprecate, 0)]
void local3()
{
// No obsolete warnings expected inside a deprecated local function
local1();
local2();
}
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { DeprecatedAttributeSource, ExperimentalAttributeSource, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,9): warning CS0618: 'local1()' is obsolete: ''
// local1(); // 1
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "local1()").WithArguments("local1()", "").WithLocation(7, 9),
// (8,9): error CS0619: 'local2()' is obsolete: ''
// local2(); // 2
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "local2()").WithArguments("local2()", "").WithLocation(8, 9));
}
// Diagnostics for [Obsolete] members
// are not suppressed in [Experimental] types.
[Fact]
public void TestObsoleteMembersInExperimentalType()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
class A
{
internal void F0() { }
[Deprecated("""", DeprecationType.Deprecate, 0)]
internal void F1() { }
[Deprecated("""", DeprecationType.Remove, 0)]
internal void F2() { }
[Obsolete("""", false)]
internal void F3() { }
[Obsolete("""", true)]
internal void F4() { }
[Experimental]
internal class B { }
}
[Experimental]
class C
{
static void F(A a)
{
a.F0();
a.F1();
a.F2();
a.F3();
a.F4();
(new A.B()).ToString();
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(DeprecatedAttributeSource), Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (23,9): warning CS0618: 'A.F1()' is obsolete: ''
// a.F1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "a.F1()").WithArguments("A.F1()", "").WithLocation(23, 9),
// (24,9): error CS0619: 'A.F2()' is obsolete: ''
// a.F2();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "a.F2()").WithArguments("A.F2()", "").WithLocation(24, 9),
// (25,9): warning CS0618: 'A.F3()' is obsolete: ''
// a.F3();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "a.F3()").WithArguments("A.F3()", "").WithLocation(25, 9),
// (26,9): error CS0619: 'A.F4()' is obsolete: ''
// a.F4();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "a.F4()").WithArguments("A.F4()", "").WithLocation(26, 9),
// (27,14): warning CS8305: 'A.B' is for evaluation purposes only and is subject to change or removal in future updates.
// (new A.B()).ToString();
Diagnostic(ErrorCode.WRN_Experimental, "A.B").WithArguments("A.B").WithLocation(27, 14));
}
[Fact]
public void TestObsoleteMembersInExperimentalTypeInObsoleteType()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
class A
{
[Obsolete("""", false)]
internal void F() { }
}
[Obsolete("""", false)]
class B
{
[Experimental]
class C
{
static void G(A a)
{
a.F();
}
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(DeprecatedAttributeSource), Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics();
}
// Diagnostics for [Experimental] types
// are not suppressed in [Obsolete] members.
[Fact]
public void TestExperimentalTypeInObsoleteMember()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Experimental] class A { }
[Experimental] class B { }
class C
{
static object FA() => new A();
[Obsolete("""", false)]
static object FB() => new B();
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (7,31): warning CS8305: 'A' is for evaluation purposes only and is subject to change or removal in future updates.
// static object FA() => new A();
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("A"),
// (9,31): warning CS8305: 'B' is for evaluation purposes only and is subject to change or removal in future updates.
// static object FB() => new B();
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("B").WithLocation(9, 31));
}
[Fact]
public void TestExperimentalTypeWithAttributeMarkedObsolete()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Obsolete]
class MyAttribute : Attribute
{
}
[Experimental]
[MyAttribute]
class A
{
}
class B
{
A F() => null;
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (8,2): warning CS0612: 'MyAttribute' is obsolete
// [MyAttribute]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyAttribute").WithArguments("MyAttribute"),
// (14,5): warning CS8305: 'A' is for evaluation purposes only and is subject to change or removal in future updates.
// A F() => null;
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("A").WithLocation(14, 5));
}
[Fact]
public void TestObsoleteTypeWithAttributeMarkedExperimental()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Experimental]
class MyAttribute : Attribute
{
}
[Obsolete]
[MyAttribute]
class A
{
}
class B
{
A F() => null;
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (8,2): warning CS8305: 'MyAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [MyAttribute]
Diagnostic(ErrorCode.WRN_Experimental, "MyAttribute").WithArguments("MyAttribute").WithLocation(8, 2),
// (14,5): warning CS0612: 'A' is obsolete
// A F() => null;
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "A").WithArguments("A").WithLocation(14, 5));
}
[Fact]
public void TestAttributesMarkedExperimentalAndObsolete()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Experimental]
[B]
class AAttribute : Attribute
{
}
[Obsolete]
[A]
class BAttribute : Attribute
{
}
[A]
[B]
class C
{
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (9,2): warning CS8305: 'AAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [A]
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("AAttribute").WithLocation(9, 2),
// (4,2): warning CS0612: 'BAttribute' is obsolete
// [B]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "B").WithArguments("BAttribute").WithLocation(4, 2),
// (13,2): warning CS8305: 'AAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [A]
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("AAttribute").WithLocation(13, 2),
// (14,2): warning CS0612: 'BAttribute' is obsolete
// [B]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "B").WithArguments("BAttribute").WithLocation(14, 2));
}
[Fact]
public void TestAttributesMarkedExperimentalAndObsolete2()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Obsolete]
[B]
class AAttribute : Attribute
{
}
[Experimental]
[A]
class BAttribute : Attribute
{
}
[A]
[B]
class C
{
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (9,2): warning CS0612: 'AAttribute' is obsolete
// [A]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "A").WithArguments("AAttribute").WithLocation(9, 2),
// (4,2): warning CS8305: 'BAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [B]
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("BAttribute").WithLocation(4, 2),
// (13,2): warning CS0612: 'AAttribute' is obsolete
// [A]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "A").WithArguments("AAttribute").WithLocation(13, 2),
// (14,2): warning CS8305: 'BAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [B]
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("BAttribute").WithLocation(14, 2));
}
// Combinations of attributes.
[Fact]
public void TestDeprecatedAndExperimentalAndObsoleteAttributes()
{
var source1 =
@"using System;
using Windows.Foundation.Metadata;
[Obsolete(""OA"", false), Deprecated(""DA"", DeprecationType.Deprecate, 0)]public struct SA { }
[Obsolete(""OB"", false), Deprecated(""DB"", DeprecationType.Remove, 0)] public struct SB { }
[Obsolete(""OC"", false), Experimental] public struct SC { }
[Obsolete(""OD"", true), Deprecated(""DC"", DeprecationType.Deprecate, 0)]public struct SD { }
[Obsolete(""OE"", true), Deprecated(""DD"", DeprecationType.Remove, 0)] public struct SE { }
[Obsolete(""OF"", true), Experimental] public struct SF { }
[Deprecated(""DG"", DeprecationType.Deprecate, 0), Obsolete(""OG"", false)] public interface IG { }
[Deprecated(""DH"", DeprecationType.Deprecate, 0), Obsolete(""OH"", true)] public interface IH { }
[Deprecated(""DI"", DeprecationType.Deprecate, 0), Experimental] public interface II { }
[Deprecated(""DJ"", DeprecationType.Remove, 0), Obsolete(""OJ"", false)] public interface IJ { }
[Deprecated(""DK"", DeprecationType.Remove, 0), Obsolete(""OK"", true)] public interface IK { }
[Deprecated(""DL"", DeprecationType.Remove, 0), Experimental] public interface IL { }
[Experimental, Obsolete(""OM"", false)] public enum EM { }
[Experimental, Obsolete(""ON"", true)] public enum EN { }
[Experimental, Deprecated(""DO"", DeprecationType.Deprecate, 0)]public enum EO { }
[Experimental, Deprecated(""DP"", DeprecationType.Remove, 0)] public enum EP { }";
var comp1 = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(DeprecatedAttributeSource), Parse(ExperimentalAttributeSource), Parse(source1) });
comp1.VerifyDiagnostics();
var source2 =
@"class C
{
static void F(object o) { }
static void Main()
{
F(default(SA));
F(default(SB));
F(default(SC));
F(default(SD));
F(default(SE));
F(default(SF));
F(default(IG));
F(default(IH));
F(default(II));
F(default(IJ));
F(default(IK));
F(default(EM));
F(default(EN));
F(default(EO));
F(default(EP));
}
}";
var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, references: new[] { comp1.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (6,19): warning CS0618: 'SA' is obsolete: 'DA'
// F(default(SA));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SA").WithArguments("SA", "DA").WithLocation(6, 19),
// (7,19): error CS0619: 'SB' is obsolete: 'DB'
// F(default(SB));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "SB").WithArguments("SB", "DB").WithLocation(7, 19),
// (8,19): warning CS0618: 'SC' is obsolete: 'OC'
// F(default(SC));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SC").WithArguments("SC", "OC").WithLocation(8, 19),
// (9,19): warning CS0618: 'SD' is obsolete: 'DC'
// F(default(SD));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SD").WithArguments("SD", "DC").WithLocation(9, 19),
// (10,19): error CS0619: 'SE' is obsolete: 'DD'
// F(default(SE));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "SE").WithArguments("SE", "DD").WithLocation(10, 19),
// (11,19): error CS0619: 'SF' is obsolete: 'OF'
// F(default(SF));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "SF").WithArguments("SF", "OF").WithLocation(11, 19),
// (12,19): warning CS0618: 'IG' is obsolete: 'DG'
// F(default(IG));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "IG").WithArguments("IG", "DG").WithLocation(12, 19),
// (13,19): warning CS0618: 'IH' is obsolete: 'DH'
// F(default(IH));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "IH").WithArguments("IH", "DH").WithLocation(13, 19),
// (14,19): warning CS0618: 'II' is obsolete: 'DI'
// F(default(II));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "II").WithArguments("II", "DI").WithLocation(14, 19),
// (15,19): error CS0619: 'IJ' is obsolete: 'DJ'
// F(default(IJ));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "IJ").WithArguments("IJ", "DJ").WithLocation(15, 19),
// (16,19): error CS0619: 'IK' is obsolete: 'DK'
// F(default(IK));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "IK").WithArguments("IK", "DK").WithLocation(16, 19),
// (17,19): warning CS0618: 'EM' is obsolete: 'OM'
// F(default(EM));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "EM").WithArguments("EM", "OM").WithLocation(17, 19),
// (18,19): error CS0619: 'EN' is obsolete: 'ON'
// F(default(EN));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "EN").WithArguments("EN", "ON").WithLocation(18, 19),
// (19,19): warning CS0618: 'EO' is obsolete: 'DO'
// F(default(EO));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "EO").WithArguments("EO", "DO").WithLocation(19, 19),
// (20,19): error CS0619: 'EP' is obsolete: 'DP'
// F(default(EP));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "EP").WithArguments("EP", "DP").WithLocation(20, 19));
}
[Fact]
public void TestImportStatements()
{
var source =
@"#pragma warning disable 219
#pragma warning disable 8019
using System;
using Windows.Foundation.Metadata;
using CA = C<A>;
using CB = C<B>;
using CC = C<C>;
using CD = C<D>;
[Obsolete] class A { }
[Obsolete] class B { }
[Experimental] class C { }
[Experimental] class D { }
class C<T> { }
class P
{
static void Main()
{
object o;
o = default(CB);
o = default(CD);
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (19,21): warning CS0612: 'B' is obsolete
// o = default(CB);
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "CB").WithArguments("B").WithLocation(19, 21),
// (20,21): warning CS8305: 'D' is for evaluation purposes only and is subject to change or removal in future updates.
// o = default(CD);
Diagnostic(ErrorCode.WRN_Experimental, "CD").WithArguments("D").WithLocation(20, 21));
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_Experimental : CSharpTestBase
{
private const string DeprecatedAttributeSource =
@"using System;
namespace Windows.Foundation.Metadata
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true)]
public sealed class DeprecatedAttribute : Attribute
{
public DeprecatedAttribute(System.String message, DeprecationType type, System.UInt32 version)
{
}
}
public enum DeprecationType
{
Deprecate = 0,
Remove = 1
}
}";
private const string ExperimentalAttributeSource =
@"using System;
namespace Windows.Foundation.Metadata
{
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate,
AllowMultiple = false)]
public sealed class ExperimentalAttribute : Attribute
{
}
}";
[Fact]
public void TestExperimentalAttribute()
{
var source1 =
@"using Windows.Foundation.Metadata;
namespace N
{
[Experimental] public struct S { }
[Experimental] internal delegate void D<T>();
public class A<T>
{
[Experimental] public class B { }
static void M()
{
new B();
D<int> d = null;
d();
}
}
[Experimental] public enum E { A }
}";
var comp1 = CreateCompilation(new[] { Parse(ExperimentalAttributeSource), Parse(source1) });
comp1.VerifyDiagnostics(
// (11,17): warning CS8305: 'N.A<T>.B' is for evaluation purposes only and is subject to change or removal in future updates.
// new B();
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("N.A<T>.B").WithLocation(11, 17),
// (12,13): warning CS8305: 'N.D<int>' is for evaluation purposes only and is subject to change or removal in future updates.
// D<int> d = null;
Diagnostic(ErrorCode.WRN_Experimental, "D<int>").WithArguments("N.D<int>").WithLocation(12, 13));
var source2 =
@"using N;
using B = N.A<int>.B;
#pragma warning disable 219
class C
{
static void F()
{
object o = new B();
o = default(S);
var e = default(E);
e = E.A;
}
}";
var comp2A = CreateCompilation(source2, new[] { comp1.EmitToImageReference() });
comp2A.VerifyDiagnostics(
// (8,24): warning CS8305: 'N.A<int>.B' is for evaluation purposes only and is subject to change or removal in future updates.
// object o = new B();
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("N.A<int>.B").WithLocation(8, 24),
// (9,21): warning CS8305: 'N.S' is for evaluation purposes only and is subject to change or removal in future updates.
// o = default(S);
Diagnostic(ErrorCode.WRN_Experimental, "S").WithArguments("N.S").WithLocation(9, 21),
// (10,25): warning CS8305: 'N.E' is for evaluation purposes only and is subject to change or removal in future updates.
// var e = default(E);
Diagnostic(ErrorCode.WRN_Experimental, "E").WithArguments("N.E").WithLocation(10, 25),
// (11,13): warning CS8305: 'N.E' is for evaluation purposes only and is subject to change or removal in future updates.
// e = E.A;
Diagnostic(ErrorCode.WRN_Experimental, "E").WithArguments("N.E").WithLocation(11, 13));
var comp2B = CreateCompilation(source2, new[] { new CSharpCompilationReference(comp1) });
comp2B.VerifyDiagnostics(
// (8,24): warning CS8305: 'N.A<int>.B' is for evaluation purposes only and is subject to change or removal in future updates.
// object o = new B();
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("N.A<int>.B").WithLocation(8, 24),
// (9,21): warning CS8305: 'N.S' is for evaluation purposes only and is subject to change or removal in future updates.
// o = default(S);
Diagnostic(ErrorCode.WRN_Experimental, "S").WithArguments("N.S").WithLocation(9, 21),
// (10,25): warning CS8305: 'N.E' is for evaluation purposes only and is subject to change or removal in future updates.
// var e = default(E);
Diagnostic(ErrorCode.WRN_Experimental, "E").WithArguments("N.E").WithLocation(10, 25),
// (11,13): warning CS8305: 'N.E' is for evaluation purposes only and is subject to change or removal in future updates.
// e = E.A;
Diagnostic(ErrorCode.WRN_Experimental, "E").WithArguments("N.E").WithLocation(11, 13));
}
// [Experimental] applied to members even though
// AttributeUsage is types only.
[Fact]
public void TestExperimentalMembers()
{
var source0 =
@".class public Windows.Foundation.Metadata.ExperimentalAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 1C 14 00 00 01 00 54 02 0D 41 6C 6C 6F 77 // ........T..Allow
4D 75 6C 74 69 70 6C 65 00 ) // Multiple.
}
.class public E extends [mscorlib]System.Enum
{
.field public specialname rtspecialname int32 value__
.field public static literal valuetype E A = int32(0x00000000)
.custom instance void Windows.Foundation.Metadata.ExperimentalAttribute::.ctor() = ( 01 00 00 00 )
.field public static literal valuetype E B = int32(0x00000001)
}
.class interface public I
{
.method public abstract virtual instance void F()
{
.custom instance void Windows.Foundation.Metadata.ExperimentalAttribute::.ctor() = ( 01 00 00 00 )
}
}
.class public C implements I
{
.method public virtual final instance void F() { ret }
}";
var ref0 = CompileIL(source0);
var source1 =
@"#pragma warning disable 219
class Program
{
static void Main()
{
E e = default(E);
e = E.A; // warning CS8305: 'E.A' is for evaluation purposes only
e = E.B;
var o = default(C);
o.F();
((I)o).F(); // warning CS8305: 'I.F()' is for evaluation purposes only
}
}";
var comp1 = CreateCompilation(source1, new[] { ref0 });
comp1.VerifyDiagnostics(
// (7,13): warning CS8305: 'E.A' is for evaluation purposes only and is subject to change or removal in future updates.
// e = E.A; // warning CS8305: 'F.A' is for evaluation purposes only
Diagnostic(ErrorCode.WRN_Experimental, "E.A").WithArguments("E.A").WithLocation(7, 13),
// (11,9): warning CS8305: 'I.F()' is for evaluation purposes only and is subject to change or removal in future updates.
// ((I)o).F(); // warning CS8305: 'I.F()' is for evaluation purposes only
Diagnostic(ErrorCode.WRN_Experimental, "((I)o).F()").WithArguments("I.F()").WithLocation(11, 9));
}
[Fact]
public void TestExperimentalTypeWithDeprecatedAndObsoleteMembers()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Experimental]
class A
{
internal void F0() { }
[Deprecated("""", DeprecationType.Deprecate, 0)]
internal void F1() { }
[Deprecated("""", DeprecationType.Remove, 0)]
internal void F2() { }
[Obsolete("""", false)]
internal void F3() { }
[Obsolete("""", true)]
internal void F4() { }
[Experimental]
internal class B { }
}
class C
{
static void F(A a)
{
a.F0();
a.F1();
a.F2();
a.F3();
a.F4();
(new A.B()).ToString();
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(DeprecatedAttributeSource), Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (20,19): warning CS8305: 'A' is for evaluation purposes only and is subject to change or removal in future updates.
// static void F(A a)
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("A").WithLocation(20, 19),
// (23,9): warning CS0618: 'A.F1()' is obsolete: ''
// a.F1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "a.F1()").WithArguments("A.F1()", "").WithLocation(23, 9),
// (24,9): error CS0619: 'A.F2()' is obsolete: ''
// a.F2();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "a.F2()").WithArguments("A.F2()", "").WithLocation(24, 9),
// (25,9): warning CS0618: 'A.F3()' is obsolete: ''
// a.F3();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "a.F3()").WithArguments("A.F3()", "").WithLocation(25, 9),
// (26,9): error CS0619: 'A.F4()' is obsolete: ''
// a.F4();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "a.F4()").WithArguments("A.F4()", "").WithLocation(26, 9),
// (27,14): warning CS8305: 'A' is for evaluation purposes only and is subject to change or removal in future updates.
// (new A.B()).ToString();
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("A").WithLocation(27, 14),
// (27,14): warning CS8305: 'A.B' is for evaluation purposes only and is subject to change or removal in future updates.
// (new A.B()).ToString();
Diagnostic(ErrorCode.WRN_Experimental, "A.B").WithArguments("A.B").WithLocation(27, 14));
}
[Fact]
public void TestDeprecatedLocalFunctions()
{
var source =
@"
using Windows.Foundation.Metadata;
class A
{
void M()
{
local1(); // 1
local2(); // 2
[Deprecated("""", DeprecationType.Deprecate, 0)]
void local1() { }
[Deprecated("""", DeprecationType.Remove, 0)]
void local2() { }
#pragma warning disable 8321 // Unreferenced local function
[Deprecated("""", DeprecationType.Deprecate, 0)]
void local3()
{
// No obsolete warnings expected inside a deprecated local function
local1();
local2();
}
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { DeprecatedAttributeSource, ExperimentalAttributeSource, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,9): warning CS0618: 'local1()' is obsolete: ''
// local1(); // 1
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "local1()").WithArguments("local1()", "").WithLocation(7, 9),
// (8,9): error CS0619: 'local2()' is obsolete: ''
// local2(); // 2
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "local2()").WithArguments("local2()", "").WithLocation(8, 9));
}
// Diagnostics for [Obsolete] members
// are not suppressed in [Experimental] types.
[Fact]
public void TestObsoleteMembersInExperimentalType()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
class A
{
internal void F0() { }
[Deprecated("""", DeprecationType.Deprecate, 0)]
internal void F1() { }
[Deprecated("""", DeprecationType.Remove, 0)]
internal void F2() { }
[Obsolete("""", false)]
internal void F3() { }
[Obsolete("""", true)]
internal void F4() { }
[Experimental]
internal class B { }
}
[Experimental]
class C
{
static void F(A a)
{
a.F0();
a.F1();
a.F2();
a.F3();
a.F4();
(new A.B()).ToString();
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(DeprecatedAttributeSource), Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (23,9): warning CS0618: 'A.F1()' is obsolete: ''
// a.F1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "a.F1()").WithArguments("A.F1()", "").WithLocation(23, 9),
// (24,9): error CS0619: 'A.F2()' is obsolete: ''
// a.F2();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "a.F2()").WithArguments("A.F2()", "").WithLocation(24, 9),
// (25,9): warning CS0618: 'A.F3()' is obsolete: ''
// a.F3();
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "a.F3()").WithArguments("A.F3()", "").WithLocation(25, 9),
// (26,9): error CS0619: 'A.F4()' is obsolete: ''
// a.F4();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "a.F4()").WithArguments("A.F4()", "").WithLocation(26, 9),
// (27,14): warning CS8305: 'A.B' is for evaluation purposes only and is subject to change or removal in future updates.
// (new A.B()).ToString();
Diagnostic(ErrorCode.WRN_Experimental, "A.B").WithArguments("A.B").WithLocation(27, 14));
}
[Fact]
public void TestObsoleteMembersInExperimentalTypeInObsoleteType()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
class A
{
[Obsolete("""", false)]
internal void F() { }
}
[Obsolete("""", false)]
class B
{
[Experimental]
class C
{
static void G(A a)
{
a.F();
}
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(DeprecatedAttributeSource), Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics();
}
// Diagnostics for [Experimental] types
// are not suppressed in [Obsolete] members.
[Fact]
public void TestExperimentalTypeInObsoleteMember()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Experimental] class A { }
[Experimental] class B { }
class C
{
static object FA() => new A();
[Obsolete("""", false)]
static object FB() => new B();
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (7,31): warning CS8305: 'A' is for evaluation purposes only and is subject to change or removal in future updates.
// static object FA() => new A();
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("A"),
// (9,31): warning CS8305: 'B' is for evaluation purposes only and is subject to change or removal in future updates.
// static object FB() => new B();
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("B").WithLocation(9, 31));
}
[Fact]
public void TestExperimentalTypeWithAttributeMarkedObsolete()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Obsolete]
class MyAttribute : Attribute
{
}
[Experimental]
[MyAttribute]
class A
{
}
class B
{
A F() => null;
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (8,2): warning CS0612: 'MyAttribute' is obsolete
// [MyAttribute]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyAttribute").WithArguments("MyAttribute"),
// (14,5): warning CS8305: 'A' is for evaluation purposes only and is subject to change or removal in future updates.
// A F() => null;
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("A").WithLocation(14, 5));
}
[Fact]
public void TestObsoleteTypeWithAttributeMarkedExperimental()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Experimental]
class MyAttribute : Attribute
{
}
[Obsolete]
[MyAttribute]
class A
{
}
class B
{
A F() => null;
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (8,2): warning CS8305: 'MyAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [MyAttribute]
Diagnostic(ErrorCode.WRN_Experimental, "MyAttribute").WithArguments("MyAttribute").WithLocation(8, 2),
// (14,5): warning CS0612: 'A' is obsolete
// A F() => null;
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "A").WithArguments("A").WithLocation(14, 5));
}
[Fact]
public void TestAttributesMarkedExperimentalAndObsolete()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Experimental]
[B]
class AAttribute : Attribute
{
}
[Obsolete]
[A]
class BAttribute : Attribute
{
}
[A]
[B]
class C
{
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (9,2): warning CS8305: 'AAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [A]
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("AAttribute").WithLocation(9, 2),
// (4,2): warning CS0612: 'BAttribute' is obsolete
// [B]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "B").WithArguments("BAttribute").WithLocation(4, 2),
// (13,2): warning CS8305: 'AAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [A]
Diagnostic(ErrorCode.WRN_Experimental, "A").WithArguments("AAttribute").WithLocation(13, 2),
// (14,2): warning CS0612: 'BAttribute' is obsolete
// [B]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "B").WithArguments("BAttribute").WithLocation(14, 2));
}
[Fact]
public void TestAttributesMarkedExperimentalAndObsolete2()
{
var source =
@"using System;
using Windows.Foundation.Metadata;
[Obsolete]
[B]
class AAttribute : Attribute
{
}
[Experimental]
[A]
class BAttribute : Attribute
{
}
[A]
[B]
class C
{
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (9,2): warning CS0612: 'AAttribute' is obsolete
// [A]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "A").WithArguments("AAttribute").WithLocation(9, 2),
// (4,2): warning CS8305: 'BAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [B]
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("BAttribute").WithLocation(4, 2),
// (13,2): warning CS0612: 'AAttribute' is obsolete
// [A]
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "A").WithArguments("AAttribute").WithLocation(13, 2),
// (14,2): warning CS8305: 'BAttribute' is for evaluation purposes only and is subject to change or removal in future updates.
// [B]
Diagnostic(ErrorCode.WRN_Experimental, "B").WithArguments("BAttribute").WithLocation(14, 2));
}
// Combinations of attributes.
[Fact]
public void TestDeprecatedAndExperimentalAndObsoleteAttributes()
{
var source1 =
@"using System;
using Windows.Foundation.Metadata;
[Obsolete(""OA"", false), Deprecated(""DA"", DeprecationType.Deprecate, 0)]public struct SA { }
[Obsolete(""OB"", false), Deprecated(""DB"", DeprecationType.Remove, 0)] public struct SB { }
[Obsolete(""OC"", false), Experimental] public struct SC { }
[Obsolete(""OD"", true), Deprecated(""DC"", DeprecationType.Deprecate, 0)]public struct SD { }
[Obsolete(""OE"", true), Deprecated(""DD"", DeprecationType.Remove, 0)] public struct SE { }
[Obsolete(""OF"", true), Experimental] public struct SF { }
[Deprecated(""DG"", DeprecationType.Deprecate, 0), Obsolete(""OG"", false)] public interface IG { }
[Deprecated(""DH"", DeprecationType.Deprecate, 0), Obsolete(""OH"", true)] public interface IH { }
[Deprecated(""DI"", DeprecationType.Deprecate, 0), Experimental] public interface II { }
[Deprecated(""DJ"", DeprecationType.Remove, 0), Obsolete(""OJ"", false)] public interface IJ { }
[Deprecated(""DK"", DeprecationType.Remove, 0), Obsolete(""OK"", true)] public interface IK { }
[Deprecated(""DL"", DeprecationType.Remove, 0), Experimental] public interface IL { }
[Experimental, Obsolete(""OM"", false)] public enum EM { }
[Experimental, Obsolete(""ON"", true)] public enum EN { }
[Experimental, Deprecated(""DO"", DeprecationType.Deprecate, 0)]public enum EO { }
[Experimental, Deprecated(""DP"", DeprecationType.Remove, 0)] public enum EP { }";
var comp1 = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(DeprecatedAttributeSource), Parse(ExperimentalAttributeSource), Parse(source1) });
comp1.VerifyDiagnostics();
var source2 =
@"class C
{
static void F(object o) { }
static void Main()
{
F(default(SA));
F(default(SB));
F(default(SC));
F(default(SD));
F(default(SE));
F(default(SF));
F(default(IG));
F(default(IH));
F(default(II));
F(default(IJ));
F(default(IK));
F(default(EM));
F(default(EN));
F(default(EO));
F(default(EP));
}
}";
var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, references: new[] { comp1.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (6,19): warning CS0618: 'SA' is obsolete: 'DA'
// F(default(SA));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SA").WithArguments("SA", "DA").WithLocation(6, 19),
// (7,19): error CS0619: 'SB' is obsolete: 'DB'
// F(default(SB));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "SB").WithArguments("SB", "DB").WithLocation(7, 19),
// (8,19): warning CS0618: 'SC' is obsolete: 'OC'
// F(default(SC));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SC").WithArguments("SC", "OC").WithLocation(8, 19),
// (9,19): warning CS0618: 'SD' is obsolete: 'DC'
// F(default(SD));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SD").WithArguments("SD", "DC").WithLocation(9, 19),
// (10,19): error CS0619: 'SE' is obsolete: 'DD'
// F(default(SE));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "SE").WithArguments("SE", "DD").WithLocation(10, 19),
// (11,19): error CS0619: 'SF' is obsolete: 'OF'
// F(default(SF));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "SF").WithArguments("SF", "OF").WithLocation(11, 19),
// (12,19): warning CS0618: 'IG' is obsolete: 'DG'
// F(default(IG));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "IG").WithArguments("IG", "DG").WithLocation(12, 19),
// (13,19): warning CS0618: 'IH' is obsolete: 'DH'
// F(default(IH));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "IH").WithArguments("IH", "DH").WithLocation(13, 19),
// (14,19): warning CS0618: 'II' is obsolete: 'DI'
// F(default(II));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "II").WithArguments("II", "DI").WithLocation(14, 19),
// (15,19): error CS0619: 'IJ' is obsolete: 'DJ'
// F(default(IJ));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "IJ").WithArguments("IJ", "DJ").WithLocation(15, 19),
// (16,19): error CS0619: 'IK' is obsolete: 'DK'
// F(default(IK));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "IK").WithArguments("IK", "DK").WithLocation(16, 19),
// (17,19): warning CS0618: 'EM' is obsolete: 'OM'
// F(default(EM));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "EM").WithArguments("EM", "OM").WithLocation(17, 19),
// (18,19): error CS0619: 'EN' is obsolete: 'ON'
// F(default(EN));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "EN").WithArguments("EN", "ON").WithLocation(18, 19),
// (19,19): warning CS0618: 'EO' is obsolete: 'DO'
// F(default(EO));
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "EO").WithArguments("EO", "DO").WithLocation(19, 19),
// (20,19): error CS0619: 'EP' is obsolete: 'DP'
// F(default(EP));
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "EP").WithArguments("EP", "DP").WithLocation(20, 19));
}
[Fact]
public void TestImportStatements()
{
var source =
@"#pragma warning disable 219
#pragma warning disable 8019
using System;
using Windows.Foundation.Metadata;
using CA = C<A>;
using CB = C<B>;
using CC = C<C>;
using CD = C<D>;
[Obsolete] class A { }
[Obsolete] class B { }
[Experimental] class C { }
[Experimental] class D { }
class C<T> { }
class P
{
static void Main()
{
object o;
o = default(CB);
o = default(CD);
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { Parse(ExperimentalAttributeSource), Parse(source) });
comp.VerifyDiagnostics(
// (19,21): warning CS0612: 'B' is obsolete
// o = default(CB);
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "CB").WithArguments("B").WithLocation(19, 21),
// (20,21): warning CS8305: 'D' is for evaluation purposes only and is subject to change or removal in future updates.
// o = default(CD);
Diagnostic(ErrorCode.WRN_Experimental, "CD").WithArguments("D").WithLocation(20, 21));
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/EditorFeatures/Core.Wpf/RenameTracking/RenameTrackingTagDefinition.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
[Export(typeof(EditorFormatDefinition))]
[Name(RenameTrackingTag.TagId)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
internal class RenameTrackingTagDefinition : MarkerFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RenameTrackingTagDefinition()
{
this.Border = new Pen(Brushes.Black, thickness: 1.0) { DashStyle = new DashStyle(new[] { 0.5, 4.0 }, 1) };
this.DisplayName = EditorFeaturesResources.Rename_Tracking;
this.ZOrder = 1;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
[Export(typeof(EditorFormatDefinition))]
[Name(RenameTrackingTag.TagId)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
internal class RenameTrackingTagDefinition : MarkerFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RenameTrackingTagDefinition()
{
this.Border = new Pen(Brushes.Black, thickness: 1.0) { DashStyle = new DashStyle(new[] { 0.5, 4.0 }, 1) };
this.DisplayName = EditorFeaturesResources.Rename_Tracking;
this.ZOrder = 1;
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.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.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
/// <summary>
/// This is the entry point for foreach-loop lowering. It delegates to
/// RewriteEnumeratorForEachStatement
/// RewriteSingleDimensionalArrayForEachStatement
/// RewriteMultiDimensionalArrayForEachStatement
/// CanRewriteForEachAsFor
/// </summary>
/// <remarks>
/// We are diverging from the C# 4 spec (and Dev10) to follow the C# 5 spec.
/// The iteration variable will be declared *inside* each loop iteration,
/// rather than outside the loop.
/// </remarks>
public override BoundNode VisitForEachStatement(BoundForEachStatement node)
{
// No point in performing this lowering if the node won't be emitted.
if (node.HasErrors)
{
return node;
}
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
TypeSymbol? nodeExpressionType = collectionExpression.Type;
Debug.Assert(nodeExpressionType is { });
if (nodeExpressionType.Kind == SymbolKind.ArrayType)
{
ArrayTypeSymbol arrayType = (ArrayTypeSymbol)nodeExpressionType;
if (arrayType.IsSZArray)
{
return RewriteSingleDimensionalArrayForEachStatement(node);
}
else
{
return RewriteMultiDimensionalArrayForEachStatement(node);
}
}
else if (node.AwaitOpt is null && CanRewriteForEachAsFor(node.Syntax, nodeExpressionType, out var indexerGet, out var lengthGetter))
{
return RewriteForEachStatementAsFor(node, indexerGet, lengthGetter);
}
else
{
return RewriteEnumeratorForEachStatement(node);
}
}
private bool CanRewriteForEachAsFor(SyntaxNode forEachSyntax, TypeSymbol nodeExpressionType, [NotNullWhen(true)] out MethodSymbol? indexerGet, [NotNullWhen(true)] out MethodSymbol? lengthGet)
{
lengthGet = indexerGet = null;
var origDefinition = nodeExpressionType.OriginalDefinition;
if (origDefinition.SpecialType == SpecialType.System_String)
{
lengthGet = UnsafeGetSpecialTypeMethod(forEachSyntax, SpecialMember.System_String__Length);
indexerGet = UnsafeGetSpecialTypeMethod(forEachSyntax, SpecialMember.System_String__Chars);
}
else if ((object)origDefinition == this._compilation.GetWellKnownType(WellKnownType.System_Span_T))
{
var spanType = (NamedTypeSymbol)nodeExpressionType;
lengthGet = (MethodSymbol?)_factory.WellKnownMember(WellKnownMember.System_Span_T__get_Length, isOptional: true)?.SymbolAsMember(spanType);
indexerGet = (MethodSymbol?)_factory.WellKnownMember(WellKnownMember.System_Span_T__get_Item, isOptional: true)?.SymbolAsMember(spanType);
}
else if ((object)origDefinition == this._compilation.GetWellKnownType(WellKnownType.System_ReadOnlySpan_T))
{
var spanType = (NamedTypeSymbol)nodeExpressionType;
lengthGet = (MethodSymbol?)_factory.WellKnownMember(WellKnownMember.System_ReadOnlySpan_T__get_Length, isOptional: true)?.SymbolAsMember(spanType);
indexerGet = (MethodSymbol?)_factory.WellKnownMember(WellKnownMember.System_ReadOnlySpan_T__get_Item, isOptional: true)?.SymbolAsMember(spanType);
}
return lengthGet is { } && indexerGet is { };
}
/// <summary>
/// Lower a foreach loop that will enumerate a collection using an enumerator.
///
/// <![CDATA[
/// E e = ((C)(x)).GetEnumerator() OR ((C)(x)).GetAsyncEnumerator()
/// try {
/// while (e.MoveNext()) OR while (await e.MoveNextAsync())
/// {
/// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
/// // body
/// }
/// }
/// finally {
/// // clean up e
/// }
/// ]]>
/// </summary>
private BoundStatement RewriteEnumeratorForEachStatement(BoundForEachStatement node)
{
var forEachSyntax = (CommonForEachStatementSyntax)node.Syntax;
bool isAsync = node.AwaitOpt != null;
ForEachEnumeratorInfo? enumeratorInfo = node.EnumeratorInfoOpt;
Debug.Assert(enumeratorInfo != null);
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
BoundExpression rewrittenExpression = VisitExpression(collectionExpression);
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
MethodArgumentInfo getEnumeratorInfo = enumeratorInfo.GetEnumeratorInfo;
TypeSymbol enumeratorType = getEnumeratorInfo.Method.ReturnType;
TypeSymbol elementType = enumeratorInfo.ElementType;
// E e
LocalSymbol enumeratorVar = _factory.SynthesizedLocal(enumeratorType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachEnumerator);
// Reference to e.
BoundLocal boundEnumeratorVar = MakeBoundLocal(forEachSyntax, enumeratorVar, enumeratorType);
var receiver = ConvertReceiverForInvocation(forEachSyntax, rewrittenExpression, getEnumeratorInfo.Method, enumeratorInfo.CollectionConversion, enumeratorInfo.CollectionType);
// If the GetEnumerator call is an extension method, then the first argument is the receiver. We want to replace
// the first argument with our converted receiver and pass null as the receiver instead.
if (getEnumeratorInfo.Method.IsExtensionMethod)
{
var builder = ArrayBuilder<BoundExpression>.GetInstance(getEnumeratorInfo.Arguments.Length);
builder.Add(receiver);
builder.AddRange(getEnumeratorInfo.Arguments, 1, getEnumeratorInfo.Arguments.Length - 1);
getEnumeratorInfo = getEnumeratorInfo with { Arguments = builder.ToImmutableAndFree() };
receiver = null;
}
// ((C)(x)).GetEnumerator(); OR (x).GetEnumerator(); OR async variants (which fill-in arguments for optional parameters)
BoundExpression enumeratorVarInitValue = SynthesizeCall(getEnumeratorInfo, forEachSyntax, receiver,
allowExtensionAndOptionalParameters: isAsync || getEnumeratorInfo.Method.IsExtensionMethod,
// C# 8 shipped allowing the CancellationToken of `IAsyncEnumerable.GetAsyncEnumerator` to be non-optional.
// https://github.com/dotnet/roslyn/issues/50182 tracks making this an error and breaking the scenario.
assertParametersAreOptional: false);
// E e = ((C)(x)).GetEnumerator();
BoundStatement enumeratorVarDecl = MakeLocalDeclaration(forEachSyntax, enumeratorVar, enumeratorVarInitValue);
InstrumentForEachStatementCollectionVarDeclaration(node, ref enumeratorVarDecl);
// (V)(T)e.Current
BoundExpression iterationVarAssignValue = MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: BoundCall.Synthesized(
syntax: forEachSyntax,
receiverOpt: boundEnumeratorVar,
method: enumeratorInfo.CurrentPropertyGetter),
conversion: enumeratorInfo.CurrentConversion,
rewrittenType: elementType,
@checked: node.Checked),
conversion: node.ElementConversion,
rewrittenType: node.IterationVariableType.Type,
@checked: node.Checked);
// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
ImmutableArray<LocalSymbol> iterationVariables = node.IterationVariables;
BoundStatement iterationVarDecl = LocalOrDeconstructionDeclaration(node, iterationVariables, iterationVarAssignValue);
InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVarDecl);
// while (e.MoveNext()) -OR- while (await e.MoveNextAsync())
// {
// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
// /* node.Body */
// }
var rewrittenBodyBlock = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVarDecl, rewrittenBody, forEachSyntax);
BoundExpression rewrittenCondition = SynthesizeCall(
methodArgumentInfo: enumeratorInfo.MoveNextInfo,
syntax: forEachSyntax,
receiver: boundEnumeratorVar,
allowExtensionAndOptionalParameters: isAsync);
if (isAsync)
{
Debug.Assert(node.AwaitOpt is { GetResult: { } });
rewrittenCondition = RewriteAwaitExpression(forEachSyntax, rewrittenCondition, node.AwaitOpt, node.AwaitOpt.GetResult.ReturnType, used: true);
}
BoundStatement whileLoop = RewriteWhileStatement(
loop: node,
rewrittenCondition,
rewrittenBody: rewrittenBodyBlock,
breakLabel: node.BreakLabel,
continueLabel: node.ContinueLabel,
hasErrors: false);
BoundStatement result;
if (enumeratorInfo.NeedsDisposal)
{
BoundStatement tryFinally = WrapWithTryFinallyDispose(forEachSyntax, enumeratorInfo, enumeratorType, boundEnumeratorVar, whileLoop);
// E e = ((C)(x)).GetEnumerator();
// try {
// /* as above */
result = new BoundBlock(
syntax: forEachSyntax,
locals: ImmutableArray.Create(enumeratorVar),
statements: ImmutableArray.Create<BoundStatement>(enumeratorVarDecl, tryFinally));
}
else
{
// E e = ((C)(x)).GetEnumerator();
// while (e.MoveNext()) {
// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
// /* loop body */
// }
result = new BoundBlock(
syntax: forEachSyntax,
locals: ImmutableArray.Create(enumeratorVar),
statements: ImmutableArray.Create<BoundStatement>(enumeratorVarDecl, whileLoop));
}
InstrumentForEachStatement(node, ref result);
return result;
}
private bool TryGetDisposeMethod(CommonForEachStatementSyntax forEachSyntax, ForEachEnumeratorInfo enumeratorInfo, out MethodSymbol disposeMethod)
{
if (enumeratorInfo.IsAsync)
{
disposeMethod = (MethodSymbol)Binder.GetWellKnownTypeMember(_compilation, WellKnownMember.System_IAsyncDisposable__DisposeAsync, _diagnostics, syntax: forEachSyntax);
return (object)disposeMethod != null;
}
return Binder.TryGetSpecialTypeMember(_compilation, SpecialMember.System_IDisposable__Dispose, forEachSyntax, _diagnostics, out disposeMethod);
}
/// <summary>
/// There are three possible cases where we need disposal:
/// - pattern-based disposal (we have a Dispose/DisposeAsync method)
/// - interface-based disposal (the enumerator type converts to IDisposable/IAsyncDisposable)
/// - we need to do a runtime check for IDisposable
/// </summary>
private BoundStatement WrapWithTryFinallyDispose(
CommonForEachStatementSyntax forEachSyntax,
ForEachEnumeratorInfo enumeratorInfo,
TypeSymbol enumeratorType,
BoundLocal boundEnumeratorVar,
BoundStatement rewrittenBody)
{
Debug.Assert(enumeratorInfo.NeedsDisposal);
NamedTypeSymbol? idisposableTypeSymbol = null;
bool isImplicit = false;
MethodSymbol? disposeMethod = enumeratorInfo.PatternDisposeInfo?.Method; // pattern-based
if (disposeMethod is null)
{
TryGetDisposeMethod(forEachSyntax, enumeratorInfo, out disposeMethod); // interface-based
// This is a temporary workaround for https://github.com/dotnet/roslyn/issues/39948
if (disposeMethod is null)
{
return rewrittenBody;
}
idisposableTypeSymbol = disposeMethod.ContainingType;
Debug.Assert(_factory.CurrentFunction is { });
var conversions = new TypeConversions(_factory.CurrentFunction.ContainingAssembly.CorLibrary);
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo();
isImplicit = conversions.ClassifyImplicitConversionFromType(enumeratorType, idisposableTypeSymbol, ref useSiteInfo).IsImplicit;
_diagnostics.Add(forEachSyntax, useSiteInfo);
}
Binder.ReportDiagnosticsIfObsolete(_diagnostics, disposeMethod, forEachSyntax,
hasBaseReceiver: false,
containingMember: _factory.CurrentFunction,
containingType: _factory.CurrentType,
location: enumeratorInfo.Location);
BoundBlock finallyBlockOpt;
if (isImplicit || !(enumeratorInfo.PatternDisposeInfo is null))
{
Conversion receiverConversion = enumeratorType.IsStructType() ?
Conversion.Boxing :
Conversion.ImplicitReference;
BoundExpression receiver;
BoundExpression disposeCall;
var disposeInfo = enumeratorInfo.PatternDisposeInfo;
if (disposeInfo is null)
{
Debug.Assert(idisposableTypeSymbol is { });
disposeInfo = MethodArgumentInfo.CreateParameterlessMethod(disposeMethod);
receiver = ConvertReceiverForInvocation(forEachSyntax, boundEnumeratorVar, disposeMethod, receiverConversion, idisposableTypeSymbol);
}
else
{
receiver = boundEnumeratorVar;
}
// ((IDisposable)e).Dispose() or e.Dispose() or await ((IAsyncDisposable)e).DisposeAsync() or await e.DisposeAsync()
disposeCall = MakeCallWithNoExplicitArgument(disposeInfo, forEachSyntax, receiver);
BoundStatement disposeCallStatement;
var disposeAwaitableInfoOpt = enumeratorInfo.DisposeAwaitableInfo;
if (disposeAwaitableInfoOpt != null)
{
// await /* disposeCall */
disposeCallStatement = WrapWithAwait(forEachSyntax, disposeCall, disposeAwaitableInfoOpt);
_sawAwaitInExceptionHandler = true;
}
else
{
// ((IDisposable)e).Dispose(); or e.Dispose();
disposeCallStatement = new BoundExpressionStatement(forEachSyntax, disposeCall);
}
BoundStatement alwaysOrMaybeDisposeStmt;
if (enumeratorType.IsValueType)
{
// No way for the struct to be nullable and disposable.
Debug.Assert(enumeratorType.OriginalDefinition.SpecialType != SpecialType.System_Nullable_T);
// For non-nullable structs, no null check is required.
alwaysOrMaybeDisposeStmt = disposeCallStatement;
}
else
{
// NB: cast to object missing from spec. Needed to ignore user-defined operators and box type parameters.
// if ((object)e != null) ((IDisposable)e).Dispose();
alwaysOrMaybeDisposeStmt = RewriteIfStatement(
syntax: forEachSyntax,
rewrittenCondition: new BoundBinaryOperator(forEachSyntax,
operatorKind: BinaryOperatorKind.NotEqual,
left: MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: boundEnumeratorVar,
conversion: enumeratorInfo.EnumeratorConversion,
rewrittenType: _compilation.GetSpecialType(SpecialType.System_Object),
@checked: false),
right: MakeLiteral(forEachSyntax,
constantValue: ConstantValue.Null,
type: null),
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: _compilation.GetSpecialType(SpecialType.System_Boolean)),
rewrittenConsequence: disposeCallStatement,
rewrittenAlternativeOpt: null,
hasErrors: false);
}
finallyBlockOpt = new BoundBlock(forEachSyntax,
locals: ImmutableArray<LocalSymbol>.Empty,
statements: ImmutableArray.Create(alwaysOrMaybeDisposeStmt));
}
else
{
// If we couldn't find either pattern-based or interface-based disposal, and the enumerator type isn't sealed,
// and the loop isn't async, then we include a runtime check.
Debug.Assert(!enumeratorType.IsSealed);
Debug.Assert(!enumeratorInfo.IsAsync);
Debug.Assert(idisposableTypeSymbol is { });
Debug.Assert(disposeMethod is { });
// IDisposable d
LocalSymbol disposableVar = _factory.SynthesizedLocal(idisposableTypeSymbol);
// Reference to d.
BoundLocal boundDisposableVar = MakeBoundLocal(forEachSyntax, disposableVar, idisposableTypeSymbol);
BoundTypeExpression boundIDisposableTypeExpr = new BoundTypeExpression(forEachSyntax,
aliasOpt: null,
type: idisposableTypeSymbol);
// e as IDisposable
BoundExpression disposableVarInitValue = new BoundAsOperator(forEachSyntax,
operand: boundEnumeratorVar,
targetType: boundIDisposableTypeExpr,
conversion: Conversion.ExplicitReference, // Explicit so the emitter won't optimize it away.
type: idisposableTypeSymbol);
// IDisposable d = e as IDisposable;
BoundStatement disposableVarDecl = MakeLocalDeclaration(forEachSyntax, disposableVar, disposableVarInitValue);
// d.Dispose()
BoundExpression disposeCall = BoundCall.Synthesized(syntax: forEachSyntax, receiverOpt: boundDisposableVar, method: disposeMethod);
BoundStatement disposeCallStatement = new BoundExpressionStatement(forEachSyntax, expression: disposeCall);
// if (d != null) d.Dispose();
BoundStatement ifStmt = RewriteIfStatement(
syntax: forEachSyntax,
rewrittenCondition: new BoundBinaryOperator(forEachSyntax,
operatorKind: BinaryOperatorKind.NotEqual, // reference equality
left: boundDisposableVar,
right: MakeLiteral(forEachSyntax, constantValue: ConstantValue.Null, type: null),
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: _compilation.GetSpecialType(SpecialType.System_Boolean)),
rewrittenConsequence: disposeCallStatement,
rewrittenAlternativeOpt: null,
hasErrors: false);
// IDisposable d = e as IDisposable;
// if (d != null) d.Dispose();
finallyBlockOpt = new BoundBlock(forEachSyntax,
locals: ImmutableArray.Create(disposableVar),
statements: ImmutableArray.Create(disposableVarDecl, ifStmt));
}
// try {
// while (e.MoveNext()) {
// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
// /* loop body */
// }
// }
// finally {
// /* dispose of e */
// }
BoundStatement tryFinally = new BoundTryStatement(forEachSyntax,
tryBlock: new BoundBlock(forEachSyntax,
locals: ImmutableArray<LocalSymbol>.Empty,
statements: ImmutableArray.Create<BoundStatement>(rewrittenBody)),
catchBlocks: ImmutableArray<BoundCatchBlock>.Empty,
finallyBlockOpt: finallyBlockOpt);
return tryFinally;
}
/// <summary>
/// Produce:
/// await /* disposeCall */;
/// </summary>
private BoundStatement WrapWithAwait(CommonForEachStatementSyntax forEachSyntax, BoundExpression disposeCall, BoundAwaitableInfo disposeAwaitableInfoOpt)
{
TypeSymbol awaitExpressionType = disposeAwaitableInfoOpt.GetResult?.ReturnType ?? _compilation.DynamicType;
var awaitExpr = RewriteAwaitExpression(forEachSyntax, disposeCall, disposeAwaitableInfoOpt, awaitExpressionType, used: false);
return new BoundExpressionStatement(forEachSyntax, awaitExpr);
}
/// <summary>
/// Optionally apply a conversion to the receiver.
///
/// If the receiver is of struct type and the method is an interface method, then skip the conversion.
/// When we call the interface method directly - the code generator will detect it and generate a
/// constrained virtual call.
/// </summary>
/// <param name="syntax">A syntax node to attach to the synthesized bound node.</param>
/// <param name="receiver">Receiver of method call.</param>
/// <param name="method">Method to invoke.</param>
/// <param name="receiverConversion">Conversion to be applied to the receiver if not calling an interface method on a struct.</param>
/// <param name="convertedReceiverType">Type of the receiver after applying the conversion.</param>
private BoundExpression ConvertReceiverForInvocation(CSharpSyntaxNode syntax, BoundExpression receiver, MethodSymbol method, Conversion receiverConversion, TypeSymbol convertedReceiverType)
{
Debug.Assert(receiver.Type is { });
if (!receiver.Type.IsReferenceType && method.ContainingType.IsInterface)
{
Debug.Assert(receiverConversion.IsImplicit && !receiverConversion.IsUserDefined);
// NOTE: The spec says that disposing of a struct enumerator won't cause any
// unnecessary boxing to occur. However, Dev10 extends this improvement to the
// GetEnumerator call as well.
// We're going to let the emitter take care of avoiding the extra boxing.
// When it sees an interface call to a struct, it will generate a constrained
// virtual call, which will skip boxing, if possible.
// CONSIDER: In cases where the struct implicitly implements the interface method
// (i.e. with a public method), we could save a few bytes of IL by creating a
// BoundCall to the struct method rather than the interface method (so that the
// emitter wouldn't need to create a constrained virtual call). It is not clear
// what effect this would have on back compat.
// NOTE: This call does not correspond to anything that can be written in C# source.
// We're invoking the interface method directly on the struct (which may have a private
// explicit implementation). The code generator knows how to handle it though.
// receiver.InterfaceMethod()
}
else
{
// ((Interface)receiver).InterfaceMethod()
Debug.Assert(!receiverConversion.IsNumeric);
receiver = MakeConversionNode(
syntax: syntax,
rewrittenOperand: receiver,
conversion: receiverConversion,
@checked: false,
rewrittenType: convertedReceiverType);
}
return receiver;
}
private BoundExpression SynthesizeCall(MethodArgumentInfo methodArgumentInfo, CSharpSyntaxNode syntax, BoundExpression? receiver, bool allowExtensionAndOptionalParameters, bool assertParametersAreOptional = true)
{
if (allowExtensionAndOptionalParameters)
{
// Generate a call with zero explicit arguments, but with implicit arguments for optional and params parameters.
return MakeCallWithNoExplicitArgument(methodArgumentInfo, syntax, receiver, assertParametersAreOptional);
}
// Generate a call with literally zero arguments
Debug.Assert(methodArgumentInfo.Arguments.IsEmpty);
return BoundCall.Synthesized(syntax, receiver, methodArgumentInfo.Method, arguments: ImmutableArray<BoundExpression>.Empty);
}
/// <summary>
/// Lower a foreach loop that will enumerate a collection via indexing.
///
/// <![CDATA[
///
/// Indexable a = x;
/// for (int p = 0; p < a.Length; p = p + 1) {
/// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
/// // body
/// }
///
/// ]]>
/// </summary>
/// <remarks>
/// NOTE: We're assuming that sequence points have already been generated.
/// Otherwise, lowering to for-loops would generated spurious ones.
/// </remarks>
private BoundStatement RewriteForEachStatementAsFor(BoundForEachStatement node, MethodSymbol indexerGet, MethodSymbol lengthGet)
{
var forEachSyntax = (CommonForEachStatementSyntax)node.Syntax;
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
NamedTypeSymbol? collectionType = (NamedTypeSymbol?)collectionExpression.Type;
Debug.Assert(collectionType is { });
TypeSymbol intType = _compilation.GetSpecialType(SpecialType.System_Int32);
TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean);
BoundExpression rewrittenExpression = VisitExpression(collectionExpression);
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
// Collection a
LocalSymbol collectionTemp = _factory.SynthesizedLocal(collectionType, forEachSyntax, kind: SynthesizedLocalKind.ForEachArray);
// Collection a = /*node.Expression*/;
BoundStatement arrayVarDecl = MakeLocalDeclaration(forEachSyntax, collectionTemp, rewrittenExpression);
InstrumentForEachStatementCollectionVarDeclaration(node, ref arrayVarDecl);
// Reference to a.
BoundLocal boundArrayVar = MakeBoundLocal(forEachSyntax, collectionTemp, collectionType);
// int p
LocalSymbol positionVar = _factory.SynthesizedLocal(intType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArrayIndex);
// Reference to p.
BoundLocal boundPositionVar = MakeBoundLocal(forEachSyntax, positionVar, intType);
// int p = 0;
BoundStatement positionVarDecl = MakeLocalDeclaration(forEachSyntax, positionVar,
MakeLiteral(forEachSyntax, ConstantValue.Default(SpecialType.System_Int32), intType));
// (V)a[p]
BoundExpression iterationVarInitValue = MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: BoundCall.Synthesized(
syntax: forEachSyntax,
receiverOpt: boundArrayVar,
indexerGet,
boundPositionVar),
conversion: node.ElementConversion,
rewrittenType: node.IterationVariableType.Type,
@checked: node.Checked);
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
ImmutableArray<LocalSymbol> iterationVariables = node.IterationVariables;
BoundStatement iterationVariableDecl = LocalOrDeconstructionDeclaration(node, iterationVariables, iterationVarInitValue);
InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVariableDecl);
BoundStatement initializer = new BoundStatementList(forEachSyntax,
statements: ImmutableArray.Create<BoundStatement>(arrayVarDecl, positionVarDecl));
// a.Length
BoundExpression arrayLength = BoundCall.Synthesized(
syntax: forEachSyntax,
receiverOpt: boundArrayVar,
lengthGet);
// p < a.Length
BoundExpression exitCondition = new BoundBinaryOperator(
syntax: forEachSyntax,
operatorKind: BinaryOperatorKind.IntLessThan,
left: boundPositionVar,
right: arrayLength,
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: boolType);
// p = p + 1;
BoundStatement positionIncrement = MakePositionIncrement(forEachSyntax, boundPositionVar, intType);
// {
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
// /*node.Body*/
// }
BoundStatement loopBody = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVariableDecl, rewrittenBody, forEachSyntax);
// for (Collection a = /*node.Expression*/, int p = 0; p < a.Length; p = p + 1) {
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
// /*node.Body*/
// }
BoundStatement result = RewriteForStatementWithoutInnerLocals(
original: node,
outerLocals: ImmutableArray.Create<LocalSymbol>(collectionTemp, positionVar),
rewrittenInitializer: initializer,
rewrittenCondition: exitCondition,
rewrittenIncrement: positionIncrement,
rewrittenBody: loopBody,
breakLabel: node.BreakLabel,
continueLabel: node.ContinueLabel,
hasErrors: node.HasErrors);
InstrumentForEachStatement(node, ref result);
return result;
}
/// <summary>
/// Takes the expression for the current value of the iteration variable and either
/// (1) assigns it into a local, or
/// (2) deconstructs it into multiple locals (if there is a deconstruct step).
///
/// Produces <c>V v = /* expression */</c> or <c>(D1 d1, ...) = /* expression */</c>.
/// </summary>
private BoundStatement LocalOrDeconstructionDeclaration(
BoundForEachStatement forEachBound,
ImmutableArray<LocalSymbol> iterationVariables,
BoundExpression iterationVarValue)
{
var forEachSyntax = (CommonForEachStatementSyntax)forEachBound.Syntax;
BoundStatement iterationVarDecl;
BoundForEachDeconstructStep? deconstruction = forEachBound.DeconstructionOpt;
if (deconstruction == null)
{
// V v = /* expression */
Debug.Assert(iterationVariables.Length == 1);
iterationVarDecl = MakeLocalDeclaration(forEachSyntax, iterationVariables[0], iterationVarValue);
}
else
{
// (D1 d1, ...) = /* expression */
var assignment = deconstruction.DeconstructionAssignment;
AddPlaceholderReplacement(deconstruction.TargetPlaceholder, iterationVarValue);
BoundExpression loweredAssignment = VisitExpression(assignment);
iterationVarDecl = new BoundExpressionStatement(assignment.Syntax, loweredAssignment);
RemovePlaceholderReplacement(deconstruction.TargetPlaceholder);
}
return iterationVarDecl;
}
private static BoundBlock CreateBlockDeclaringIterationVariables(
ImmutableArray<LocalSymbol> iterationVariables,
BoundStatement iteratorVariableInitialization,
BoundStatement rewrittenBody,
CommonForEachStatementSyntax forEachSyntax)
{
// The scope of the iteration variable is the embedded statement syntax.
// However consider the following foreach statement:
//
// foreach (int x in ...) { int y = ...; F(() => x); F(() => y));
//
// We currently generate 2 closures. One containing variable x, the other variable y.
// The EnC source mapping infrastructure requires each closure within a method body
// to have a unique syntax offset. Hence we associate the bound block declaring the
// iteration variable with the foreach statement, not the embedded statement.
return new BoundBlock(
forEachSyntax,
locals: iterationVariables,
statements: ImmutableArray.Create(iteratorVariableInitialization, rewrittenBody));
}
private static BoundBlock CreateBlockDeclaringIterationVariables(
ImmutableArray<LocalSymbol> iterationVariables,
BoundStatement iteratorVariableInitialization,
BoundStatement checkAndBreak,
BoundStatement rewrittenBody,
LabelSymbol continueLabel,
CommonForEachStatementSyntax forEachSyntax)
{
// The scope of the iteration variable is the embedded statement syntax.
// However consider the following foreach statement:
//
// await foreach (int x in ...) { int y = ...; F(() => x); F(() => y));
//
// We currently generate 2 closures. One containing variable x, the other variable y.
// The EnC source mapping infrastructure requires each closure within a method body
// to have a unique syntax offset. Hence we associate the bound block declaring the
// iteration variable with the foreach statement, not the embedded statement.
return new BoundBlock(
forEachSyntax,
locals: iterationVariables,
statements: ImmutableArray.Create(
iteratorVariableInitialization,
checkAndBreak,
rewrittenBody,
new BoundLabelStatement(forEachSyntax, continueLabel)));
}
/// <summary>
/// Lower a foreach loop that will enumerate a single-dimensional array.
///
/// A[] a = x;
/// for (int p = 0; p < a.Length; p = p + 1) {
/// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
/// // body
/// }
/// </summary>
/// <remarks>
/// We will follow Dev10 in diverging from the C# 4 spec by ignoring Array's
/// implementation of IEnumerable and just indexing into its elements.
///
/// NOTE: We're assuming that sequence points have already been generated.
/// Otherwise, lowering to for-loops would generated spurious ones.
/// </remarks>
private BoundStatement RewriteSingleDimensionalArrayForEachStatement(BoundForEachStatement node)
{
var forEachSyntax = (CommonForEachStatementSyntax)node.Syntax;
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
Debug.Assert(collectionExpression.Type is { TypeKind: TypeKind.Array });
ArrayTypeSymbol arrayType = (ArrayTypeSymbol)collectionExpression.Type;
Debug.Assert(arrayType is { IsSZArray: true });
TypeSymbol intType = _compilation.GetSpecialType(SpecialType.System_Int32);
TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean);
BoundExpression rewrittenExpression = VisitExpression(collectionExpression);
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
// A[] a
LocalSymbol arrayVar = _factory.SynthesizedLocal(arrayType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArray);
// A[] a = /*node.Expression*/;
BoundStatement arrayVarDecl = MakeLocalDeclaration(forEachSyntax, arrayVar, rewrittenExpression);
InstrumentForEachStatementCollectionVarDeclaration(node, ref arrayVarDecl);
// Reference to a.
BoundLocal boundArrayVar = MakeBoundLocal(forEachSyntax, arrayVar, arrayType);
// int p
LocalSymbol positionVar = _factory.SynthesizedLocal(intType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArrayIndex);
// Reference to p.
BoundLocal boundPositionVar = MakeBoundLocal(forEachSyntax, positionVar, intType);
// int p = 0;
BoundStatement positionVarDecl = MakeLocalDeclaration(forEachSyntax, positionVar,
MakeLiteral(forEachSyntax, ConstantValue.Default(SpecialType.System_Int32), intType));
// (V)a[p]
BoundExpression iterationVarInitValue = MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: new BoundArrayAccess(
syntax: forEachSyntax,
expression: boundArrayVar,
indices: ImmutableArray.Create<BoundExpression>(boundPositionVar),
type: arrayType.ElementType),
conversion: node.ElementConversion,
rewrittenType: node.IterationVariableType.Type,
@checked: node.Checked);
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
ImmutableArray<LocalSymbol> iterationVariables = node.IterationVariables;
BoundStatement iterationVariableDecl = LocalOrDeconstructionDeclaration(node, iterationVariables, iterationVarInitValue);
InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVariableDecl);
BoundStatement initializer = new BoundStatementList(forEachSyntax,
statements: ImmutableArray.Create<BoundStatement>(arrayVarDecl, positionVarDecl));
// a.Length
BoundExpression arrayLength = new BoundArrayLength(
syntax: forEachSyntax,
expression: boundArrayVar,
type: intType);
// p < a.Length
BoundExpression exitCondition = new BoundBinaryOperator(
syntax: forEachSyntax,
operatorKind: BinaryOperatorKind.IntLessThan,
left: boundPositionVar,
right: arrayLength,
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: boolType);
// p = p + 1;
BoundStatement positionIncrement = MakePositionIncrement(forEachSyntax, boundPositionVar, intType);
// {
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
// /*node.Body*/
// }
BoundStatement loopBody = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVariableDecl, rewrittenBody, forEachSyntax);
// for (A[] a = /*node.Expression*/, int p = 0; p < a.Length; p = p + 1) {
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
// /*node.Body*/
// }
BoundStatement result = RewriteForStatementWithoutInnerLocals(
original: node,
outerLocals: ImmutableArray.Create<LocalSymbol>(arrayVar, positionVar),
rewrittenInitializer: initializer,
rewrittenCondition: exitCondition,
rewrittenIncrement: positionIncrement,
rewrittenBody: loopBody,
breakLabel: node.BreakLabel,
continueLabel: node.ContinueLabel,
hasErrors: node.HasErrors);
InstrumentForEachStatement(node, ref result);
return result;
}
/// <summary>
/// Lower a foreach loop that will enumerate a multi-dimensional array.
///
/// A[...] a = x;
/// int q_0 = a.GetUpperBound(0), q_1 = a.GetUpperBound(1), ...;
/// for (int p_0 = a.GetLowerBound(0); p_0 <= q_0; p_0 = p_0 + 1)
/// for (int p_1 = a.GetLowerBound(1); p_1 <= q_1; p_1 = p_1 + 1)
/// ...
/// {
/// V v = (V)a[p_0, p_1, ...]; /* OR */ (D1 d1, ...) = (V)a[p_0, p_1, ...];
/// /* body */
/// }
/// </summary>
/// <remarks>
/// We will follow Dev10 in diverging from the C# 4 spec by ignoring Array's
/// implementation of IEnumerable and just indexing into its elements.
///
/// NOTE: We're assuming that sequence points have already been generated.
/// Otherwise, lowering to nested for-loops would generated spurious ones.
/// </remarks>
private BoundStatement RewriteMultiDimensionalArrayForEachStatement(BoundForEachStatement node)
{
var forEachSyntax = (CommonForEachStatementSyntax)node.Syntax;
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
Debug.Assert(collectionExpression.Type is { TypeKind: TypeKind.Array });
ArrayTypeSymbol arrayType = (ArrayTypeSymbol)collectionExpression.Type;
int rank = arrayType.Rank;
Debug.Assert(!arrayType.IsSZArray);
TypeSymbol intType = _compilation.GetSpecialType(SpecialType.System_Int32);
TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean);
// Values we'll use every iteration
MethodSymbol getLowerBoundMethod = UnsafeGetSpecialTypeMethod(forEachSyntax, SpecialMember.System_Array__GetLowerBound);
MethodSymbol getUpperBoundMethod = UnsafeGetSpecialTypeMethod(forEachSyntax, SpecialMember.System_Array__GetUpperBound);
BoundExpression rewrittenExpression = VisitExpression(collectionExpression);
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
// A[...] a
LocalSymbol arrayVar = _factory.SynthesizedLocal(arrayType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArray);
BoundLocal boundArrayVar = MakeBoundLocal(forEachSyntax, arrayVar, arrayType);
// A[...] a = /*node.Expression*/;
BoundStatement arrayVarDecl = MakeLocalDeclaration(forEachSyntax, arrayVar, rewrittenExpression);
InstrumentForEachStatementCollectionVarDeclaration(node, ref arrayVarDecl);
// NOTE: dev10 initializes all of the upper bound temps before entering the loop (as opposed to
// initializing each one at the corresponding level of nesting). Doing it at the same time as
// the lower bound would make this code a bit simpler, but it would make it harder to compare
// the roslyn and dev10 IL.
// int q_0, q_1, ...
LocalSymbol[] upperVar = new LocalSymbol[rank];
BoundLocal[] boundUpperVar = new BoundLocal[rank];
BoundStatement[] upperVarDecl = new BoundStatement[rank];
for (int dimension = 0; dimension < rank; dimension++)
{
// int q_dimension
upperVar[dimension] = _factory.SynthesizedLocal(intType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArrayLimit);
boundUpperVar[dimension] = MakeBoundLocal(forEachSyntax, upperVar[dimension], intType);
ImmutableArray<BoundExpression> dimensionArgument = ImmutableArray.Create(
MakeLiteral(forEachSyntax,
constantValue: ConstantValue.Create(dimension, ConstantValueTypeDiscriminator.Int32),
type: intType));
// a.GetUpperBound(dimension)
BoundExpression currentDimensionUpperBound = BoundCall.Synthesized(forEachSyntax, boundArrayVar, getUpperBoundMethod, dimensionArgument);
// int q_dimension = a.GetUpperBound(dimension);
upperVarDecl[dimension] = MakeLocalDeclaration(forEachSyntax, upperVar[dimension], currentDimensionUpperBound);
}
// int p_0, p_1, ...
LocalSymbol[] positionVar = new LocalSymbol[rank];
BoundLocal[] boundPositionVar = new BoundLocal[rank];
for (int dimension = 0; dimension < rank; dimension++)
{
positionVar[dimension] = _factory.SynthesizedLocal(intType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArrayIndex);
boundPositionVar[dimension] = MakeBoundLocal(forEachSyntax, positionVar[dimension], intType);
}
// (V)a[p_0, p_1, ...]
BoundExpression iterationVarInitValue = MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: new BoundArrayAccess(forEachSyntax,
expression: boundArrayVar,
indices: ImmutableArray.Create((BoundExpression[])boundPositionVar),
type: arrayType.ElementType),
conversion: node.ElementConversion,
rewrittenType: node.IterationVariableType.Type,
@checked: node.Checked);
// V v = (V)a[p_0, p_1, ...]; /* OR */ (D1 d1, ...) = (V)a[p_0, p_1, ...];
ImmutableArray<LocalSymbol> iterationVariables = node.IterationVariables;
BoundStatement iterationVarDecl = LocalOrDeconstructionDeclaration(node, iterationVariables, iterationVarInitValue);
InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVarDecl);
// {
// V v = (V)a[p_0, p_1, ...]; /* OR */ (D1 d1, ...) = (V)a[p_0, p_1, ...];
// /* node.Body */
// }
BoundStatement innermostLoopBody = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVarDecl, rewrittenBody, forEachSyntax);
// work from most-nested to least-nested
// for (int p_0 = a.GetLowerBound(0); p_0 <= q_0; p_0 = p_0 + 1)
// for (int p_1 = a.GetLowerBound(0); p_1 <= q_1; p_1 = p_1 + 1)
// ...
// {
// V v = (V)a[p_0, p_1, ...]; /* OR */ (D1 d1, ...) = (V)a[p_0, p_1, ...];
// /* body */
// }
BoundStatement? forLoop = null;
for (int dimension = rank - 1; dimension >= 0; dimension--)
{
ImmutableArray<BoundExpression> dimensionArgument = ImmutableArray.Create(
MakeLiteral(forEachSyntax,
constantValue: ConstantValue.Create(dimension, ConstantValueTypeDiscriminator.Int32),
type: intType));
// a.GetLowerBound(dimension)
BoundExpression currentDimensionLowerBound = BoundCall.Synthesized(forEachSyntax, boundArrayVar, getLowerBoundMethod, dimensionArgument);
// int p_dimension = a.GetLowerBound(dimension);
BoundStatement positionVarDecl = MakeLocalDeclaration(forEachSyntax, positionVar[dimension], currentDimensionLowerBound);
GeneratedLabelSymbol breakLabel = dimension == 0 // outermost for-loop
? node.BreakLabel // i.e. the one that break statements will jump to
: new GeneratedLabelSymbol("break"); // Should not affect emitted code since unused
// p_dimension <= q_dimension //NB: OrEqual
BoundExpression exitCondition = new BoundBinaryOperator(
syntax: forEachSyntax,
operatorKind: BinaryOperatorKind.IntLessThanOrEqual,
left: boundPositionVar[dimension],
right: boundUpperVar[dimension],
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: boolType);
// p_dimension = p_dimension + 1;
BoundStatement positionIncrement = MakePositionIncrement(forEachSyntax, boundPositionVar[dimension], intType);
BoundStatement body;
GeneratedLabelSymbol continueLabel;
if (forLoop == null)
{
// innermost for-loop
body = innermostLoopBody;
continueLabel = node.ContinueLabel; //i.e. the one continue statements will actually jump to
}
else
{
body = forLoop;
continueLabel = new GeneratedLabelSymbol("continue"); // Should not affect emitted code since unused
}
forLoop = RewriteForStatementWithoutInnerLocals(
original: node,
outerLocals: ImmutableArray.Create(positionVar[dimension]),
rewrittenInitializer: positionVarDecl,
rewrittenCondition: exitCondition,
rewrittenIncrement: positionIncrement,
rewrittenBody: body,
breakLabel: breakLabel,
continueLabel: continueLabel,
hasErrors: node.HasErrors);
}
Debug.Assert(forLoop != null);
BoundStatement result = new BoundBlock(
forEachSyntax,
ImmutableArray.Create(arrayVar).Concat(upperVar.AsImmutableOrNull()),
ImmutableArray.Create(arrayVarDecl).Concat(upperVarDecl.AsImmutableOrNull()).Add(forLoop));
InstrumentForEachStatement(node, ref result);
return result;
}
/// <summary>
/// So that the binding info can return an appropriate SemanticInfo.Converted type for the collection
/// expression of a foreach node, it is wrapped in a BoundConversion to the collection type in the
/// initial bound tree. However, we may be able to optimize away (or entirely disregard) the conversion
/// so we pull out the bound node for the underlying expression.
/// </summary>
private static BoundExpression GetUnconvertedCollectionExpression(BoundForEachStatement node)
{
var boundExpression = node.Expression;
if (boundExpression.Kind == BoundKind.Conversion)
{
return ((BoundConversion)boundExpression).Operand;
}
// Conversion was an identity conversion and the LocalRewriter must have optimized away the
// BoundConversion node, we can return the expression itself.
return boundExpression;
}
private static BoundLocal MakeBoundLocal(CSharpSyntaxNode syntax, LocalSymbol local, TypeSymbol type)
{
return new BoundLocal(syntax,
localSymbol: local,
constantValueOpt: null,
type: type);
}
private BoundStatement MakeLocalDeclaration(CSharpSyntaxNode syntax, LocalSymbol local, BoundExpression rewrittenInitialValue)
{
var result = RewriteLocalDeclaration(
originalOpt: null,
syntax: syntax,
localSymbol: local,
rewrittenInitializer: rewrittenInitialValue);
Debug.Assert(result is { });
return result;
}
// Used to increment integer index into an array or string.
private BoundStatement MakePositionIncrement(CSharpSyntaxNode syntax, BoundLocal boundPositionVar, TypeSymbol intType)
{
// A normal for-loop would have a sequence point on the increment. We don't want that since the code is synthesized,
// but we add a hidden sequence point to avoid disrupting the stepping experience.
// A bound sequence point is permitted to have a null syntax to make a hidden sequence point.
return BoundSequencePoint.CreateHidden(
statementOpt: new BoundExpressionStatement(syntax,
expression: new BoundAssignmentOperator(syntax,
left: boundPositionVar,
right: new BoundBinaryOperator(syntax,
operatorKind: BinaryOperatorKind.IntAddition, // unchecked, never overflows since array/string index can't be >= Int32.MaxValue
left: boundPositionVar,
right: MakeLiteral(syntax,
constantValue: ConstantValue.Create(1),
type: intType),
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: intType),
type: intType)));
}
private void InstrumentForEachStatementCollectionVarDeclaration(BoundForEachStatement original, [NotNullIfNotNull("collectionVarDecl")] ref BoundStatement? collectionVarDecl)
{
if (this.Instrument)
{
collectionVarDecl = _instrumenter.InstrumentForEachStatementCollectionVarDeclaration(original, collectionVarDecl);
}
}
private void InstrumentForEachStatementIterationVarDeclaration(BoundForEachStatement original, ref BoundStatement iterationVarDecl)
{
if (this.Instrument)
{
CommonForEachStatementSyntax forEachSyntax = (CommonForEachStatementSyntax)original.Syntax;
if (forEachSyntax is ForEachVariableStatementSyntax)
{
iterationVarDecl = _instrumenter.InstrumentForEachStatementDeconstructionVariablesDeclaration(original, iterationVarDecl);
}
else
{
iterationVarDecl = _instrumenter.InstrumentForEachStatementIterationVarDeclaration(original, iterationVarDecl);
}
}
}
private void InstrumentForEachStatement(BoundForEachStatement original, ref BoundStatement result)
{
if (this.Instrument)
{
result = _instrumenter.InstrumentForEachStatement(original, result);
}
}
/// <summary>
/// Produce a while(true) loop
///
/// <![CDATA[
/// still-true:
/// /* body */
/// goto still-true;
/// ]]>
/// </summary>
private BoundStatement MakeWhileTrueLoop(BoundForEachStatement loop, BoundBlock body)
{
Debug.Assert(loop.EnumeratorInfoOpt is { IsAsync: true });
SyntaxNode syntax = loop.Syntax;
GeneratedLabelSymbol startLabel = new GeneratedLabelSymbol("still-true");
BoundStatement startLabelStatement = new BoundLabelStatement(syntax, startLabel);
if (this.Instrument)
{
startLabelStatement = BoundSequencePoint.CreateHidden(startLabelStatement);
}
// still-true:
// /* body */
// goto still-true;
return BoundStatementList.Synthesized(syntax, hasErrors: false,
startLabelStatement,
body,
new BoundGotoStatement(syntax, startLabel));
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
/// <summary>
/// This is the entry point for foreach-loop lowering. It delegates to
/// RewriteEnumeratorForEachStatement
/// RewriteSingleDimensionalArrayForEachStatement
/// RewriteMultiDimensionalArrayForEachStatement
/// CanRewriteForEachAsFor
/// </summary>
/// <remarks>
/// We are diverging from the C# 4 spec (and Dev10) to follow the C# 5 spec.
/// The iteration variable will be declared *inside* each loop iteration,
/// rather than outside the loop.
/// </remarks>
public override BoundNode VisitForEachStatement(BoundForEachStatement node)
{
// No point in performing this lowering if the node won't be emitted.
if (node.HasErrors)
{
return node;
}
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
TypeSymbol? nodeExpressionType = collectionExpression.Type;
Debug.Assert(nodeExpressionType is { });
if (nodeExpressionType.Kind == SymbolKind.ArrayType)
{
ArrayTypeSymbol arrayType = (ArrayTypeSymbol)nodeExpressionType;
if (arrayType.IsSZArray)
{
return RewriteSingleDimensionalArrayForEachStatement(node);
}
else
{
return RewriteMultiDimensionalArrayForEachStatement(node);
}
}
else if (node.AwaitOpt is null && CanRewriteForEachAsFor(node.Syntax, nodeExpressionType, out var indexerGet, out var lengthGetter))
{
return RewriteForEachStatementAsFor(node, indexerGet, lengthGetter);
}
else
{
return RewriteEnumeratorForEachStatement(node);
}
}
private bool CanRewriteForEachAsFor(SyntaxNode forEachSyntax, TypeSymbol nodeExpressionType, [NotNullWhen(true)] out MethodSymbol? indexerGet, [NotNullWhen(true)] out MethodSymbol? lengthGet)
{
lengthGet = indexerGet = null;
var origDefinition = nodeExpressionType.OriginalDefinition;
if (origDefinition.SpecialType == SpecialType.System_String)
{
lengthGet = UnsafeGetSpecialTypeMethod(forEachSyntax, SpecialMember.System_String__Length);
indexerGet = UnsafeGetSpecialTypeMethod(forEachSyntax, SpecialMember.System_String__Chars);
}
else if ((object)origDefinition == this._compilation.GetWellKnownType(WellKnownType.System_Span_T))
{
var spanType = (NamedTypeSymbol)nodeExpressionType;
lengthGet = (MethodSymbol?)_factory.WellKnownMember(WellKnownMember.System_Span_T__get_Length, isOptional: true)?.SymbolAsMember(spanType);
indexerGet = (MethodSymbol?)_factory.WellKnownMember(WellKnownMember.System_Span_T__get_Item, isOptional: true)?.SymbolAsMember(spanType);
}
else if ((object)origDefinition == this._compilation.GetWellKnownType(WellKnownType.System_ReadOnlySpan_T))
{
var spanType = (NamedTypeSymbol)nodeExpressionType;
lengthGet = (MethodSymbol?)_factory.WellKnownMember(WellKnownMember.System_ReadOnlySpan_T__get_Length, isOptional: true)?.SymbolAsMember(spanType);
indexerGet = (MethodSymbol?)_factory.WellKnownMember(WellKnownMember.System_ReadOnlySpan_T__get_Item, isOptional: true)?.SymbolAsMember(spanType);
}
return lengthGet is { } && indexerGet is { };
}
/// <summary>
/// Lower a foreach loop that will enumerate a collection using an enumerator.
///
/// <![CDATA[
/// E e = ((C)(x)).GetEnumerator() OR ((C)(x)).GetAsyncEnumerator()
/// try {
/// while (e.MoveNext()) OR while (await e.MoveNextAsync())
/// {
/// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
/// // body
/// }
/// }
/// finally {
/// // clean up e
/// }
/// ]]>
/// </summary>
private BoundStatement RewriteEnumeratorForEachStatement(BoundForEachStatement node)
{
var forEachSyntax = (CommonForEachStatementSyntax)node.Syntax;
bool isAsync = node.AwaitOpt != null;
ForEachEnumeratorInfo? enumeratorInfo = node.EnumeratorInfoOpt;
Debug.Assert(enumeratorInfo != null);
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
BoundExpression rewrittenExpression = VisitExpression(collectionExpression);
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
MethodArgumentInfo getEnumeratorInfo = enumeratorInfo.GetEnumeratorInfo;
TypeSymbol enumeratorType = getEnumeratorInfo.Method.ReturnType;
TypeSymbol elementType = enumeratorInfo.ElementType;
// E e
LocalSymbol enumeratorVar = _factory.SynthesizedLocal(enumeratorType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachEnumerator);
// Reference to e.
BoundLocal boundEnumeratorVar = MakeBoundLocal(forEachSyntax, enumeratorVar, enumeratorType);
var receiver = ConvertReceiverForInvocation(forEachSyntax, rewrittenExpression, getEnumeratorInfo.Method, enumeratorInfo.CollectionConversion, enumeratorInfo.CollectionType);
// If the GetEnumerator call is an extension method, then the first argument is the receiver. We want to replace
// the first argument with our converted receiver and pass null as the receiver instead.
if (getEnumeratorInfo.Method.IsExtensionMethod)
{
var builder = ArrayBuilder<BoundExpression>.GetInstance(getEnumeratorInfo.Arguments.Length);
builder.Add(receiver);
builder.AddRange(getEnumeratorInfo.Arguments, 1, getEnumeratorInfo.Arguments.Length - 1);
getEnumeratorInfo = getEnumeratorInfo with { Arguments = builder.ToImmutableAndFree() };
receiver = null;
}
// ((C)(x)).GetEnumerator(); OR (x).GetEnumerator(); OR async variants (which fill-in arguments for optional parameters)
BoundExpression enumeratorVarInitValue = SynthesizeCall(getEnumeratorInfo, forEachSyntax, receiver,
allowExtensionAndOptionalParameters: isAsync || getEnumeratorInfo.Method.IsExtensionMethod,
// C# 8 shipped allowing the CancellationToken of `IAsyncEnumerable.GetAsyncEnumerator` to be non-optional.
// https://github.com/dotnet/roslyn/issues/50182 tracks making this an error and breaking the scenario.
assertParametersAreOptional: false);
// E e = ((C)(x)).GetEnumerator();
BoundStatement enumeratorVarDecl = MakeLocalDeclaration(forEachSyntax, enumeratorVar, enumeratorVarInitValue);
InstrumentForEachStatementCollectionVarDeclaration(node, ref enumeratorVarDecl);
// (V)(T)e.Current
BoundExpression iterationVarAssignValue = MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: BoundCall.Synthesized(
syntax: forEachSyntax,
receiverOpt: boundEnumeratorVar,
method: enumeratorInfo.CurrentPropertyGetter),
conversion: enumeratorInfo.CurrentConversion,
rewrittenType: elementType,
@checked: node.Checked),
conversion: node.ElementConversion,
rewrittenType: node.IterationVariableType.Type,
@checked: node.Checked);
// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
ImmutableArray<LocalSymbol> iterationVariables = node.IterationVariables;
BoundStatement iterationVarDecl = LocalOrDeconstructionDeclaration(node, iterationVariables, iterationVarAssignValue);
InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVarDecl);
// while (e.MoveNext()) -OR- while (await e.MoveNextAsync())
// {
// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
// /* node.Body */
// }
var rewrittenBodyBlock = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVarDecl, rewrittenBody, forEachSyntax);
BoundExpression rewrittenCondition = SynthesizeCall(
methodArgumentInfo: enumeratorInfo.MoveNextInfo,
syntax: forEachSyntax,
receiver: boundEnumeratorVar,
allowExtensionAndOptionalParameters: isAsync);
if (isAsync)
{
Debug.Assert(node.AwaitOpt is { GetResult: { } });
rewrittenCondition = RewriteAwaitExpression(forEachSyntax, rewrittenCondition, node.AwaitOpt, node.AwaitOpt.GetResult.ReturnType, used: true);
}
BoundStatement whileLoop = RewriteWhileStatement(
loop: node,
rewrittenCondition,
rewrittenBody: rewrittenBodyBlock,
breakLabel: node.BreakLabel,
continueLabel: node.ContinueLabel,
hasErrors: false);
BoundStatement result;
if (enumeratorInfo.NeedsDisposal)
{
BoundStatement tryFinally = WrapWithTryFinallyDispose(forEachSyntax, enumeratorInfo, enumeratorType, boundEnumeratorVar, whileLoop);
// E e = ((C)(x)).GetEnumerator();
// try {
// /* as above */
result = new BoundBlock(
syntax: forEachSyntax,
locals: ImmutableArray.Create(enumeratorVar),
statements: ImmutableArray.Create<BoundStatement>(enumeratorVarDecl, tryFinally));
}
else
{
// E e = ((C)(x)).GetEnumerator();
// while (e.MoveNext()) {
// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
// /* loop body */
// }
result = new BoundBlock(
syntax: forEachSyntax,
locals: ImmutableArray.Create(enumeratorVar),
statements: ImmutableArray.Create<BoundStatement>(enumeratorVarDecl, whileLoop));
}
InstrumentForEachStatement(node, ref result);
return result;
}
private bool TryGetDisposeMethod(CommonForEachStatementSyntax forEachSyntax, ForEachEnumeratorInfo enumeratorInfo, out MethodSymbol disposeMethod)
{
if (enumeratorInfo.IsAsync)
{
disposeMethod = (MethodSymbol)Binder.GetWellKnownTypeMember(_compilation, WellKnownMember.System_IAsyncDisposable__DisposeAsync, _diagnostics, syntax: forEachSyntax);
return (object)disposeMethod != null;
}
return Binder.TryGetSpecialTypeMember(_compilation, SpecialMember.System_IDisposable__Dispose, forEachSyntax, _diagnostics, out disposeMethod);
}
/// <summary>
/// There are three possible cases where we need disposal:
/// - pattern-based disposal (we have a Dispose/DisposeAsync method)
/// - interface-based disposal (the enumerator type converts to IDisposable/IAsyncDisposable)
/// - we need to do a runtime check for IDisposable
/// </summary>
private BoundStatement WrapWithTryFinallyDispose(
CommonForEachStatementSyntax forEachSyntax,
ForEachEnumeratorInfo enumeratorInfo,
TypeSymbol enumeratorType,
BoundLocal boundEnumeratorVar,
BoundStatement rewrittenBody)
{
Debug.Assert(enumeratorInfo.NeedsDisposal);
NamedTypeSymbol? idisposableTypeSymbol = null;
bool isImplicit = false;
MethodSymbol? disposeMethod = enumeratorInfo.PatternDisposeInfo?.Method; // pattern-based
if (disposeMethod is null)
{
TryGetDisposeMethod(forEachSyntax, enumeratorInfo, out disposeMethod); // interface-based
// This is a temporary workaround for https://github.com/dotnet/roslyn/issues/39948
if (disposeMethod is null)
{
return rewrittenBody;
}
idisposableTypeSymbol = disposeMethod.ContainingType;
Debug.Assert(_factory.CurrentFunction is { });
var conversions = new TypeConversions(_factory.CurrentFunction.ContainingAssembly.CorLibrary);
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo();
isImplicit = conversions.ClassifyImplicitConversionFromType(enumeratorType, idisposableTypeSymbol, ref useSiteInfo).IsImplicit;
_diagnostics.Add(forEachSyntax, useSiteInfo);
}
Binder.ReportDiagnosticsIfObsolete(_diagnostics, disposeMethod, forEachSyntax,
hasBaseReceiver: false,
containingMember: _factory.CurrentFunction,
containingType: _factory.CurrentType,
location: enumeratorInfo.Location);
BoundBlock finallyBlockOpt;
if (isImplicit || !(enumeratorInfo.PatternDisposeInfo is null))
{
Conversion receiverConversion = enumeratorType.IsStructType() ?
Conversion.Boxing :
Conversion.ImplicitReference;
BoundExpression receiver;
BoundExpression disposeCall;
var disposeInfo = enumeratorInfo.PatternDisposeInfo;
if (disposeInfo is null)
{
Debug.Assert(idisposableTypeSymbol is { });
disposeInfo = MethodArgumentInfo.CreateParameterlessMethod(disposeMethod);
receiver = ConvertReceiverForInvocation(forEachSyntax, boundEnumeratorVar, disposeMethod, receiverConversion, idisposableTypeSymbol);
}
else
{
receiver = boundEnumeratorVar;
}
// ((IDisposable)e).Dispose() or e.Dispose() or await ((IAsyncDisposable)e).DisposeAsync() or await e.DisposeAsync()
disposeCall = MakeCallWithNoExplicitArgument(disposeInfo, forEachSyntax, receiver);
BoundStatement disposeCallStatement;
var disposeAwaitableInfoOpt = enumeratorInfo.DisposeAwaitableInfo;
if (disposeAwaitableInfoOpt != null)
{
// await /* disposeCall */
disposeCallStatement = WrapWithAwait(forEachSyntax, disposeCall, disposeAwaitableInfoOpt);
_sawAwaitInExceptionHandler = true;
}
else
{
// ((IDisposable)e).Dispose(); or e.Dispose();
disposeCallStatement = new BoundExpressionStatement(forEachSyntax, disposeCall);
}
BoundStatement alwaysOrMaybeDisposeStmt;
if (enumeratorType.IsValueType)
{
// No way for the struct to be nullable and disposable.
Debug.Assert(enumeratorType.OriginalDefinition.SpecialType != SpecialType.System_Nullable_T);
// For non-nullable structs, no null check is required.
alwaysOrMaybeDisposeStmt = disposeCallStatement;
}
else
{
// NB: cast to object missing from spec. Needed to ignore user-defined operators and box type parameters.
// if ((object)e != null) ((IDisposable)e).Dispose();
alwaysOrMaybeDisposeStmt = RewriteIfStatement(
syntax: forEachSyntax,
rewrittenCondition: new BoundBinaryOperator(forEachSyntax,
operatorKind: BinaryOperatorKind.NotEqual,
left: MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: boundEnumeratorVar,
conversion: enumeratorInfo.EnumeratorConversion,
rewrittenType: _compilation.GetSpecialType(SpecialType.System_Object),
@checked: false),
right: MakeLiteral(forEachSyntax,
constantValue: ConstantValue.Null,
type: null),
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: _compilation.GetSpecialType(SpecialType.System_Boolean)),
rewrittenConsequence: disposeCallStatement,
rewrittenAlternativeOpt: null,
hasErrors: false);
}
finallyBlockOpt = new BoundBlock(forEachSyntax,
locals: ImmutableArray<LocalSymbol>.Empty,
statements: ImmutableArray.Create(alwaysOrMaybeDisposeStmt));
}
else
{
// If we couldn't find either pattern-based or interface-based disposal, and the enumerator type isn't sealed,
// and the loop isn't async, then we include a runtime check.
Debug.Assert(!enumeratorType.IsSealed);
Debug.Assert(!enumeratorInfo.IsAsync);
Debug.Assert(idisposableTypeSymbol is { });
Debug.Assert(disposeMethod is { });
// IDisposable d
LocalSymbol disposableVar = _factory.SynthesizedLocal(idisposableTypeSymbol);
// Reference to d.
BoundLocal boundDisposableVar = MakeBoundLocal(forEachSyntax, disposableVar, idisposableTypeSymbol);
BoundTypeExpression boundIDisposableTypeExpr = new BoundTypeExpression(forEachSyntax,
aliasOpt: null,
type: idisposableTypeSymbol);
// e as IDisposable
BoundExpression disposableVarInitValue = new BoundAsOperator(forEachSyntax,
operand: boundEnumeratorVar,
targetType: boundIDisposableTypeExpr,
conversion: Conversion.ExplicitReference, // Explicit so the emitter won't optimize it away.
type: idisposableTypeSymbol);
// IDisposable d = e as IDisposable;
BoundStatement disposableVarDecl = MakeLocalDeclaration(forEachSyntax, disposableVar, disposableVarInitValue);
// d.Dispose()
BoundExpression disposeCall = BoundCall.Synthesized(syntax: forEachSyntax, receiverOpt: boundDisposableVar, method: disposeMethod);
BoundStatement disposeCallStatement = new BoundExpressionStatement(forEachSyntax, expression: disposeCall);
// if (d != null) d.Dispose();
BoundStatement ifStmt = RewriteIfStatement(
syntax: forEachSyntax,
rewrittenCondition: new BoundBinaryOperator(forEachSyntax,
operatorKind: BinaryOperatorKind.NotEqual, // reference equality
left: boundDisposableVar,
right: MakeLiteral(forEachSyntax, constantValue: ConstantValue.Null, type: null),
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: _compilation.GetSpecialType(SpecialType.System_Boolean)),
rewrittenConsequence: disposeCallStatement,
rewrittenAlternativeOpt: null,
hasErrors: false);
// IDisposable d = e as IDisposable;
// if (d != null) d.Dispose();
finallyBlockOpt = new BoundBlock(forEachSyntax,
locals: ImmutableArray.Create(disposableVar),
statements: ImmutableArray.Create(disposableVarDecl, ifStmt));
}
// try {
// while (e.MoveNext()) {
// V v = (V)(T)e.Current; -OR- (D1 d1, ...) = (V)(T)e.Current;
// /* loop body */
// }
// }
// finally {
// /* dispose of e */
// }
BoundStatement tryFinally = new BoundTryStatement(forEachSyntax,
tryBlock: new BoundBlock(forEachSyntax,
locals: ImmutableArray<LocalSymbol>.Empty,
statements: ImmutableArray.Create<BoundStatement>(rewrittenBody)),
catchBlocks: ImmutableArray<BoundCatchBlock>.Empty,
finallyBlockOpt: finallyBlockOpt);
return tryFinally;
}
/// <summary>
/// Produce:
/// await /* disposeCall */;
/// </summary>
private BoundStatement WrapWithAwait(CommonForEachStatementSyntax forEachSyntax, BoundExpression disposeCall, BoundAwaitableInfo disposeAwaitableInfoOpt)
{
TypeSymbol awaitExpressionType = disposeAwaitableInfoOpt.GetResult?.ReturnType ?? _compilation.DynamicType;
var awaitExpr = RewriteAwaitExpression(forEachSyntax, disposeCall, disposeAwaitableInfoOpt, awaitExpressionType, used: false);
return new BoundExpressionStatement(forEachSyntax, awaitExpr);
}
/// <summary>
/// Optionally apply a conversion to the receiver.
///
/// If the receiver is of struct type and the method is an interface method, then skip the conversion.
/// When we call the interface method directly - the code generator will detect it and generate a
/// constrained virtual call.
/// </summary>
/// <param name="syntax">A syntax node to attach to the synthesized bound node.</param>
/// <param name="receiver">Receiver of method call.</param>
/// <param name="method">Method to invoke.</param>
/// <param name="receiverConversion">Conversion to be applied to the receiver if not calling an interface method on a struct.</param>
/// <param name="convertedReceiverType">Type of the receiver after applying the conversion.</param>
private BoundExpression ConvertReceiverForInvocation(CSharpSyntaxNode syntax, BoundExpression receiver, MethodSymbol method, Conversion receiverConversion, TypeSymbol convertedReceiverType)
{
Debug.Assert(receiver.Type is { });
if (!receiver.Type.IsReferenceType && method.ContainingType.IsInterface)
{
Debug.Assert(receiverConversion.IsImplicit && !receiverConversion.IsUserDefined);
// NOTE: The spec says that disposing of a struct enumerator won't cause any
// unnecessary boxing to occur. However, Dev10 extends this improvement to the
// GetEnumerator call as well.
// We're going to let the emitter take care of avoiding the extra boxing.
// When it sees an interface call to a struct, it will generate a constrained
// virtual call, which will skip boxing, if possible.
// CONSIDER: In cases where the struct implicitly implements the interface method
// (i.e. with a public method), we could save a few bytes of IL by creating a
// BoundCall to the struct method rather than the interface method (so that the
// emitter wouldn't need to create a constrained virtual call). It is not clear
// what effect this would have on back compat.
// NOTE: This call does not correspond to anything that can be written in C# source.
// We're invoking the interface method directly on the struct (which may have a private
// explicit implementation). The code generator knows how to handle it though.
// receiver.InterfaceMethod()
}
else
{
// ((Interface)receiver).InterfaceMethod()
Debug.Assert(!receiverConversion.IsNumeric);
receiver = MakeConversionNode(
syntax: syntax,
rewrittenOperand: receiver,
conversion: receiverConversion,
@checked: false,
rewrittenType: convertedReceiverType);
}
return receiver;
}
private BoundExpression SynthesizeCall(MethodArgumentInfo methodArgumentInfo, CSharpSyntaxNode syntax, BoundExpression? receiver, bool allowExtensionAndOptionalParameters, bool assertParametersAreOptional = true)
{
if (allowExtensionAndOptionalParameters)
{
// Generate a call with zero explicit arguments, but with implicit arguments for optional and params parameters.
return MakeCallWithNoExplicitArgument(methodArgumentInfo, syntax, receiver, assertParametersAreOptional);
}
// Generate a call with literally zero arguments
Debug.Assert(methodArgumentInfo.Arguments.IsEmpty);
return BoundCall.Synthesized(syntax, receiver, methodArgumentInfo.Method, arguments: ImmutableArray<BoundExpression>.Empty);
}
/// <summary>
/// Lower a foreach loop that will enumerate a collection via indexing.
///
/// <![CDATA[
///
/// Indexable a = x;
/// for (int p = 0; p < a.Length; p = p + 1) {
/// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
/// // body
/// }
///
/// ]]>
/// </summary>
/// <remarks>
/// NOTE: We're assuming that sequence points have already been generated.
/// Otherwise, lowering to for-loops would generated spurious ones.
/// </remarks>
private BoundStatement RewriteForEachStatementAsFor(BoundForEachStatement node, MethodSymbol indexerGet, MethodSymbol lengthGet)
{
var forEachSyntax = (CommonForEachStatementSyntax)node.Syntax;
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
NamedTypeSymbol? collectionType = (NamedTypeSymbol?)collectionExpression.Type;
Debug.Assert(collectionType is { });
TypeSymbol intType = _compilation.GetSpecialType(SpecialType.System_Int32);
TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean);
BoundExpression rewrittenExpression = VisitExpression(collectionExpression);
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
// Collection a
LocalSymbol collectionTemp = _factory.SynthesizedLocal(collectionType, forEachSyntax, kind: SynthesizedLocalKind.ForEachArray);
// Collection a = /*node.Expression*/;
BoundStatement arrayVarDecl = MakeLocalDeclaration(forEachSyntax, collectionTemp, rewrittenExpression);
InstrumentForEachStatementCollectionVarDeclaration(node, ref arrayVarDecl);
// Reference to a.
BoundLocal boundArrayVar = MakeBoundLocal(forEachSyntax, collectionTemp, collectionType);
// int p
LocalSymbol positionVar = _factory.SynthesizedLocal(intType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArrayIndex);
// Reference to p.
BoundLocal boundPositionVar = MakeBoundLocal(forEachSyntax, positionVar, intType);
// int p = 0;
BoundStatement positionVarDecl = MakeLocalDeclaration(forEachSyntax, positionVar,
MakeLiteral(forEachSyntax, ConstantValue.Default(SpecialType.System_Int32), intType));
// (V)a[p]
BoundExpression iterationVarInitValue = MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: BoundCall.Synthesized(
syntax: forEachSyntax,
receiverOpt: boundArrayVar,
indexerGet,
boundPositionVar),
conversion: node.ElementConversion,
rewrittenType: node.IterationVariableType.Type,
@checked: node.Checked);
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
ImmutableArray<LocalSymbol> iterationVariables = node.IterationVariables;
BoundStatement iterationVariableDecl = LocalOrDeconstructionDeclaration(node, iterationVariables, iterationVarInitValue);
InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVariableDecl);
BoundStatement initializer = new BoundStatementList(forEachSyntax,
statements: ImmutableArray.Create<BoundStatement>(arrayVarDecl, positionVarDecl));
// a.Length
BoundExpression arrayLength = BoundCall.Synthesized(
syntax: forEachSyntax,
receiverOpt: boundArrayVar,
lengthGet);
// p < a.Length
BoundExpression exitCondition = new BoundBinaryOperator(
syntax: forEachSyntax,
operatorKind: BinaryOperatorKind.IntLessThan,
left: boundPositionVar,
right: arrayLength,
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: boolType);
// p = p + 1;
BoundStatement positionIncrement = MakePositionIncrement(forEachSyntax, boundPositionVar, intType);
// {
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
// /*node.Body*/
// }
BoundStatement loopBody = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVariableDecl, rewrittenBody, forEachSyntax);
// for (Collection a = /*node.Expression*/, int p = 0; p < a.Length; p = p + 1) {
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
// /*node.Body*/
// }
BoundStatement result = RewriteForStatementWithoutInnerLocals(
original: node,
outerLocals: ImmutableArray.Create<LocalSymbol>(collectionTemp, positionVar),
rewrittenInitializer: initializer,
rewrittenCondition: exitCondition,
rewrittenIncrement: positionIncrement,
rewrittenBody: loopBody,
breakLabel: node.BreakLabel,
continueLabel: node.ContinueLabel,
hasErrors: node.HasErrors);
InstrumentForEachStatement(node, ref result);
return result;
}
/// <summary>
/// Takes the expression for the current value of the iteration variable and either
/// (1) assigns it into a local, or
/// (2) deconstructs it into multiple locals (if there is a deconstruct step).
///
/// Produces <c>V v = /* expression */</c> or <c>(D1 d1, ...) = /* expression */</c>.
/// </summary>
private BoundStatement LocalOrDeconstructionDeclaration(
BoundForEachStatement forEachBound,
ImmutableArray<LocalSymbol> iterationVariables,
BoundExpression iterationVarValue)
{
var forEachSyntax = (CommonForEachStatementSyntax)forEachBound.Syntax;
BoundStatement iterationVarDecl;
BoundForEachDeconstructStep? deconstruction = forEachBound.DeconstructionOpt;
if (deconstruction == null)
{
// V v = /* expression */
Debug.Assert(iterationVariables.Length == 1);
iterationVarDecl = MakeLocalDeclaration(forEachSyntax, iterationVariables[0], iterationVarValue);
}
else
{
// (D1 d1, ...) = /* expression */
var assignment = deconstruction.DeconstructionAssignment;
AddPlaceholderReplacement(deconstruction.TargetPlaceholder, iterationVarValue);
BoundExpression loweredAssignment = VisitExpression(assignment);
iterationVarDecl = new BoundExpressionStatement(assignment.Syntax, loweredAssignment);
RemovePlaceholderReplacement(deconstruction.TargetPlaceholder);
}
return iterationVarDecl;
}
private static BoundBlock CreateBlockDeclaringIterationVariables(
ImmutableArray<LocalSymbol> iterationVariables,
BoundStatement iteratorVariableInitialization,
BoundStatement rewrittenBody,
CommonForEachStatementSyntax forEachSyntax)
{
// The scope of the iteration variable is the embedded statement syntax.
// However consider the following foreach statement:
//
// foreach (int x in ...) { int y = ...; F(() => x); F(() => y));
//
// We currently generate 2 closures. One containing variable x, the other variable y.
// The EnC source mapping infrastructure requires each closure within a method body
// to have a unique syntax offset. Hence we associate the bound block declaring the
// iteration variable with the foreach statement, not the embedded statement.
return new BoundBlock(
forEachSyntax,
locals: iterationVariables,
statements: ImmutableArray.Create(iteratorVariableInitialization, rewrittenBody));
}
private static BoundBlock CreateBlockDeclaringIterationVariables(
ImmutableArray<LocalSymbol> iterationVariables,
BoundStatement iteratorVariableInitialization,
BoundStatement checkAndBreak,
BoundStatement rewrittenBody,
LabelSymbol continueLabel,
CommonForEachStatementSyntax forEachSyntax)
{
// The scope of the iteration variable is the embedded statement syntax.
// However consider the following foreach statement:
//
// await foreach (int x in ...) { int y = ...; F(() => x); F(() => y));
//
// We currently generate 2 closures. One containing variable x, the other variable y.
// The EnC source mapping infrastructure requires each closure within a method body
// to have a unique syntax offset. Hence we associate the bound block declaring the
// iteration variable with the foreach statement, not the embedded statement.
return new BoundBlock(
forEachSyntax,
locals: iterationVariables,
statements: ImmutableArray.Create(
iteratorVariableInitialization,
checkAndBreak,
rewrittenBody,
new BoundLabelStatement(forEachSyntax, continueLabel)));
}
/// <summary>
/// Lower a foreach loop that will enumerate a single-dimensional array.
///
/// A[] a = x;
/// for (int p = 0; p < a.Length; p = p + 1) {
/// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
/// // body
/// }
/// </summary>
/// <remarks>
/// We will follow Dev10 in diverging from the C# 4 spec by ignoring Array's
/// implementation of IEnumerable and just indexing into its elements.
///
/// NOTE: We're assuming that sequence points have already been generated.
/// Otherwise, lowering to for-loops would generated spurious ones.
/// </remarks>
private BoundStatement RewriteSingleDimensionalArrayForEachStatement(BoundForEachStatement node)
{
var forEachSyntax = (CommonForEachStatementSyntax)node.Syntax;
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
Debug.Assert(collectionExpression.Type is { TypeKind: TypeKind.Array });
ArrayTypeSymbol arrayType = (ArrayTypeSymbol)collectionExpression.Type;
Debug.Assert(arrayType is { IsSZArray: true });
TypeSymbol intType = _compilation.GetSpecialType(SpecialType.System_Int32);
TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean);
BoundExpression rewrittenExpression = VisitExpression(collectionExpression);
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
// A[] a
LocalSymbol arrayVar = _factory.SynthesizedLocal(arrayType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArray);
// A[] a = /*node.Expression*/;
BoundStatement arrayVarDecl = MakeLocalDeclaration(forEachSyntax, arrayVar, rewrittenExpression);
InstrumentForEachStatementCollectionVarDeclaration(node, ref arrayVarDecl);
// Reference to a.
BoundLocal boundArrayVar = MakeBoundLocal(forEachSyntax, arrayVar, arrayType);
// int p
LocalSymbol positionVar = _factory.SynthesizedLocal(intType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArrayIndex);
// Reference to p.
BoundLocal boundPositionVar = MakeBoundLocal(forEachSyntax, positionVar, intType);
// int p = 0;
BoundStatement positionVarDecl = MakeLocalDeclaration(forEachSyntax, positionVar,
MakeLiteral(forEachSyntax, ConstantValue.Default(SpecialType.System_Int32), intType));
// (V)a[p]
BoundExpression iterationVarInitValue = MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: new BoundArrayAccess(
syntax: forEachSyntax,
expression: boundArrayVar,
indices: ImmutableArray.Create<BoundExpression>(boundPositionVar),
type: arrayType.ElementType),
conversion: node.ElementConversion,
rewrittenType: node.IterationVariableType.Type,
@checked: node.Checked);
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
ImmutableArray<LocalSymbol> iterationVariables = node.IterationVariables;
BoundStatement iterationVariableDecl = LocalOrDeconstructionDeclaration(node, iterationVariables, iterationVarInitValue);
InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVariableDecl);
BoundStatement initializer = new BoundStatementList(forEachSyntax,
statements: ImmutableArray.Create<BoundStatement>(arrayVarDecl, positionVarDecl));
// a.Length
BoundExpression arrayLength = new BoundArrayLength(
syntax: forEachSyntax,
expression: boundArrayVar,
type: intType);
// p < a.Length
BoundExpression exitCondition = new BoundBinaryOperator(
syntax: forEachSyntax,
operatorKind: BinaryOperatorKind.IntLessThan,
left: boundPositionVar,
right: arrayLength,
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: boolType);
// p = p + 1;
BoundStatement positionIncrement = MakePositionIncrement(forEachSyntax, boundPositionVar, intType);
// {
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
// /*node.Body*/
// }
BoundStatement loopBody = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVariableDecl, rewrittenBody, forEachSyntax);
// for (A[] a = /*node.Expression*/, int p = 0; p < a.Length; p = p + 1) {
// V v = (V)a[p]; /* OR */ (D1 d1, ...) = (V)a[p];
// /*node.Body*/
// }
BoundStatement result = RewriteForStatementWithoutInnerLocals(
original: node,
outerLocals: ImmutableArray.Create<LocalSymbol>(arrayVar, positionVar),
rewrittenInitializer: initializer,
rewrittenCondition: exitCondition,
rewrittenIncrement: positionIncrement,
rewrittenBody: loopBody,
breakLabel: node.BreakLabel,
continueLabel: node.ContinueLabel,
hasErrors: node.HasErrors);
InstrumentForEachStatement(node, ref result);
return result;
}
/// <summary>
/// Lower a foreach loop that will enumerate a multi-dimensional array.
///
/// A[...] a = x;
/// int q_0 = a.GetUpperBound(0), q_1 = a.GetUpperBound(1), ...;
/// for (int p_0 = a.GetLowerBound(0); p_0 <= q_0; p_0 = p_0 + 1)
/// for (int p_1 = a.GetLowerBound(1); p_1 <= q_1; p_1 = p_1 + 1)
/// ...
/// {
/// V v = (V)a[p_0, p_1, ...]; /* OR */ (D1 d1, ...) = (V)a[p_0, p_1, ...];
/// /* body */
/// }
/// </summary>
/// <remarks>
/// We will follow Dev10 in diverging from the C# 4 spec by ignoring Array's
/// implementation of IEnumerable and just indexing into its elements.
///
/// NOTE: We're assuming that sequence points have already been generated.
/// Otherwise, lowering to nested for-loops would generated spurious ones.
/// </remarks>
private BoundStatement RewriteMultiDimensionalArrayForEachStatement(BoundForEachStatement node)
{
var forEachSyntax = (CommonForEachStatementSyntax)node.Syntax;
BoundExpression collectionExpression = GetUnconvertedCollectionExpression(node);
Debug.Assert(collectionExpression.Type is { TypeKind: TypeKind.Array });
ArrayTypeSymbol arrayType = (ArrayTypeSymbol)collectionExpression.Type;
int rank = arrayType.Rank;
Debug.Assert(!arrayType.IsSZArray);
TypeSymbol intType = _compilation.GetSpecialType(SpecialType.System_Int32);
TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean);
// Values we'll use every iteration
MethodSymbol getLowerBoundMethod = UnsafeGetSpecialTypeMethod(forEachSyntax, SpecialMember.System_Array__GetLowerBound);
MethodSymbol getUpperBoundMethod = UnsafeGetSpecialTypeMethod(forEachSyntax, SpecialMember.System_Array__GetUpperBound);
BoundExpression rewrittenExpression = VisitExpression(collectionExpression);
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
// A[...] a
LocalSymbol arrayVar = _factory.SynthesizedLocal(arrayType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArray);
BoundLocal boundArrayVar = MakeBoundLocal(forEachSyntax, arrayVar, arrayType);
// A[...] a = /*node.Expression*/;
BoundStatement arrayVarDecl = MakeLocalDeclaration(forEachSyntax, arrayVar, rewrittenExpression);
InstrumentForEachStatementCollectionVarDeclaration(node, ref arrayVarDecl);
// NOTE: dev10 initializes all of the upper bound temps before entering the loop (as opposed to
// initializing each one at the corresponding level of nesting). Doing it at the same time as
// the lower bound would make this code a bit simpler, but it would make it harder to compare
// the roslyn and dev10 IL.
// int q_0, q_1, ...
LocalSymbol[] upperVar = new LocalSymbol[rank];
BoundLocal[] boundUpperVar = new BoundLocal[rank];
BoundStatement[] upperVarDecl = new BoundStatement[rank];
for (int dimension = 0; dimension < rank; dimension++)
{
// int q_dimension
upperVar[dimension] = _factory.SynthesizedLocal(intType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArrayLimit);
boundUpperVar[dimension] = MakeBoundLocal(forEachSyntax, upperVar[dimension], intType);
ImmutableArray<BoundExpression> dimensionArgument = ImmutableArray.Create(
MakeLiteral(forEachSyntax,
constantValue: ConstantValue.Create(dimension, ConstantValueTypeDiscriminator.Int32),
type: intType));
// a.GetUpperBound(dimension)
BoundExpression currentDimensionUpperBound = BoundCall.Synthesized(forEachSyntax, boundArrayVar, getUpperBoundMethod, dimensionArgument);
// int q_dimension = a.GetUpperBound(dimension);
upperVarDecl[dimension] = MakeLocalDeclaration(forEachSyntax, upperVar[dimension], currentDimensionUpperBound);
}
// int p_0, p_1, ...
LocalSymbol[] positionVar = new LocalSymbol[rank];
BoundLocal[] boundPositionVar = new BoundLocal[rank];
for (int dimension = 0; dimension < rank; dimension++)
{
positionVar[dimension] = _factory.SynthesizedLocal(intType, syntax: forEachSyntax, kind: SynthesizedLocalKind.ForEachArrayIndex);
boundPositionVar[dimension] = MakeBoundLocal(forEachSyntax, positionVar[dimension], intType);
}
// (V)a[p_0, p_1, ...]
BoundExpression iterationVarInitValue = MakeConversionNode(
syntax: forEachSyntax,
rewrittenOperand: new BoundArrayAccess(forEachSyntax,
expression: boundArrayVar,
indices: ImmutableArray.Create((BoundExpression[])boundPositionVar),
type: arrayType.ElementType),
conversion: node.ElementConversion,
rewrittenType: node.IterationVariableType.Type,
@checked: node.Checked);
// V v = (V)a[p_0, p_1, ...]; /* OR */ (D1 d1, ...) = (V)a[p_0, p_1, ...];
ImmutableArray<LocalSymbol> iterationVariables = node.IterationVariables;
BoundStatement iterationVarDecl = LocalOrDeconstructionDeclaration(node, iterationVariables, iterationVarInitValue);
InstrumentForEachStatementIterationVarDeclaration(node, ref iterationVarDecl);
// {
// V v = (V)a[p_0, p_1, ...]; /* OR */ (D1 d1, ...) = (V)a[p_0, p_1, ...];
// /* node.Body */
// }
BoundStatement innermostLoopBody = CreateBlockDeclaringIterationVariables(iterationVariables, iterationVarDecl, rewrittenBody, forEachSyntax);
// work from most-nested to least-nested
// for (int p_0 = a.GetLowerBound(0); p_0 <= q_0; p_0 = p_0 + 1)
// for (int p_1 = a.GetLowerBound(0); p_1 <= q_1; p_1 = p_1 + 1)
// ...
// {
// V v = (V)a[p_0, p_1, ...]; /* OR */ (D1 d1, ...) = (V)a[p_0, p_1, ...];
// /* body */
// }
BoundStatement? forLoop = null;
for (int dimension = rank - 1; dimension >= 0; dimension--)
{
ImmutableArray<BoundExpression> dimensionArgument = ImmutableArray.Create(
MakeLiteral(forEachSyntax,
constantValue: ConstantValue.Create(dimension, ConstantValueTypeDiscriminator.Int32),
type: intType));
// a.GetLowerBound(dimension)
BoundExpression currentDimensionLowerBound = BoundCall.Synthesized(forEachSyntax, boundArrayVar, getLowerBoundMethod, dimensionArgument);
// int p_dimension = a.GetLowerBound(dimension);
BoundStatement positionVarDecl = MakeLocalDeclaration(forEachSyntax, positionVar[dimension], currentDimensionLowerBound);
GeneratedLabelSymbol breakLabel = dimension == 0 // outermost for-loop
? node.BreakLabel // i.e. the one that break statements will jump to
: new GeneratedLabelSymbol("break"); // Should not affect emitted code since unused
// p_dimension <= q_dimension //NB: OrEqual
BoundExpression exitCondition = new BoundBinaryOperator(
syntax: forEachSyntax,
operatorKind: BinaryOperatorKind.IntLessThanOrEqual,
left: boundPositionVar[dimension],
right: boundUpperVar[dimension],
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: boolType);
// p_dimension = p_dimension + 1;
BoundStatement positionIncrement = MakePositionIncrement(forEachSyntax, boundPositionVar[dimension], intType);
BoundStatement body;
GeneratedLabelSymbol continueLabel;
if (forLoop == null)
{
// innermost for-loop
body = innermostLoopBody;
continueLabel = node.ContinueLabel; //i.e. the one continue statements will actually jump to
}
else
{
body = forLoop;
continueLabel = new GeneratedLabelSymbol("continue"); // Should not affect emitted code since unused
}
forLoop = RewriteForStatementWithoutInnerLocals(
original: node,
outerLocals: ImmutableArray.Create(positionVar[dimension]),
rewrittenInitializer: positionVarDecl,
rewrittenCondition: exitCondition,
rewrittenIncrement: positionIncrement,
rewrittenBody: body,
breakLabel: breakLabel,
continueLabel: continueLabel,
hasErrors: node.HasErrors);
}
Debug.Assert(forLoop != null);
BoundStatement result = new BoundBlock(
forEachSyntax,
ImmutableArray.Create(arrayVar).Concat(upperVar.AsImmutableOrNull()),
ImmutableArray.Create(arrayVarDecl).Concat(upperVarDecl.AsImmutableOrNull()).Add(forLoop));
InstrumentForEachStatement(node, ref result);
return result;
}
/// <summary>
/// So that the binding info can return an appropriate SemanticInfo.Converted type for the collection
/// expression of a foreach node, it is wrapped in a BoundConversion to the collection type in the
/// initial bound tree. However, we may be able to optimize away (or entirely disregard) the conversion
/// so we pull out the bound node for the underlying expression.
/// </summary>
private static BoundExpression GetUnconvertedCollectionExpression(BoundForEachStatement node)
{
var boundExpression = node.Expression;
if (boundExpression.Kind == BoundKind.Conversion)
{
return ((BoundConversion)boundExpression).Operand;
}
// Conversion was an identity conversion and the LocalRewriter must have optimized away the
// BoundConversion node, we can return the expression itself.
return boundExpression;
}
private static BoundLocal MakeBoundLocal(CSharpSyntaxNode syntax, LocalSymbol local, TypeSymbol type)
{
return new BoundLocal(syntax,
localSymbol: local,
constantValueOpt: null,
type: type);
}
private BoundStatement MakeLocalDeclaration(CSharpSyntaxNode syntax, LocalSymbol local, BoundExpression rewrittenInitialValue)
{
var result = RewriteLocalDeclaration(
originalOpt: null,
syntax: syntax,
localSymbol: local,
rewrittenInitializer: rewrittenInitialValue);
Debug.Assert(result is { });
return result;
}
// Used to increment integer index into an array or string.
private BoundStatement MakePositionIncrement(CSharpSyntaxNode syntax, BoundLocal boundPositionVar, TypeSymbol intType)
{
// A normal for-loop would have a sequence point on the increment. We don't want that since the code is synthesized,
// but we add a hidden sequence point to avoid disrupting the stepping experience.
// A bound sequence point is permitted to have a null syntax to make a hidden sequence point.
return BoundSequencePoint.CreateHidden(
statementOpt: new BoundExpressionStatement(syntax,
expression: new BoundAssignmentOperator(syntax,
left: boundPositionVar,
right: new BoundBinaryOperator(syntax,
operatorKind: BinaryOperatorKind.IntAddition, // unchecked, never overflows since array/string index can't be >= Int32.MaxValue
left: boundPositionVar,
right: MakeLiteral(syntax,
constantValue: ConstantValue.Create(1),
type: intType),
constantValueOpt: null,
methodOpt: null,
constrainedToTypeOpt: null,
resultKind: LookupResultKind.Viable,
type: intType),
type: intType)));
}
private void InstrumentForEachStatementCollectionVarDeclaration(BoundForEachStatement original, [NotNullIfNotNull("collectionVarDecl")] ref BoundStatement? collectionVarDecl)
{
if (this.Instrument)
{
collectionVarDecl = _instrumenter.InstrumentForEachStatementCollectionVarDeclaration(original, collectionVarDecl);
}
}
private void InstrumentForEachStatementIterationVarDeclaration(BoundForEachStatement original, ref BoundStatement iterationVarDecl)
{
if (this.Instrument)
{
CommonForEachStatementSyntax forEachSyntax = (CommonForEachStatementSyntax)original.Syntax;
if (forEachSyntax is ForEachVariableStatementSyntax)
{
iterationVarDecl = _instrumenter.InstrumentForEachStatementDeconstructionVariablesDeclaration(original, iterationVarDecl);
}
else
{
iterationVarDecl = _instrumenter.InstrumentForEachStatementIterationVarDeclaration(original, iterationVarDecl);
}
}
}
private void InstrumentForEachStatement(BoundForEachStatement original, ref BoundStatement result)
{
if (this.Instrument)
{
result = _instrumenter.InstrumentForEachStatement(original, result);
}
}
/// <summary>
/// Produce a while(true) loop
///
/// <![CDATA[
/// still-true:
/// /* body */
/// goto still-true;
/// ]]>
/// </summary>
private BoundStatement MakeWhileTrueLoop(BoundForEachStatement loop, BoundBlock body)
{
Debug.Assert(loop.EnumeratorInfoOpt is { IsAsync: true });
SyntaxNode syntax = loop.Syntax;
GeneratedLabelSymbol startLabel = new GeneratedLabelSymbol("still-true");
BoundStatement startLabelStatement = new BoundLabelStatement(syntax, startLabel);
if (this.Instrument)
{
startLabelStatement = BoundSequencePoint.CreateHidden(startLabelStatement);
}
// still-true:
// /* body */
// goto still-true;
return BoundStatementList.Synthesized(syntax, hasErrors: false,
startLabelStatement,
body,
new BoundGotoStatement(syntax, startLabel));
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Features/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.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.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.DocumentChanges
{
public partial class DocumentChangesTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task DocumentChanges_EndToEnd()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts());
await DidOpen(testLspServer, locationTyped.Uri);
Assert.Single(testLspServer.GetQueueAccessor().GetTrackedTexts());
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().Single();
Assert.Equal(documentText, document.ToString());
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"));
document = testLspServer.GetQueueAccessor().GetTrackedTexts().Single();
Assert.Equal(expected, document.ToString());
await DidClose(testLspServer, locationTyped.Uri);
Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts());
}
}
[Fact]
public async Task DidOpen_DocumentIsTracked()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault();
Assert.NotNull(document);
Assert.Equal(documentText, document.ToString());
}
}
[Fact]
public async Task MultipleDidOpen_Errors()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await Assert.ThrowsAsync<InvalidOperationException>(() => DidOpen(testLspServer, locationTyped.Uri));
}
}
[Fact]
public async Task DidCloseWithoutDidOpen_Errors()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await Assert.ThrowsAsync<InvalidOperationException>(() => DidClose(testLspServer, locationTyped.Uri));
}
}
[Fact]
public async Task DidChangeWithoutDidOpen_Errors()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await Assert.ThrowsAsync<InvalidOperationException>(() => DidChange(testLspServer, locationTyped.Uri, (0, 0, "goo")));
}
}
[Fact]
public async Task DidClose_StopsTrackingDocument()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidClose(testLspServer, locationTyped.Uri);
Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts());
}
}
[Fact]
public async Task DidChange_AppliesChanges()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
}
}";
var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"));
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault();
Assert.NotNull(document);
Assert.Equal(expected, document.ToString());
}
}
[Fact]
public async Task DidChange_DoesntUpdateWorkspace()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"));
var documentTextFromWorkspace = (await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync()).ToString();
Assert.NotNull(documentTextFromWorkspace);
Assert.Equal(documentText, documentTextFromWorkspace);
// Just to ensure this test breaks if didChange stops working for some reason
Assert.NotEqual(expected, documentTextFromWorkspace);
}
}
[Fact]
public async Task DidChange_MultipleChanges()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
// this builds on that
}
}";
var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"), (5, 0, " // this builds on that\r\n"));
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault();
Assert.NotNull(document);
Assert.Equal(expected, document.ToString());
}
}
[Fact]
public async Task DidChange_MultipleRequests()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
// this builds on that
}
}";
var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"));
await DidChange(testLspServer, locationTyped.Uri, (5, 0, " // this builds on that\r\n"));
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault();
Assert.NotNull(document);
Assert.Equal(expected, document.ToString());
}
}
private async Task<(TestLspServer, LSP.Location, string)> GetTestLspServerAndLocationAsync(string source)
{
var testLspServer = CreateTestLspServer(source, out var locations);
var locationTyped = locations["type"].Single();
var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync();
return (testLspServer, locationTyped, documentText.ToString());
}
private static Task DidOpen(TestLspServer testLspServer, Uri uri) => testLspServer.OpenDocumentAsync(uri);
private static async Task DidChange(TestLspServer testLspServer, Uri uri, params (int line, int column, string text)[] changes)
=> await testLspServer.InsertTextAsync(uri, changes);
private static async Task DidClose(TestLspServer testLspServer, Uri uri) => await testLspServer.CloseDocumentAsync(uri);
}
}
| // Licensed to the .NET Foundation under one or more 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.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.DocumentChanges
{
public partial class DocumentChangesTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task DocumentChanges_EndToEnd()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts());
await DidOpen(testLspServer, locationTyped.Uri);
Assert.Single(testLspServer.GetQueueAccessor().GetTrackedTexts());
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().Single();
Assert.Equal(documentText, document.ToString());
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"));
document = testLspServer.GetQueueAccessor().GetTrackedTexts().Single();
Assert.Equal(expected, document.ToString());
await DidClose(testLspServer, locationTyped.Uri);
Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts());
}
}
[Fact]
public async Task DidOpen_DocumentIsTracked()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault();
Assert.NotNull(document);
Assert.Equal(documentText, document.ToString());
}
}
[Fact]
public async Task MultipleDidOpen_Errors()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await Assert.ThrowsAsync<InvalidOperationException>(() => DidOpen(testLspServer, locationTyped.Uri));
}
}
[Fact]
public async Task DidCloseWithoutDidOpen_Errors()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await Assert.ThrowsAsync<InvalidOperationException>(() => DidClose(testLspServer, locationTyped.Uri));
}
}
[Fact]
public async Task DidChangeWithoutDidOpen_Errors()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await Assert.ThrowsAsync<InvalidOperationException>(() => DidChange(testLspServer, locationTyped.Uri, (0, 0, "goo")));
}
}
[Fact]
public async Task DidClose_StopsTrackingDocument()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidClose(testLspServer, locationTyped.Uri);
Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts());
}
}
[Fact]
public async Task DidChange_AppliesChanges()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
}
}";
var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"));
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault();
Assert.NotNull(document);
Assert.Equal(expected, document.ToString());
}
}
[Fact]
public async Task DidChange_DoesntUpdateWorkspace()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
}
}";
var (testLspServer, locationTyped, documentText) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"));
var documentTextFromWorkspace = (await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync()).ToString();
Assert.NotNull(documentTextFromWorkspace);
Assert.Equal(documentText, documentTextFromWorkspace);
// Just to ensure this test breaks if didChange stops working for some reason
Assert.NotEqual(expected, documentTextFromWorkspace);
}
}
[Fact]
public async Task DidChange_MultipleChanges()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
// this builds on that
}
}";
var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"), (5, 0, " // this builds on that\r\n"));
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault();
Assert.NotNull(document);
Assert.Equal(expected, document.ToString());
}
}
[Fact]
public async Task DidChange_MultipleRequests()
{
var source =
@"class A
{
void M()
{
{|type:|}
}
}";
var expected =
@"class A
{
void M()
{
// hi there
// this builds on that
}
}";
var (testLspServer, locationTyped, _) = await GetTestLspServerAndLocationAsync(source);
using (testLspServer)
{
await DidOpen(testLspServer, locationTyped.Uri);
await DidChange(testLspServer, locationTyped.Uri, (4, 8, "// hi there"));
await DidChange(testLspServer, locationTyped.Uri, (5, 0, " // this builds on that\r\n"));
var document = testLspServer.GetQueueAccessor().GetTrackedTexts().FirstOrDefault();
Assert.NotNull(document);
Assert.Equal(expected, document.ToString());
}
}
private async Task<(TestLspServer, LSP.Location, string)> GetTestLspServerAndLocationAsync(string source)
{
var testLspServer = CreateTestLspServer(source, out var locations);
var locationTyped = locations["type"].Single();
var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync();
return (testLspServer, locationTyped, documentText.ToString());
}
private static Task DidOpen(TestLspServer testLspServer, Uri uri) => testLspServer.OpenDocumentAsync(uri);
private static async Task DidChange(TestLspServer testLspServer, Uri uri, params (int line, int column, string text)[] changes)
=> await testLspServer.InsertTextAsync(uri, changes);
private static async Task DidClose(TestLspServer testLspServer, Uri uri) => await testLspServer.CloseDocumentAsync(uri);
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Test/PdbUtilities/Shared/DateTimeUtilities.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;
namespace Roslyn.Utilities
{
internal static class DateTimeUtilities
{
// From DateTime.cs.
private const long TicksMask = 0x3FFFFFFFFFFFFFFF;
internal static DateTime ToDateTime(double raw)
{
// This mechanism for getting the tick count from the underlying ulong field is copied
// from System.DateTime.InternalTicks (ndp\clr\src\BCL\System\DateTime.cs).
var tickCount = BitConverter.DoubleToInt64Bits(raw) & TicksMask;
return new DateTime(tickCount);
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Roslyn.Utilities
{
internal static class DateTimeUtilities
{
// From DateTime.cs.
private const long TicksMask = 0x3FFFFFFFFFFFFFFF;
internal static DateTime ToDateTime(double raw)
{
// This mechanism for getting the tick count from the underlying ulong field is copied
// from System.DateTime.InternalTicks (ndp\clr\src\BCL\System\DateTime.cs).
var tickCount = BitConverter.DoubleToInt64Bits(raw) & TicksMask;
return new DateTime(tickCount);
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/ExtractInterfaceDialog_OutOfProc.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.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
/// <summary>
/// Handles interaction with the Extract Interface Dialog.
/// </summary>
public class ExtractInterfaceDialog_OutOfProc : OutOfProcComponent
{
private readonly ExtractInterfaceDialog_InProc _inProc;
public ExtractInterfaceDialog_OutOfProc(VisualStudioInstance visualStudioInstance)
: base(visualStudioInstance)
{
_inProc = CreateInProcComponent<ExtractInterfaceDialog_InProc>(visualStudioInstance);
}
/// <summary>
/// Verifies that the Extract Interface dialog is currently open.
/// </summary>
public void VerifyOpen()
=> _inProc.VerifyOpen();
/// <summary>
/// Verifies that the Extract Interface dialog is currently closed.
/// </summary>
public void VerifyClosed()
=> _inProc.VerifyClosed();
public bool CloseWindow()
=> _inProc.CloseWindow();
/// <summary>
/// Clicks the "OK" button and waits for the Extract Interface operation to complete.
/// </summary>
public void ClickOK()
{
_inProc.ClickOK();
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
}
/// <summary>
/// Clicks the "Cancel" button and waits for the Extract Interface operation to complete.
/// </summary>
public void ClickCancel()
{
_inProc.ClickCancel();
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
}
/// <summary>
/// Returns the name of the generated file that will contain the interface.
/// </summary>
public string GetTargetFileName()
=> _inProc.GetTargetFileName();
/// <summary>
/// Gets the set of members that are currently checked.
/// </summary>
public string[] GetSelectedItems()
=> _inProc.GetSelectedItems();
/// <summary>
/// Clicks the "Deselect All" button.
/// </summary>
public void ClickDeselectAll()
=> _inProc.ClickDeselectAll();
/// <summary>
/// Clicks the "Select All" button.
/// </summary>
public void ClickSelectAll()
=> _inProc.ClickSelectAll();
public void SelectSameFile()
=> _inProc.SelectSameFile();
/// <summary>
/// Clicks the checkbox on the given item, cycling it from on to off or from off to on.
/// </summary>
/// <param name="item"></param>
public void ToggleItem(string item)
=> _inProc.ToggleItem(item);
}
}
| // Licensed to the .NET Foundation under one or more 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.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
/// <summary>
/// Handles interaction with the Extract Interface Dialog.
/// </summary>
public class ExtractInterfaceDialog_OutOfProc : OutOfProcComponent
{
private readonly ExtractInterfaceDialog_InProc _inProc;
public ExtractInterfaceDialog_OutOfProc(VisualStudioInstance visualStudioInstance)
: base(visualStudioInstance)
{
_inProc = CreateInProcComponent<ExtractInterfaceDialog_InProc>(visualStudioInstance);
}
/// <summary>
/// Verifies that the Extract Interface dialog is currently open.
/// </summary>
public void VerifyOpen()
=> _inProc.VerifyOpen();
/// <summary>
/// Verifies that the Extract Interface dialog is currently closed.
/// </summary>
public void VerifyClosed()
=> _inProc.VerifyClosed();
public bool CloseWindow()
=> _inProc.CloseWindow();
/// <summary>
/// Clicks the "OK" button and waits for the Extract Interface operation to complete.
/// </summary>
public void ClickOK()
{
_inProc.ClickOK();
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
}
/// <summary>
/// Clicks the "Cancel" button and waits for the Extract Interface operation to complete.
/// </summary>
public void ClickCancel()
{
_inProc.ClickCancel();
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
}
/// <summary>
/// Returns the name of the generated file that will contain the interface.
/// </summary>
public string GetTargetFileName()
=> _inProc.GetTargetFileName();
/// <summary>
/// Gets the set of members that are currently checked.
/// </summary>
public string[] GetSelectedItems()
=> _inProc.GetSelectedItems();
/// <summary>
/// Clicks the "Deselect All" button.
/// </summary>
public void ClickDeselectAll()
=> _inProc.ClickDeselectAll();
/// <summary>
/// Clicks the "Select All" button.
/// </summary>
public void ClickSelectAll()
=> _inProc.ClickSelectAll();
public void SelectSameFile()
=> _inProc.SelectSameFile();
/// <summary>
/// Clicks the checkbox on the given item, cycling it from on to off or from off to on.
/// </summary>
/// <param name="item"></param>
public void ToggleItem(string item)
=> _inProc.ToggleItem(item);
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/VisualBasic/Portable/Binding/ForEachEnumeratorInfo.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.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Holds all information needed to rewrite a bound for each node.
''' </summary>
Friend NotInheritable Class ForEachEnumeratorInfo
''' <summary>
''' A bound call to the GetEnumerator method.
''' </summary>
''' <remarks></remarks>
Public ReadOnly GetEnumerator As BoundExpression
''' <summary>
''' A bound call to the MoveNext method.
''' </summary>
''' <remarks></remarks>
Public ReadOnly MoveNext As BoundExpression
''' <summary>
''' A bound access to the Current property.
''' </summary>
''' <remarks></remarks>
Public ReadOnly Current As BoundExpression
''' <summary>
''' Element type of the collection.
''' </summary>
''' <remarks></remarks>
Public ReadOnly ElementType As TypeSymbol
''' <summary>
''' True is the enumerator needs or may need (in case of IEnumerator) to be disposed.
''' </summary>
''' <remarks></remarks>
Public ReadOnly NeedToDispose As Boolean
''' <summary>
''' True if the enumerator is, inherits from or implements IDisposable.
''' </summary>
''' <remarks></remarks>
Public ReadOnly IsOrInheritsFromOrImplementsIDisposable As Boolean
''' <summary>
''' The condition that is used to determine whether to call Dispose or not (contains a placeholder).
''' </summary>
''' <remarks></remarks>
Public ReadOnly DisposeCondition As BoundExpression
''' <summary>
''' The conversion of the enumerator to the target type on which Dispose is called
''' (contains a placeholder).
''' </summary>
''' <remarks></remarks>
Public ReadOnly DisposeCast As BoundExpression
''' <summary>
''' The conversion of the return value of the current call to the type of the control variable
''' (contains a placeholder).
''' </summary>
''' <remarks></remarks>
Public ReadOnly CurrentConversion As BoundExpression
''' <summary>
''' Placeholder for the bound enumerator local.
''' </summary>
''' <remarks></remarks>
Public ReadOnly EnumeratorPlaceholder As BoundLValuePlaceholder
''' <summary>
''' Placeholder for the bound call to the get_Current method.
''' </summary>
''' <remarks></remarks>
Public ReadOnly CurrentPlaceholder As BoundRValuePlaceholder
''' <summary>
''' Placeholder for the collection; used only when the collection's type
''' is not an one dimensional array or string.
''' </summary>
''' <remarks></remarks>
Public ReadOnly CollectionPlaceholder As BoundRValuePlaceholder
''' <summary>
''' Initializes a new instance of the <see cref="ForEachEnumeratorInfo" /> class.
''' </summary>
''' <param name="getEnumerator">A bound call to the GetEnumerator method.</param>
''' <param name="moveNext">A bound call to the MoveNext method.</param>
''' <param name="current">A bound access to the Current property.</param>
''' <param name="elementType">An element type.</param>
''' <param name="needToDispose">if set to <c>true</c> the enumerator needs to be disposed.</param>
''' <param name="isOrInheritsFromOrImplementsIDisposable">if set to <c>true</c> the enumerator is or inherits from or implements IDisposable.</param>
''' <param name="disposeCondition">The condition whether to call dispose or not.</param>
''' <param name="disposeCast">The conversion of the enumerator to call Dispose on.</param>
''' <param name="currentConversion">The conversion from Current return type to the type of the controlVariable.</param>
''' <param name="enumeratorPlaceholder">The placeholder for the bound enumerator local.</param>
''' <param name="currentPlaceholder">The placeholder for the expression that get's the current value.</param>
''' <param name="collectionPlaceholder">The placeholder for the collection expression.</param>
Public Sub New(
getEnumerator As BoundExpression,
moveNext As BoundExpression,
current As BoundExpression,
elementType As TypeSymbol,
needToDispose As Boolean,
isOrInheritsFromOrImplementsIDisposable As Boolean,
disposeCondition As BoundExpression,
disposeCast As BoundExpression,
currentConversion As BoundExpression,
enumeratorPlaceholder As BoundLValuePlaceholder,
currentPlaceholder As BoundRValuePlaceholder,
collectionPlaceholder As BoundRValuePlaceholder
)
Me.GetEnumerator = getEnumerator
Me.MoveNext = moveNext
Me.Current = current
Me.ElementType = elementType
Me.NeedToDispose = needToDispose
Me.IsOrInheritsFromOrImplementsIDisposable = isOrInheritsFromOrImplementsIDisposable
Me.DisposeCondition = disposeCondition
Me.DisposeCast = disposeCast
Me.CurrentConversion = currentConversion
Me.EnumeratorPlaceholder = enumeratorPlaceholder
Me.CurrentPlaceholder = currentPlaceholder
Me.CollectionPlaceholder = collectionPlaceholder
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 Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Holds all information needed to rewrite a bound for each node.
''' </summary>
Friend NotInheritable Class ForEachEnumeratorInfo
''' <summary>
''' A bound call to the GetEnumerator method.
''' </summary>
''' <remarks></remarks>
Public ReadOnly GetEnumerator As BoundExpression
''' <summary>
''' A bound call to the MoveNext method.
''' </summary>
''' <remarks></remarks>
Public ReadOnly MoveNext As BoundExpression
''' <summary>
''' A bound access to the Current property.
''' </summary>
''' <remarks></remarks>
Public ReadOnly Current As BoundExpression
''' <summary>
''' Element type of the collection.
''' </summary>
''' <remarks></remarks>
Public ReadOnly ElementType As TypeSymbol
''' <summary>
''' True is the enumerator needs or may need (in case of IEnumerator) to be disposed.
''' </summary>
''' <remarks></remarks>
Public ReadOnly NeedToDispose As Boolean
''' <summary>
''' True if the enumerator is, inherits from or implements IDisposable.
''' </summary>
''' <remarks></remarks>
Public ReadOnly IsOrInheritsFromOrImplementsIDisposable As Boolean
''' <summary>
''' The condition that is used to determine whether to call Dispose or not (contains a placeholder).
''' </summary>
''' <remarks></remarks>
Public ReadOnly DisposeCondition As BoundExpression
''' <summary>
''' The conversion of the enumerator to the target type on which Dispose is called
''' (contains a placeholder).
''' </summary>
''' <remarks></remarks>
Public ReadOnly DisposeCast As BoundExpression
''' <summary>
''' The conversion of the return value of the current call to the type of the control variable
''' (contains a placeholder).
''' </summary>
''' <remarks></remarks>
Public ReadOnly CurrentConversion As BoundExpression
''' <summary>
''' Placeholder for the bound enumerator local.
''' </summary>
''' <remarks></remarks>
Public ReadOnly EnumeratorPlaceholder As BoundLValuePlaceholder
''' <summary>
''' Placeholder for the bound call to the get_Current method.
''' </summary>
''' <remarks></remarks>
Public ReadOnly CurrentPlaceholder As BoundRValuePlaceholder
''' <summary>
''' Placeholder for the collection; used only when the collection's type
''' is not an one dimensional array or string.
''' </summary>
''' <remarks></remarks>
Public ReadOnly CollectionPlaceholder As BoundRValuePlaceholder
''' <summary>
''' Initializes a new instance of the <see cref="ForEachEnumeratorInfo" /> class.
''' </summary>
''' <param name="getEnumerator">A bound call to the GetEnumerator method.</param>
''' <param name="moveNext">A bound call to the MoveNext method.</param>
''' <param name="current">A bound access to the Current property.</param>
''' <param name="elementType">An element type.</param>
''' <param name="needToDispose">if set to <c>true</c> the enumerator needs to be disposed.</param>
''' <param name="isOrInheritsFromOrImplementsIDisposable">if set to <c>true</c> the enumerator is or inherits from or implements IDisposable.</param>
''' <param name="disposeCondition">The condition whether to call dispose or not.</param>
''' <param name="disposeCast">The conversion of the enumerator to call Dispose on.</param>
''' <param name="currentConversion">The conversion from Current return type to the type of the controlVariable.</param>
''' <param name="enumeratorPlaceholder">The placeholder for the bound enumerator local.</param>
''' <param name="currentPlaceholder">The placeholder for the expression that get's the current value.</param>
''' <param name="collectionPlaceholder">The placeholder for the collection expression.</param>
Public Sub New(
getEnumerator As BoundExpression,
moveNext As BoundExpression,
current As BoundExpression,
elementType As TypeSymbol,
needToDispose As Boolean,
isOrInheritsFromOrImplementsIDisposable As Boolean,
disposeCondition As BoundExpression,
disposeCast As BoundExpression,
currentConversion As BoundExpression,
enumeratorPlaceholder As BoundLValuePlaceholder,
currentPlaceholder As BoundRValuePlaceholder,
collectionPlaceholder As BoundRValuePlaceholder
)
Me.GetEnumerator = getEnumerator
Me.MoveNext = moveNext
Me.Current = current
Me.ElementType = elementType
Me.NeedToDispose = needToDispose
Me.IsOrInheritsFromOrImplementsIDisposable = isOrInheritsFromOrImplementsIDisposable
Me.DisposeCondition = disposeCondition
Me.DisposeCast = disposeCast
Me.CurrentConversion = currentConversion
Me.EnumeratorPlaceholder = enumeratorPlaceholder
Me.CurrentPlaceholder = currentPlaceholder
Me.CollectionPlaceholder = collectionPlaceholder
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/Test/Core/Platform/CoreClr/CoreCLRRuntimeEnvironmentFactory.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
#if NETCOREAPP
using System;
using System.Collections.Generic;
using Roslyn.Test.Utilities;
namespace Roslyn.Test.Utilities.CoreClr
{
public sealed class CoreCLRRuntimeEnvironmentFactory : IRuntimeEnvironmentFactory
{
public IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies)
=> new CoreCLRRuntimeEnvironment(additionalDependencies);
}
}
#endif
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#if NETCOREAPP
using System;
using System.Collections.Generic;
using Roslyn.Test.Utilities;
namespace Roslyn.Test.Utilities.CoreClr
{
public sealed class CoreCLRRuntimeEnvironmentFactory : IRuntimeEnvironmentFactory
{
public IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies)
=> new CoreCLRRuntimeEnvironment(additionalDependencies);
}
}
#endif
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Features/Core/Portable/NavigateTo/NavigateToMatchKind.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal enum NavigateToMatchKind
{
Exact = 0,
Prefix = 1,
Substring = 2,
Regular = 3,
None = 4,
CamelCaseExact = 5,
CamelCasePrefix = 6,
CamelCaseNonContiguousPrefix = 7,
CamelCaseSubstring = 8,
CamelCaseNonContiguousSubstring = 9,
Fuzzy = 10
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal enum NavigateToMatchKind
{
Exact = 0,
Prefix = 1,
Substring = 2,
Regular = 3,
None = 4,
CamelCaseExact = 5,
CamelCasePrefix = 6,
CamelCaseNonContiguousPrefix = 7,
CamelCaseSubstring = 8,
CamelCaseNonContiguousSubstring = 9,
Fuzzy = 10
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/AbstractProject.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.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
using Workspace = Microsoft.CodeAnalysis.Workspace;
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal abstract partial class AbstractProject : ForegroundThreadAffinitizedObject, IVisualStudioHostProject
{
internal const string ProjectGuidPropertyName = "ProjectGuid";
private string _displayName;
private readonly VisualStudioWorkspace _visualStudioWorkspace;
public AbstractProject(
VisualStudioProjectTracker projectTracker,
Func<ProjectId, IVsReportExternalErrors> reportExternalErrorCreatorOpt,
string projectSystemName,
string projectFilePath,
IVsHierarchy hierarchy,
string language,
Guid projectGuid,
#pragma warning disable IDE0060 // Remove unused parameter - not used, but left for compat with TypeScript
IServiceProvider serviceProviderNotUsed,
#pragma warning restore IDE0060 // Remove unused parameter
VisualStudioWorkspaceImpl workspace,
HostDiagnosticUpdateSource hostDiagnosticUpdateSourceOpt,
#pragma warning disable IDE0060 // Remove unused parameter - not used, but left for compat
ICommandLineParserService commandLineParserServiceOpt = null)
#pragma warning restore IDE0060 // Remove unused parameter
: base(projectTracker.ThreadingContext)
{
Hierarchy = hierarchy;
Guid = projectGuid;
Language = language;
ProjectTracker = projectTracker;
_visualStudioWorkspace = workspace;
this.DisplayName = hierarchy != null && hierarchy.TryGetName(out var name) ? name : projectSystemName;
ProjectSystemName = projectSystemName;
HostDiagnosticUpdateSource = hostDiagnosticUpdateSourceOpt;
// Set the default value for last design time build result to be true, until the project system lets us know that it failed.
LastDesignTimeBuildSucceeded = true;
if (projectFilePath != null && File.Exists(projectFilePath))
{
ProjectFilePath = projectFilePath;
}
if (ProjectFilePath != null)
{
Version = VersionStamp.Create(File.GetLastWriteTimeUtc(ProjectFilePath));
}
else
{
Version = VersionStamp.Create();
}
if (reportExternalErrorCreatorOpt != null)
{
ExternalErrorReporter = reportExternalErrorCreatorOpt(Id);
}
}
/// <summary>
/// A full path to the project bin output binary, or null if the project doesn't have an bin output binary.
/// </summary>
// FYI: this can't be made virtual because there are calls to this where a 'call' instead of 'callvirt' is being used to call
// the method.
internal string BinOutputPath => GetOutputFilePath();
protected virtual string GetOutputFilePath()
=> VisualStudioProject.OutputFilePath;
protected IVsReportExternalErrors ExternalErrorReporter { get; }
internal HostDiagnosticUpdateSource HostDiagnosticUpdateSource { get; }
public virtual ProjectId Id => VisualStudioProject?.Id ?? ExplicitId;
internal ProjectId ExplicitId { get; set; }
public string Language { get; }
public VisualStudioProjectTracker ProjectTracker { get; }
/// <summary>
/// The <see cref="IVsHierarchy"/> for this project. NOTE: May be null in Deferred Project Load cases.
/// </summary>
public IVsHierarchy Hierarchy { get; }
/// <summary>
/// Guid of the project
///
/// it is not readonly since it can be changed while loading project
/// </summary>
public Guid Guid { get; protected set; }
public Workspace Workspace { get; }
public VersionStamp Version { get; }
public IProjectCodeModel ProjectCodeModel { get; protected set; }
/// <summary>
/// The containing directory of the project. Null if none exists (consider Venus.)
/// </summary>
protected string ContainingDirectoryPathOpt
{
get
{
var projectFilePath = this.ProjectFilePath;
if (projectFilePath != null)
{
return Path.GetDirectoryName(projectFilePath);
}
else
{
return null;
}
}
}
/// <summary>
/// The full path of the project file. Null if none exists (consider Venus.)
/// Note that the project file path might change with project file rename.
/// If you need the folder of the project, just use <see cref="ContainingDirectoryPathOpt" /> which doesn't change for a project.
/// </summary>
public string ProjectFilePath { get; private set; }
/// <summary>
/// The public display name of the project. This name is not unique and may be shared
/// between multiple projects, especially in cases like Venus where the intellisense
/// projects will match the name of their logical parent project.
/// </summary>
public string DisplayName
{
get => _displayName;
set
{
_displayName = value;
UpdateVisualStudioProjectProperties();
}
}
internal string AssemblyName { get; private set; }
/// <summary>
/// The name of the project according to the project system. In "regular" projects this is
/// equivalent to <see cref="DisplayName"/>, but in Venus cases these will differ. The
/// ProjectSystemName is the 2_Default.aspx project name, whereas the regular display name
/// matches the display name of the project the user actually sees in the solution explorer.
/// These can be assumed to be unique within the Visual Studio workspace.
/// </summary>
public string ProjectSystemName { get; }
/// <summary>
/// Flag indicating if the latest design time build has succeeded for current project state.
/// </summary>
/// <remarks>Default value is true.</remarks>
protected bool LastDesignTimeBuildSucceeded { get; private set; }
#nullable enable
public VisualStudioProject? VisualStudioProject { get; internal set; }
#nullable disable
internal void UpdateVisualStudioProjectProperties()
{
if (VisualStudioProject != null)
{
VisualStudioProject.DisplayName = this.DisplayName;
}
}
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
protected void UpdateProjectDisplayName(string displayName)
=> this.DisplayName = displayName;
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal void AddDocument(IVisualStudioHostDocument document, bool isCurrentContext, bool hookupHandlers)
{
var shimDocument = (DocumentProvider.ShimDocument)document;
VisualStudioProject.AddSourceFile(shimDocument.FilePath, shimDocument.SourceCodeKind);
}
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal void RemoveDocument(IVisualStudioHostDocument document)
{
var containedDocument = ContainedDocument.TryGetContainedDocument(document.Id);
if (containedDocument != null)
{
VisualStudioProject.RemoveSourceTextContainer(containedDocument.SubjectBuffer.AsTextContainer());
containedDocument.Dispose();
}
else
{
var shimDocument = (DocumentProvider.ShimDocument)document;
VisualStudioProject.RemoveSourceFile(shimDocument.FilePath);
}
}
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal IVisualStudioHostDocument GetCurrentDocumentFromPath(string filePath)
{
var id = _visualStudioWorkspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath).FirstOrDefault(d => d.ProjectId == Id);
if (id != null)
{
return new DocumentProvider.ShimDocument(this, id, filePath);
}
else
{
return null;
}
}
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal ImmutableArray<IVisualStudioHostDocument> GetCurrentDocuments()
{
return _visualStudioWorkspace.CurrentSolution.GetProject(Id).Documents.SelectAsArray(
d => (IVisualStudioHostDocument)new DocumentProvider.ShimDocument(this, d.Id, d.FilePath, d.SourceCodeKind));
}
}
}
| // Licensed to the .NET Foundation under one or more 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.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
using Workspace = Microsoft.CodeAnalysis.Workspace;
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal abstract partial class AbstractProject : ForegroundThreadAffinitizedObject, IVisualStudioHostProject
{
internal const string ProjectGuidPropertyName = "ProjectGuid";
private string _displayName;
private readonly VisualStudioWorkspace _visualStudioWorkspace;
public AbstractProject(
VisualStudioProjectTracker projectTracker,
Func<ProjectId, IVsReportExternalErrors> reportExternalErrorCreatorOpt,
string projectSystemName,
string projectFilePath,
IVsHierarchy hierarchy,
string language,
Guid projectGuid,
#pragma warning disable IDE0060 // Remove unused parameter - not used, but left for compat with TypeScript
IServiceProvider serviceProviderNotUsed,
#pragma warning restore IDE0060 // Remove unused parameter
VisualStudioWorkspaceImpl workspace,
HostDiagnosticUpdateSource hostDiagnosticUpdateSourceOpt,
#pragma warning disable IDE0060 // Remove unused parameter - not used, but left for compat
ICommandLineParserService commandLineParserServiceOpt = null)
#pragma warning restore IDE0060 // Remove unused parameter
: base(projectTracker.ThreadingContext)
{
Hierarchy = hierarchy;
Guid = projectGuid;
Language = language;
ProjectTracker = projectTracker;
_visualStudioWorkspace = workspace;
this.DisplayName = hierarchy != null && hierarchy.TryGetName(out var name) ? name : projectSystemName;
ProjectSystemName = projectSystemName;
HostDiagnosticUpdateSource = hostDiagnosticUpdateSourceOpt;
// Set the default value for last design time build result to be true, until the project system lets us know that it failed.
LastDesignTimeBuildSucceeded = true;
if (projectFilePath != null && File.Exists(projectFilePath))
{
ProjectFilePath = projectFilePath;
}
if (ProjectFilePath != null)
{
Version = VersionStamp.Create(File.GetLastWriteTimeUtc(ProjectFilePath));
}
else
{
Version = VersionStamp.Create();
}
if (reportExternalErrorCreatorOpt != null)
{
ExternalErrorReporter = reportExternalErrorCreatorOpt(Id);
}
}
/// <summary>
/// A full path to the project bin output binary, or null if the project doesn't have an bin output binary.
/// </summary>
// FYI: this can't be made virtual because there are calls to this where a 'call' instead of 'callvirt' is being used to call
// the method.
internal string BinOutputPath => GetOutputFilePath();
protected virtual string GetOutputFilePath()
=> VisualStudioProject.OutputFilePath;
protected IVsReportExternalErrors ExternalErrorReporter { get; }
internal HostDiagnosticUpdateSource HostDiagnosticUpdateSource { get; }
public virtual ProjectId Id => VisualStudioProject?.Id ?? ExplicitId;
internal ProjectId ExplicitId { get; set; }
public string Language { get; }
public VisualStudioProjectTracker ProjectTracker { get; }
/// <summary>
/// The <see cref="IVsHierarchy"/> for this project. NOTE: May be null in Deferred Project Load cases.
/// </summary>
public IVsHierarchy Hierarchy { get; }
/// <summary>
/// Guid of the project
///
/// it is not readonly since it can be changed while loading project
/// </summary>
public Guid Guid { get; protected set; }
public Workspace Workspace { get; }
public VersionStamp Version { get; }
public IProjectCodeModel ProjectCodeModel { get; protected set; }
/// <summary>
/// The containing directory of the project. Null if none exists (consider Venus.)
/// </summary>
protected string ContainingDirectoryPathOpt
{
get
{
var projectFilePath = this.ProjectFilePath;
if (projectFilePath != null)
{
return Path.GetDirectoryName(projectFilePath);
}
else
{
return null;
}
}
}
/// <summary>
/// The full path of the project file. Null if none exists (consider Venus.)
/// Note that the project file path might change with project file rename.
/// If you need the folder of the project, just use <see cref="ContainingDirectoryPathOpt" /> which doesn't change for a project.
/// </summary>
public string ProjectFilePath { get; private set; }
/// <summary>
/// The public display name of the project. This name is not unique and may be shared
/// between multiple projects, especially in cases like Venus where the intellisense
/// projects will match the name of their logical parent project.
/// </summary>
public string DisplayName
{
get => _displayName;
set
{
_displayName = value;
UpdateVisualStudioProjectProperties();
}
}
internal string AssemblyName { get; private set; }
/// <summary>
/// The name of the project according to the project system. In "regular" projects this is
/// equivalent to <see cref="DisplayName"/>, but in Venus cases these will differ. The
/// ProjectSystemName is the 2_Default.aspx project name, whereas the regular display name
/// matches the display name of the project the user actually sees in the solution explorer.
/// These can be assumed to be unique within the Visual Studio workspace.
/// </summary>
public string ProjectSystemName { get; }
/// <summary>
/// Flag indicating if the latest design time build has succeeded for current project state.
/// </summary>
/// <remarks>Default value is true.</remarks>
protected bool LastDesignTimeBuildSucceeded { get; private set; }
#nullable enable
public VisualStudioProject? VisualStudioProject { get; internal set; }
#nullable disable
internal void UpdateVisualStudioProjectProperties()
{
if (VisualStudioProject != null)
{
VisualStudioProject.DisplayName = this.DisplayName;
}
}
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
protected void UpdateProjectDisplayName(string displayName)
=> this.DisplayName = displayName;
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal void AddDocument(IVisualStudioHostDocument document, bool isCurrentContext, bool hookupHandlers)
{
var shimDocument = (DocumentProvider.ShimDocument)document;
VisualStudioProject.AddSourceFile(shimDocument.FilePath, shimDocument.SourceCodeKind);
}
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal void RemoveDocument(IVisualStudioHostDocument document)
{
var containedDocument = ContainedDocument.TryGetContainedDocument(document.Id);
if (containedDocument != null)
{
VisualStudioProject.RemoveSourceTextContainer(containedDocument.SubjectBuffer.AsTextContainer());
containedDocument.Dispose();
}
else
{
var shimDocument = (DocumentProvider.ShimDocument)document;
VisualStudioProject.RemoveSourceFile(shimDocument.FilePath);
}
}
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal IVisualStudioHostDocument GetCurrentDocumentFromPath(string filePath)
{
var id = _visualStudioWorkspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath).FirstOrDefault(d => d.ProjectId == Id);
if (id != null)
{
return new DocumentProvider.ShimDocument(this, id, filePath);
}
else
{
return null;
}
}
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal ImmutableArray<IVisualStudioHostDocument> GetCurrentDocuments()
{
return _visualStudioWorkspace.CurrentSolution.GetProject(Id).Documents.SelectAsArray(
d => (IVisualStudioHostDocument)new DocumentProvider.ShimDocument(this, d.Id, d.FilePath, d.SourceCodeKind));
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/WhileLoopKeywordRecommender.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
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "While" keyword at the start of a statement. "While" as a part of a Do statement is handled in
''' the UntilAndWhileKeywordRecommender.
''' </summary>
Friend Class WhileLoopKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsMultiLineStatementContext Then
Return ImmutableArray.Create(New RecommendedKeyword("While", VBFeaturesResources.Runs_a_series_of_statements_as_long_as_a_given_condition_is_true))
End If
' Are we after Exit or Continue?
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
If targetToken.IsKind(SyntaxKind.ExitKeyword, SyntaxKind.ContinueKeyword) AndAlso
context.IsInStatementBlockOfKind(SyntaxKind.WhileBlock) AndAlso
Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then
Return ImmutableArray.Create(New RecommendedKeyword("While",
If(targetToken.IsKind(SyntaxKind.ExitKeyword),
VBFeaturesResources.Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement,
VBFeaturesResources.Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop)))
End If
Return 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
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "While" keyword at the start of a statement. "While" as a part of a Do statement is handled in
''' the UntilAndWhileKeywordRecommender.
''' </summary>
Friend Class WhileLoopKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsMultiLineStatementContext Then
Return ImmutableArray.Create(New RecommendedKeyword("While", VBFeaturesResources.Runs_a_series_of_statements_as_long_as_a_given_condition_is_true))
End If
' Are we after Exit or Continue?
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
If targetToken.IsKind(SyntaxKind.ExitKeyword, SyntaxKind.ContinueKeyword) AndAlso
context.IsInStatementBlockOfKind(SyntaxKind.WhileBlock) AndAlso
Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then
Return ImmutableArray.Create(New RecommendedKeyword("While",
If(targetToken.IsKind(SyntaxKind.ExitKeyword),
VBFeaturesResources.Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement,
VBFeaturesResources.Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop)))
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion
{
/// <summary>
/// csharp automatic line ender command handler
/// </summary>
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(PredefinedCommandHandlerNames.AutomaticLineEnder)]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
internal partial class AutomaticLineEnderCommandHandler : AbstractAutomaticLineEnderCommandHandler
{
private static readonly string s_semicolon = SyntaxFacts.GetText(SyntaxKind.SemicolonToken);
/// <summary>
/// Annotation to locate the open brace token.
/// </summary>
private static readonly SyntaxAnnotation s_openBracePositionAnnotation = new();
/// <summary>
/// Annotation to locate the replacement node(with or without braces).
/// </summary>
private static readonly SyntaxAnnotation s_replacementNodeAnnotation = new();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AutomaticLineEnderCommandHandler(
ITextUndoHistoryRegistry undoRegistry,
IEditorOperationsFactoryService editorOperations)
: base(undoRegistry, editorOperations)
{
}
protected override void NextAction(IEditorOperations editorOperation, Action nextAction)
=> editorOperation.InsertNewLine();
protected override bool TreatAsReturn(Document document, int caretPosition, CancellationToken cancellationToken)
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
var endToken = root.FindToken(caretPosition);
if (endToken.IsMissing)
{
return false;
}
var tokenToLeft = root.FindTokenOnLeftOfPosition(caretPosition);
var startToken = endToken.GetPreviousToken();
// case 1:
// Consider code like so: try {|}
// With auto brace completion on, user types `{` and `Return` in a hurry.
// During typing, it is possible that shift was still down and not released after typing `{`.
// So we've got an unintentional `shift + enter` and also we have nothing to complete this,
// so we put in a newline,
// which generates code like so : try { }
// |
// which is not useful as : try {
// |
// }
// To support this, we treat `shift + enter` like `enter` here.
var afterOpenBrace = startToken.Kind() == SyntaxKind.OpenBraceToken
&& endToken.Kind() == SyntaxKind.CloseBraceToken
&& tokenToLeft == startToken
&& endToken.Parent.IsKind(SyntaxKind.Block)
&& FormattingRangeHelper.AreTwoTokensOnSameLine(startToken, endToken);
return afterOpenBrace;
}
protected override Document FormatAndApplyBasedOnEndToken(Document document, int position, CancellationToken cancellationToken)
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
var endToken = root.FindToken(position);
var span = GetFormattedTextSpan(root, endToken);
if (span == null)
{
return document;
}
var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var changes = Formatter.GetFormattedTextChanges(
root,
new[] { CommonFormattingHelpers.GetFormattingSpan(root, span.Value) },
document.Project.Solution.Workspace,
options,
rules: null, // use default
cancellationToken: cancellationToken);
return document.ApplyTextChanges(changes, cancellationToken);
}
private static TextSpan? GetFormattedTextSpan(SyntaxNode root, SyntaxToken endToken)
{
if (endToken.IsMissing)
{
return null;
}
var ranges = FormattingRangeHelper.FindAppropriateRange(endToken, useDefaultRange: false);
if (ranges == null)
{
return null;
}
var startToken = ranges.Value.Item1;
if (startToken.IsMissing || startToken.Kind() == SyntaxKind.None)
{
return null;
}
return CommonFormattingHelpers.GetFormattingSpan(root, TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End));
}
#region SemicolonAppending
protected override string? GetEndingString(Document document, int position, CancellationToken cancellationToken)
{
// prepare expansive information from document
var tree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken);
var root = tree.GetRoot(cancellationToken);
var text = tree.GetText(cancellationToken);
// Go through the set of owning nodes in leaf to root chain.
foreach (var owningNode in GetOwningNodes(root, position))
{
if (!TryGetLastToken(text, position, owningNode, out var lastToken))
{
// If we can't get last token, there is nothing more to do, just skip
// the other owning nodes and return.
return null;
}
if (!CheckLocation(text, position, owningNode, lastToken))
{
// If we failed this check, we indeed got the intended owner node and
// inserting line ender here would introduce errors.
return null;
}
// so far so good. we only add semi-colon if it makes statement syntax error free
var textToParse = owningNode.NormalizeWhitespace().ToFullString() + s_semicolon;
// currently, Parsing a field is not supported. as a workaround, wrap the field in a type and parse
var node = ParseNode(tree, owningNode, textToParse);
// Insert line ender if we didn't introduce any diagnostics, if not try the next owning node.
if (node != null && !node.ContainsDiagnostics)
{
return s_semicolon;
}
}
return null;
}
private static SyntaxNode? ParseNode(SyntaxTree tree, SyntaxNode owningNode, string textToParse)
=> owningNode switch
{
BaseFieldDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
BaseMethodDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
BasePropertyDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
StatementSyntax => SyntaxFactory.ParseStatement(textToParse, options: (CSharpParseOptions)tree.Options),
UsingDirectiveSyntax => SyntaxFactory.ParseCompilationUnit(textToParse, options: (CSharpParseOptions)tree.Options),
_ => null,
};
/// <summary>
/// wrap field in type
/// </summary>
private static string WrapInType(string textToParse)
=> "class C { " + textToParse + " }";
/// <summary>
/// make sure current location is okay to put semicolon
/// </summary>
private static bool CheckLocation(SourceText text, int position, SyntaxNode owningNode, SyntaxToken lastToken)
{
var line = text.Lines.GetLineFromPosition(position);
// if caret is at the end of the line and containing statement is expression statement
// don't do anything
if (position == line.End && owningNode is ExpressionStatementSyntax)
{
return false;
}
var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken);
// make sure that there is no trailing text after last token on the line if it is not at the end of the line
if (!locatedAtTheEndOfLine)
{
var endingString = text.ToString(TextSpan.FromBounds(lastToken.Span.End, line.End));
if (!string.IsNullOrWhiteSpace(endingString))
{
return false;
}
}
// check whether using has contents
if (owningNode is UsingDirectiveSyntax u && u.Name.IsMissing)
{
return false;
}
// make sure there is no open string literals
var previousToken = lastToken.GetPreviousToken();
if (previousToken.Kind() == SyntaxKind.StringLiteralToken && previousToken.ToString().Last() != '"')
{
return false;
}
if (previousToken.Kind() == SyntaxKind.CharacterLiteralToken && previousToken.ToString().Last() != '\'')
{
return false;
}
// now, check embedded statement case
if (owningNode.IsEmbeddedStatementOwner())
{
var embeddedStatement = owningNode.GetEmbeddedStatement();
if (embeddedStatement == null || embeddedStatement.Span.IsEmpty)
{
return false;
}
}
return true;
}
/// <summary>
/// get last token of the given using/field/statement/expression bodied member if one exists
/// </summary>
private static bool TryGetLastToken(SourceText text, int position, SyntaxNode owningNode, out SyntaxToken lastToken)
{
lastToken = owningNode.GetLastToken(includeZeroWidth: true);
// last token must be on the same line as the caret
var line = text.Lines.GetLineFromPosition(position);
var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken);
if (!locatedAtTheEndOfLine && text.Lines.IndexOf(lastToken.Span.End) != line.LineNumber)
{
return false;
}
// if we already have last semicolon, we don't need to do anything
if (!lastToken.IsMissing && lastToken.Kind() == SyntaxKind.SemicolonToken)
{
return false;
}
return true;
}
/// <summary>
/// check whether the line is located at the end of the line
/// </summary>
private static bool LocatedAtTheEndOfLine(TextLine line, SyntaxToken lastToken)
=> lastToken.IsMissing && lastToken.Span.End == line.EndIncludingLineBreak;
/// <summary>
/// find owning usings/field/statement/expression-bodied member of the given position
/// </summary>
private static IEnumerable<SyntaxNode> GetOwningNodes(SyntaxNode root, int position)
{
// make sure caret position is somewhere we can find a token
var token = root.FindTokenFromEnd(position);
if (token.Kind() == SyntaxKind.None)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
return token.GetAncestors<SyntaxNode>()
.Where(AllowedConstructs)
.Select(OwningNode)
.WhereNotNull();
}
private static bool AllowedConstructs(SyntaxNode n)
=> n is StatementSyntax
or BaseFieldDeclarationSyntax
or UsingDirectiveSyntax
or ArrowExpressionClauseSyntax;
private static SyntaxNode? OwningNode(SyntaxNode n)
=> n is ArrowExpressionClauseSyntax ? n.Parent : n;
#endregion
#region BraceModification
protected override void ModifySelectedNode(
AutomaticLineEnderCommandArgs args,
Document document,
SyntaxNode selectedNode,
bool addBrace,
int caretPosition,
CancellationToken cancellationToken)
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
// Add braces for the selected node
if (addBrace)
{
// For these syntax node, braces pair could be easily added by modify the syntax tree
if (selectedNode is BaseTypeDeclarationSyntax
or BaseMethodDeclarationSyntax
or LocalFunctionStatementSyntax
or FieldDeclarationSyntax
or EventFieldDeclarationSyntax
or AccessorDeclarationSyntax
or ObjectCreationExpressionSyntax
or WhileStatementSyntax
or ForEachStatementSyntax
or ForStatementSyntax
or LockStatementSyntax
or UsingStatementSyntax
or DoStatementSyntax
or IfStatementSyntax
or ElseClauseSyntax)
{
// Add the braces and get the next caretPosition
var (newRoot, nextCaretPosition) = AddBraceToSelectedNode(document, root, selectedNode, args.TextView.Options, cancellationToken);
if (document.Project.Solution.Workspace.TryApplyChanges(document.WithSyntaxRoot(newRoot).Project.Solution))
{
args.TextView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, nextCaretPosition));
}
}
else
{
// For the rest of the syntax node,
// like try statement
// class Bar
// {
// void Main()
// {
// tr$$y
// }
// }
// In this case, the last close brace of 'void Main()' would be thought as a part of the try statement,
// and the last close brace of 'Bar' would be thought as a part of Main()
// So for these case, just find the missing open brace position and directly insert '()' to the document
// 1. Find the position to insert braces.
var insertionPosition = GetBraceInsertionPosition(selectedNode);
// 2. Insert the braces and move caret
InsertBraceAndMoveCaret(args.TextView, document, insertionPosition, cancellationToken);
}
}
else
{
// Remove the braces and get the next caretPosition
var (newRoot, nextCaretPosition) = RemoveBraceFromSelectedNode(
document,
root,
selectedNode,
args.TextView.Options,
cancellationToken);
if (document.Project.Solution.Workspace.TryApplyChanges(document.WithSyntaxRoot(newRoot).Project.Solution))
{
args.TextView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, nextCaretPosition));
}
}
}
private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToSelectedNode(
Document document,
SyntaxNode root,
SyntaxNode selectedNode,
IEditorOptions editorOptions,
CancellationToken cancellationToken)
{
// For these nodes, directly modify the node and replace it.
if (selectedNode is BaseTypeDeclarationSyntax
or BaseMethodDeclarationSyntax
or LocalFunctionStatementSyntax
or FieldDeclarationSyntax
or EventFieldDeclarationSyntax
or AccessorDeclarationSyntax)
{
var newRoot = ReplaceNodeAndFormat(
document,
root,
selectedNode,
WithBraces(selectedNode, editorOptions),
cancellationToken);
// Locate the open brace token, and move the caret after it.
var nextCaretPosition = GetOpenBraceSpanEnd(newRoot);
return (newRoot, nextCaretPosition);
}
// For ObjectCreationExpression, like new List<int>()
// It requires
// 1. Add an initializer to it.
// 2. make sure it has '()' after the type, and if its next token is a missing semicolon, add that semicolon. e.g
// var c = new Obje$$ct() => var c = new Object();
if (selectedNode is ObjectCreationExpressionSyntax objectCreationExpressionNode)
{
var (newNode, oldNode) = ModifyObjectCreationExpressionNode(objectCreationExpressionNode, addOrRemoveInitializer: true, editorOptions);
var newRoot = ReplaceNodeAndFormat(
document,
root,
oldNode,
newNode,
cancellationToken);
// Locate the open brace token, and move the caret after it.
var nextCaretPosition = GetOpenBraceSpanEnd(newRoot);
return (newRoot, nextCaretPosition);
}
// For the embeddedStatementOwner node, like ifStatement/elseClause
// It requires:
// 1. Add a empty block as its statement.
// 2. Handle its previous statement if needed.
// case 1:
// if$$ (true)
// var c = 10;
// =>
// if (true)
// {
// $$
// }
// var c = 10;
// In this case, 'var c = 10;' is considered as the inner statement so we need to move it next to the if Statement
//
// case 2:
// if (true)
// {
// }
// else if$$ (false)
// Print("Bar");
// else
// {
// }
// =>
// if (true)
// {
// }
// else if (false)
// {
// $$
// Print("Bar");
// }
// else
// {
// }
// In this case 'Print("Bar")' is considered as the innerStatement so when we inserted the empty block, we need also insert that
if (selectedNode.IsEmbeddedStatementOwner())
{
return AddBraceToEmbeddedStatementOwner(document, root, selectedNode, editorOptions, cancellationToken);
}
throw ExceptionUtilities.UnexpectedValue(selectedNode);
}
private static (SyntaxNode newRoot, int nextCaretPosition) RemoveBraceFromSelectedNode(
Document document,
SyntaxNode root,
SyntaxNode selectedNode,
IEditorOptions editorOptions,
CancellationToken cancellationToken)
{
// Remove the initializer from ObjectCreationExpression
// Step 1. Remove the initializer
// e.g. var c = new Bar { $$ } => var c = new Bar
//
// Step 2. Add parenthesis
// e.g var c = new Bar => var c = new Bar()
//
// Step 3. Add semicolon if needed
// e.g. var c = new Bar() => var c = new Bar();
if (selectedNode is ObjectCreationExpressionSyntax objectCreationExpressionNode)
{
var (newNode, oldNode) = ModifyObjectCreationExpressionNode(objectCreationExpressionNode, addOrRemoveInitializer: false, editorOptions);
var newRoot = ReplaceNodeAndFormat(
document,
root,
oldNode,
newNode,
cancellationToken);
// Find the replacement node, and move the caret to the end of line (where the last token is)
var replacementNode = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single();
var lastToken = replacementNode.GetLastToken();
var lineEnd = newRoot.GetText().Lines.GetLineFromPosition(lastToken.Span.End).End;
return (newRoot, lineEnd);
}
else
{
// For all the other cases, include
// 1. Property declaration => Field Declaration.
// e.g.
// class Bar
// {
// int Bar {$$}
// }
// =>
// class Bar
// {
// int Bar;
// }
// 2. Event Declaration => Event Field Declaration
// class Bar
// {
// event EventHandler e { $$ }
// }
// =>
// class Bar
// {
// event EventHandler e;
// }
// 3. Accessor
// class Bar
// {
// int Bar
// {
// get { $$ }
// }
// }
// =>
// class Bar
// {
// int Bar
// {
// get;
// }
// }
// Get its no-brace version of node and insert it into the root.
var newRoot = ReplaceNodeAndFormat(
document,
root,
selectedNode,
WithoutBraces(selectedNode),
cancellationToken);
// Locate the replacement node, move the caret to the end.
// e.g.
// class Bar
// {
// event EventHandler e { $$ }
// }
// =>
// class Bar
// {
// event EventHandler e;$$
// }
// and we need to move the caret after semicolon
var nextCaretPosition = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single().GetLastToken().Span.End;
return (newRoot, nextCaretPosition);
}
}
private static int GetOpenBraceSpanEnd(SyntaxNode root)
{
// Use the annotation to find the end of the open brace.
var annotatedOpenBraceToken = root.GetAnnotatedTokens(s_openBracePositionAnnotation).Single();
return annotatedOpenBraceToken.Span.End;
}
private static int GetBraceInsertionPosition(SyntaxNode node)
=> node switch
{
NamespaceDeclarationSyntax => node.GetBraces().openBrace.SpanStart,
IndexerDeclarationSyntax indexerNode => indexerNode.ParameterList.Span.End,
SwitchStatementSyntax switchStatementNode => switchStatementNode.CloseParenToken.Span.End,
TryStatementSyntax tryStatementNode => tryStatementNode.TryKeyword.Span.End,
CatchClauseSyntax catchClauseNode => catchClauseNode.Block.SpanStart,
FinallyClauseSyntax finallyClauseNode => finallyClauseNode.Block.SpanStart,
_ => throw ExceptionUtilities.Unreachable,
};
private static string GetBracePairString(IEditorOptions editorOptions)
=> string.Concat(SyntaxFacts.GetText(SyntaxKind.OpenBraceToken),
editorOptions.GetNewLineCharacter(),
SyntaxFacts.GetText(SyntaxKind.CloseBraceToken));
private void InsertBraceAndMoveCaret(
ITextView textView,
Document document,
int insertionPosition,
CancellationToken cancellationToken)
{
var bracePair = GetBracePairString(textView.Options);
// 1. Insert { }.
var newDocument = document.InsertText(insertionPosition, bracePair, cancellationToken);
// 2. Place caret between the braces.
textView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(textView.TextSnapshot, insertionPosition + 1));
// 3. Format the document using the close brace.
FormatAndApplyBasedOnEndToken(newDocument, insertionPosition + bracePair.Length - 1, cancellationToken);
}
protected override (SyntaxNode selectedNode, bool addBrace)? GetValidNodeToModifyBraces(Document document, int caretPosition, CancellationToken cancellationToken)
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
var token = root.FindTokenOnLeftOfPosition(caretPosition);
if (token.IsKind(SyntaxKind.None))
{
return null;
}
foreach (var node in token.GetAncestors<SyntaxNode>())
{
if (ShouldAddBraces(node, caretPosition))
{
return (selectedNode: node, addBrace: true);
}
if (ShouldRemoveBraces(node, caretPosition))
{
return (selectedNode: node, addBrace: false);
}
}
return null;
}
#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.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion
{
/// <summary>
/// csharp automatic line ender command handler
/// </summary>
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(PredefinedCommandHandlerNames.AutomaticLineEnder)]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
internal partial class AutomaticLineEnderCommandHandler : AbstractAutomaticLineEnderCommandHandler
{
private static readonly string s_semicolon = SyntaxFacts.GetText(SyntaxKind.SemicolonToken);
/// <summary>
/// Annotation to locate the open brace token.
/// </summary>
private static readonly SyntaxAnnotation s_openBracePositionAnnotation = new();
/// <summary>
/// Annotation to locate the replacement node(with or without braces).
/// </summary>
private static readonly SyntaxAnnotation s_replacementNodeAnnotation = new();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AutomaticLineEnderCommandHandler(
ITextUndoHistoryRegistry undoRegistry,
IEditorOperationsFactoryService editorOperations)
: base(undoRegistry, editorOperations)
{
}
protected override void NextAction(IEditorOperations editorOperation, Action nextAction)
=> editorOperation.InsertNewLine();
protected override bool TreatAsReturn(Document document, int caretPosition, CancellationToken cancellationToken)
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
var endToken = root.FindToken(caretPosition);
if (endToken.IsMissing)
{
return false;
}
var tokenToLeft = root.FindTokenOnLeftOfPosition(caretPosition);
var startToken = endToken.GetPreviousToken();
// case 1:
// Consider code like so: try {|}
// With auto brace completion on, user types `{` and `Return` in a hurry.
// During typing, it is possible that shift was still down and not released after typing `{`.
// So we've got an unintentional `shift + enter` and also we have nothing to complete this,
// so we put in a newline,
// which generates code like so : try { }
// |
// which is not useful as : try {
// |
// }
// To support this, we treat `shift + enter` like `enter` here.
var afterOpenBrace = startToken.Kind() == SyntaxKind.OpenBraceToken
&& endToken.Kind() == SyntaxKind.CloseBraceToken
&& tokenToLeft == startToken
&& endToken.Parent.IsKind(SyntaxKind.Block)
&& FormattingRangeHelper.AreTwoTokensOnSameLine(startToken, endToken);
return afterOpenBrace;
}
protected override Document FormatAndApplyBasedOnEndToken(Document document, int position, CancellationToken cancellationToken)
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
var endToken = root.FindToken(position);
var span = GetFormattedTextSpan(root, endToken);
if (span == null)
{
return document;
}
var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var changes = Formatter.GetFormattedTextChanges(
root,
new[] { CommonFormattingHelpers.GetFormattingSpan(root, span.Value) },
document.Project.Solution.Workspace,
options,
rules: null, // use default
cancellationToken: cancellationToken);
return document.ApplyTextChanges(changes, cancellationToken);
}
private static TextSpan? GetFormattedTextSpan(SyntaxNode root, SyntaxToken endToken)
{
if (endToken.IsMissing)
{
return null;
}
var ranges = FormattingRangeHelper.FindAppropriateRange(endToken, useDefaultRange: false);
if (ranges == null)
{
return null;
}
var startToken = ranges.Value.Item1;
if (startToken.IsMissing || startToken.Kind() == SyntaxKind.None)
{
return null;
}
return CommonFormattingHelpers.GetFormattingSpan(root, TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End));
}
#region SemicolonAppending
protected override string? GetEndingString(Document document, int position, CancellationToken cancellationToken)
{
// prepare expansive information from document
var tree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken);
var root = tree.GetRoot(cancellationToken);
var text = tree.GetText(cancellationToken);
// Go through the set of owning nodes in leaf to root chain.
foreach (var owningNode in GetOwningNodes(root, position))
{
if (!TryGetLastToken(text, position, owningNode, out var lastToken))
{
// If we can't get last token, there is nothing more to do, just skip
// the other owning nodes and return.
return null;
}
if (!CheckLocation(text, position, owningNode, lastToken))
{
// If we failed this check, we indeed got the intended owner node and
// inserting line ender here would introduce errors.
return null;
}
// so far so good. we only add semi-colon if it makes statement syntax error free
var textToParse = owningNode.NormalizeWhitespace().ToFullString() + s_semicolon;
// currently, Parsing a field is not supported. as a workaround, wrap the field in a type and parse
var node = ParseNode(tree, owningNode, textToParse);
// Insert line ender if we didn't introduce any diagnostics, if not try the next owning node.
if (node != null && !node.ContainsDiagnostics)
{
return s_semicolon;
}
}
return null;
}
private static SyntaxNode? ParseNode(SyntaxTree tree, SyntaxNode owningNode, string textToParse)
=> owningNode switch
{
BaseFieldDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
BaseMethodDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
BasePropertyDeclarationSyntax => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
StatementSyntax => SyntaxFactory.ParseStatement(textToParse, options: (CSharpParseOptions)tree.Options),
UsingDirectiveSyntax => SyntaxFactory.ParseCompilationUnit(textToParse, options: (CSharpParseOptions)tree.Options),
_ => null,
};
/// <summary>
/// wrap field in type
/// </summary>
private static string WrapInType(string textToParse)
=> "class C { " + textToParse + " }";
/// <summary>
/// make sure current location is okay to put semicolon
/// </summary>
private static bool CheckLocation(SourceText text, int position, SyntaxNode owningNode, SyntaxToken lastToken)
{
var line = text.Lines.GetLineFromPosition(position);
// if caret is at the end of the line and containing statement is expression statement
// don't do anything
if (position == line.End && owningNode is ExpressionStatementSyntax)
{
return false;
}
var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken);
// make sure that there is no trailing text after last token on the line if it is not at the end of the line
if (!locatedAtTheEndOfLine)
{
var endingString = text.ToString(TextSpan.FromBounds(lastToken.Span.End, line.End));
if (!string.IsNullOrWhiteSpace(endingString))
{
return false;
}
}
// check whether using has contents
if (owningNode is UsingDirectiveSyntax u && u.Name.IsMissing)
{
return false;
}
// make sure there is no open string literals
var previousToken = lastToken.GetPreviousToken();
if (previousToken.Kind() == SyntaxKind.StringLiteralToken && previousToken.ToString().Last() != '"')
{
return false;
}
if (previousToken.Kind() == SyntaxKind.CharacterLiteralToken && previousToken.ToString().Last() != '\'')
{
return false;
}
// now, check embedded statement case
if (owningNode.IsEmbeddedStatementOwner())
{
var embeddedStatement = owningNode.GetEmbeddedStatement();
if (embeddedStatement == null || embeddedStatement.Span.IsEmpty)
{
return false;
}
}
return true;
}
/// <summary>
/// get last token of the given using/field/statement/expression bodied member if one exists
/// </summary>
private static bool TryGetLastToken(SourceText text, int position, SyntaxNode owningNode, out SyntaxToken lastToken)
{
lastToken = owningNode.GetLastToken(includeZeroWidth: true);
// last token must be on the same line as the caret
var line = text.Lines.GetLineFromPosition(position);
var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken);
if (!locatedAtTheEndOfLine && text.Lines.IndexOf(lastToken.Span.End) != line.LineNumber)
{
return false;
}
// if we already have last semicolon, we don't need to do anything
if (!lastToken.IsMissing && lastToken.Kind() == SyntaxKind.SemicolonToken)
{
return false;
}
return true;
}
/// <summary>
/// check whether the line is located at the end of the line
/// </summary>
private static bool LocatedAtTheEndOfLine(TextLine line, SyntaxToken lastToken)
=> lastToken.IsMissing && lastToken.Span.End == line.EndIncludingLineBreak;
/// <summary>
/// find owning usings/field/statement/expression-bodied member of the given position
/// </summary>
private static IEnumerable<SyntaxNode> GetOwningNodes(SyntaxNode root, int position)
{
// make sure caret position is somewhere we can find a token
var token = root.FindTokenFromEnd(position);
if (token.Kind() == SyntaxKind.None)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
return token.GetAncestors<SyntaxNode>()
.Where(AllowedConstructs)
.Select(OwningNode)
.WhereNotNull();
}
private static bool AllowedConstructs(SyntaxNode n)
=> n is StatementSyntax
or BaseFieldDeclarationSyntax
or UsingDirectiveSyntax
or ArrowExpressionClauseSyntax;
private static SyntaxNode? OwningNode(SyntaxNode n)
=> n is ArrowExpressionClauseSyntax ? n.Parent : n;
#endregion
#region BraceModification
protected override void ModifySelectedNode(
AutomaticLineEnderCommandArgs args,
Document document,
SyntaxNode selectedNode,
bool addBrace,
int caretPosition,
CancellationToken cancellationToken)
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
// Add braces for the selected node
if (addBrace)
{
// For these syntax node, braces pair could be easily added by modify the syntax tree
if (selectedNode is BaseTypeDeclarationSyntax
or BaseMethodDeclarationSyntax
or LocalFunctionStatementSyntax
or FieldDeclarationSyntax
or EventFieldDeclarationSyntax
or AccessorDeclarationSyntax
or ObjectCreationExpressionSyntax
or WhileStatementSyntax
or ForEachStatementSyntax
or ForStatementSyntax
or LockStatementSyntax
or UsingStatementSyntax
or DoStatementSyntax
or IfStatementSyntax
or ElseClauseSyntax)
{
// Add the braces and get the next caretPosition
var (newRoot, nextCaretPosition) = AddBraceToSelectedNode(document, root, selectedNode, args.TextView.Options, cancellationToken);
if (document.Project.Solution.Workspace.TryApplyChanges(document.WithSyntaxRoot(newRoot).Project.Solution))
{
args.TextView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, nextCaretPosition));
}
}
else
{
// For the rest of the syntax node,
// like try statement
// class Bar
// {
// void Main()
// {
// tr$$y
// }
// }
// In this case, the last close brace of 'void Main()' would be thought as a part of the try statement,
// and the last close brace of 'Bar' would be thought as a part of Main()
// So for these case, just find the missing open brace position and directly insert '()' to the document
// 1. Find the position to insert braces.
var insertionPosition = GetBraceInsertionPosition(selectedNode);
// 2. Insert the braces and move caret
InsertBraceAndMoveCaret(args.TextView, document, insertionPosition, cancellationToken);
}
}
else
{
// Remove the braces and get the next caretPosition
var (newRoot, nextCaretPosition) = RemoveBraceFromSelectedNode(
document,
root,
selectedNode,
args.TextView.Options,
cancellationToken);
if (document.Project.Solution.Workspace.TryApplyChanges(document.WithSyntaxRoot(newRoot).Project.Solution))
{
args.TextView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, nextCaretPosition));
}
}
}
private static (SyntaxNode newRoot, int nextCaretPosition) AddBraceToSelectedNode(
Document document,
SyntaxNode root,
SyntaxNode selectedNode,
IEditorOptions editorOptions,
CancellationToken cancellationToken)
{
// For these nodes, directly modify the node and replace it.
if (selectedNode is BaseTypeDeclarationSyntax
or BaseMethodDeclarationSyntax
or LocalFunctionStatementSyntax
or FieldDeclarationSyntax
or EventFieldDeclarationSyntax
or AccessorDeclarationSyntax)
{
var newRoot = ReplaceNodeAndFormat(
document,
root,
selectedNode,
WithBraces(selectedNode, editorOptions),
cancellationToken);
// Locate the open brace token, and move the caret after it.
var nextCaretPosition = GetOpenBraceSpanEnd(newRoot);
return (newRoot, nextCaretPosition);
}
// For ObjectCreationExpression, like new List<int>()
// It requires
// 1. Add an initializer to it.
// 2. make sure it has '()' after the type, and if its next token is a missing semicolon, add that semicolon. e.g
// var c = new Obje$$ct() => var c = new Object();
if (selectedNode is ObjectCreationExpressionSyntax objectCreationExpressionNode)
{
var (newNode, oldNode) = ModifyObjectCreationExpressionNode(objectCreationExpressionNode, addOrRemoveInitializer: true, editorOptions);
var newRoot = ReplaceNodeAndFormat(
document,
root,
oldNode,
newNode,
cancellationToken);
// Locate the open brace token, and move the caret after it.
var nextCaretPosition = GetOpenBraceSpanEnd(newRoot);
return (newRoot, nextCaretPosition);
}
// For the embeddedStatementOwner node, like ifStatement/elseClause
// It requires:
// 1. Add a empty block as its statement.
// 2. Handle its previous statement if needed.
// case 1:
// if$$ (true)
// var c = 10;
// =>
// if (true)
// {
// $$
// }
// var c = 10;
// In this case, 'var c = 10;' is considered as the inner statement so we need to move it next to the if Statement
//
// case 2:
// if (true)
// {
// }
// else if$$ (false)
// Print("Bar");
// else
// {
// }
// =>
// if (true)
// {
// }
// else if (false)
// {
// $$
// Print("Bar");
// }
// else
// {
// }
// In this case 'Print("Bar")' is considered as the innerStatement so when we inserted the empty block, we need also insert that
if (selectedNode.IsEmbeddedStatementOwner())
{
return AddBraceToEmbeddedStatementOwner(document, root, selectedNode, editorOptions, cancellationToken);
}
throw ExceptionUtilities.UnexpectedValue(selectedNode);
}
private static (SyntaxNode newRoot, int nextCaretPosition) RemoveBraceFromSelectedNode(
Document document,
SyntaxNode root,
SyntaxNode selectedNode,
IEditorOptions editorOptions,
CancellationToken cancellationToken)
{
// Remove the initializer from ObjectCreationExpression
// Step 1. Remove the initializer
// e.g. var c = new Bar { $$ } => var c = new Bar
//
// Step 2. Add parenthesis
// e.g var c = new Bar => var c = new Bar()
//
// Step 3. Add semicolon if needed
// e.g. var c = new Bar() => var c = new Bar();
if (selectedNode is ObjectCreationExpressionSyntax objectCreationExpressionNode)
{
var (newNode, oldNode) = ModifyObjectCreationExpressionNode(objectCreationExpressionNode, addOrRemoveInitializer: false, editorOptions);
var newRoot = ReplaceNodeAndFormat(
document,
root,
oldNode,
newNode,
cancellationToken);
// Find the replacement node, and move the caret to the end of line (where the last token is)
var replacementNode = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single();
var lastToken = replacementNode.GetLastToken();
var lineEnd = newRoot.GetText().Lines.GetLineFromPosition(lastToken.Span.End).End;
return (newRoot, lineEnd);
}
else
{
// For all the other cases, include
// 1. Property declaration => Field Declaration.
// e.g.
// class Bar
// {
// int Bar {$$}
// }
// =>
// class Bar
// {
// int Bar;
// }
// 2. Event Declaration => Event Field Declaration
// class Bar
// {
// event EventHandler e { $$ }
// }
// =>
// class Bar
// {
// event EventHandler e;
// }
// 3. Accessor
// class Bar
// {
// int Bar
// {
// get { $$ }
// }
// }
// =>
// class Bar
// {
// int Bar
// {
// get;
// }
// }
// Get its no-brace version of node and insert it into the root.
var newRoot = ReplaceNodeAndFormat(
document,
root,
selectedNode,
WithoutBraces(selectedNode),
cancellationToken);
// Locate the replacement node, move the caret to the end.
// e.g.
// class Bar
// {
// event EventHandler e { $$ }
// }
// =>
// class Bar
// {
// event EventHandler e;$$
// }
// and we need to move the caret after semicolon
var nextCaretPosition = newRoot.GetAnnotatedNodes(s_replacementNodeAnnotation).Single().GetLastToken().Span.End;
return (newRoot, nextCaretPosition);
}
}
private static int GetOpenBraceSpanEnd(SyntaxNode root)
{
// Use the annotation to find the end of the open brace.
var annotatedOpenBraceToken = root.GetAnnotatedTokens(s_openBracePositionAnnotation).Single();
return annotatedOpenBraceToken.Span.End;
}
private static int GetBraceInsertionPosition(SyntaxNode node)
=> node switch
{
NamespaceDeclarationSyntax => node.GetBraces().openBrace.SpanStart,
IndexerDeclarationSyntax indexerNode => indexerNode.ParameterList.Span.End,
SwitchStatementSyntax switchStatementNode => switchStatementNode.CloseParenToken.Span.End,
TryStatementSyntax tryStatementNode => tryStatementNode.TryKeyword.Span.End,
CatchClauseSyntax catchClauseNode => catchClauseNode.Block.SpanStart,
FinallyClauseSyntax finallyClauseNode => finallyClauseNode.Block.SpanStart,
_ => throw ExceptionUtilities.Unreachable,
};
private static string GetBracePairString(IEditorOptions editorOptions)
=> string.Concat(SyntaxFacts.GetText(SyntaxKind.OpenBraceToken),
editorOptions.GetNewLineCharacter(),
SyntaxFacts.GetText(SyntaxKind.CloseBraceToken));
private void InsertBraceAndMoveCaret(
ITextView textView,
Document document,
int insertionPosition,
CancellationToken cancellationToken)
{
var bracePair = GetBracePairString(textView.Options);
// 1. Insert { }.
var newDocument = document.InsertText(insertionPosition, bracePair, cancellationToken);
// 2. Place caret between the braces.
textView.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(textView.TextSnapshot, insertionPosition + 1));
// 3. Format the document using the close brace.
FormatAndApplyBasedOnEndToken(newDocument, insertionPosition + bracePair.Length - 1, cancellationToken);
}
protected override (SyntaxNode selectedNode, bool addBrace)? GetValidNodeToModifyBraces(Document document, int caretPosition, CancellationToken cancellationToken)
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
var token = root.FindTokenOnLeftOfPosition(caretPosition);
if (token.IsKind(SyntaxKind.None))
{
return null;
}
foreach (var node in token.GetAncestors<SyntaxNode>())
{
if (ShouldAddBraces(node, caretPosition))
{
return (selectedNode: node, addBrace: true);
}
if (ShouldRemoveBraces(node, caretPosition))
{
return (selectedNode: node, addBrace: false);
}
}
return null;
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.WordSpanEnumerator.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.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.NamingStyles
{
internal partial struct NamingStyle
{
private struct WordSpanEnumerator
{
private readonly string _name;
private readonly TextSpan _nameSpan;
private readonly string _wordSeparator;
public WordSpanEnumerator(string name, TextSpan nameSpan, string wordSeparator)
{
Debug.Assert(nameSpan.Length > 0);
_name = name;
_nameSpan = nameSpan;
_wordSeparator = wordSeparator;
Current = new TextSpan(nameSpan.Start, 0);
}
public TextSpan Current { get; private set; }
public bool MoveNext()
{
if (_wordSeparator == "")
{
// No separator. So only ever return a single word
if (Current.Length == 0)
{
Current = _nameSpan;
return true;
}
else
{
return false;
}
}
while (true)
{
var nextWordSeparator = _name.IndexOf(_wordSeparator, Current.End);
if (nextWordSeparator == Current.End)
{
// We're right at the word separator. Skip it and continue searching.
Current = new TextSpan(Current.End + _wordSeparator.Length, 0);
continue;
}
// If didn't find a word separator, it's as if the next word separator is at the end of name span.
if (nextWordSeparator < 0)
{
nextWordSeparator = _nameSpan.End;
}
// If we've walked past the _nameSpan just immediately stop. There are no more words to return.
if (Current.End > _nameSpan.End)
{
return false;
}
// found a separator in front of us. Note: it may be in our suffix portion.
// So use the min of the separator position and our end position.
Current = TextSpan.FromBounds(Current.End, Math.Min(_nameSpan.End, nextWordSeparator));
break;
}
return Current.Length > 0 && Current.End <= _nameSpan.End;
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.NamingStyles
{
internal partial struct NamingStyle
{
private struct WordSpanEnumerator
{
private readonly string _name;
private readonly TextSpan _nameSpan;
private readonly string _wordSeparator;
public WordSpanEnumerator(string name, TextSpan nameSpan, string wordSeparator)
{
Debug.Assert(nameSpan.Length > 0);
_name = name;
_nameSpan = nameSpan;
_wordSeparator = wordSeparator;
Current = new TextSpan(nameSpan.Start, 0);
}
public TextSpan Current { get; private set; }
public bool MoveNext()
{
if (_wordSeparator == "")
{
// No separator. So only ever return a single word
if (Current.Length == 0)
{
Current = _nameSpan;
return true;
}
else
{
return false;
}
}
while (true)
{
var nextWordSeparator = _name.IndexOf(_wordSeparator, Current.End);
if (nextWordSeparator == Current.End)
{
// We're right at the word separator. Skip it and continue searching.
Current = new TextSpan(Current.End + _wordSeparator.Length, 0);
continue;
}
// If didn't find a word separator, it's as if the next word separator is at the end of name span.
if (nextWordSeparator < 0)
{
nextWordSeparator = _nameSpan.End;
}
// If we've walked past the _nameSpan just immediately stop. There are no more words to return.
if (Current.End > _nameSpan.End)
{
return false;
}
// found a separator in front of us. Note: it may be in our suffix portion.
// So use the min of the separator position and our end position.
Current = TextSpan.FromBounds(Current.End, Math.Min(_nameSpan.End, nextWordSeparator));
break;
}
return Current.Length > 0 && Current.End <= _nameSpan.End;
}
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DecimalKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class DecimalKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public DecimalKeywordRecommender()
: base(SyntaxKind.DecimalKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Decimal;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class DecimalKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public DecimalKeywordRecommender()
: base(SyntaxKind.DecimalKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Decimal;
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/EditorFeatures/Core/EditorConfigSettings/DataProvider/Analyzer/AnalyzerSettingsWorkspaceServiceFactory.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.Diagnostics;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider.Analyzer
{
[ExportWorkspaceServiceFactory(typeof(IWorkspaceSettingsProviderFactory<AnalyzerSetting>)), Shared]
internal class AnalyzerSettingsWorkspaceServiceFactory : IWorkspaceServiceFactory
{
private readonly IDiagnosticAnalyzerService _analyzerService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerSettingsWorkspaceServiceFactory(IDiagnosticAnalyzerService analyzerService)
{
_analyzerService = analyzerService;
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new AnalyzerSettingsProviderFactory(workspaceServices.Workspace, _analyzerService);
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider.Analyzer
{
[ExportWorkspaceServiceFactory(typeof(IWorkspaceSettingsProviderFactory<AnalyzerSetting>)), Shared]
internal class AnalyzerSettingsWorkspaceServiceFactory : IWorkspaceServiceFactory
{
private readonly IDiagnosticAnalyzerService _analyzerService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerSettingsWorkspaceServiceFactory(IDiagnosticAnalyzerService analyzerService)
{
_analyzerService = analyzerService;
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new AnalyzerSettingsProviderFactory(workspaceServices.Workspace, _analyzerService);
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/VisualBasic/Portable/Compilation/SymbolInfo.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.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Class SymbolInfoFactory
Friend Shared Function Create(symbols As ImmutableArray(Of Symbol), resultKind As LookupResultKind) As SymbolInfo
Return Create(StaticCast(Of ISymbol).From(symbols), resultKind)
End Function
Friend Shared Function Create(symbols As ImmutableArray(Of ISymbol), resultKind As LookupResultKind) As SymbolInfo
Dim reason = If(resultKind = LookupResultKind.Good, CandidateReason.None, resultKind.ToCandidateReason())
Return Create(symbols, reason)
End Function
Friend Shared Function Create(symbols As ImmutableArray(Of ISymbol), reason As CandidateReason) As SymbolInfo
symbols = symbols.NullToEmpty()
If symbols.IsEmpty AndAlso Not (reason = CandidateReason.None OrElse reason = CandidateReason.LateBound) Then
reason = CandidateReason.None
End If
If symbols.Length = 1 AndAlso (reason = CandidateReason.None OrElse reason = CandidateReason.LateBound) Then
Return New SymbolInfo(symbols(0), reason)
Else
Return New SymbolInfo(symbols, reason)
End If
End Function
End Class
#If False Then
Public Structure SymbolInfo
Implements IEquatable(Of SymbolInfo)
Private ReadOnly _symbols As ImmutableArray(Of Symbol)
Private ReadOnly _resultKind As LookupResultKind
Friend ReadOnly Property AllSymbols As ImmutableArray(Of Symbol)
Get
Return _symbols
End Get
End Property
Friend ReadOnly Property ResultKind As LookupResultKind
Get
Return _resultKind
End Get
End Property
Friend Shared None As SymbolInfo = New SymbolInfo(ImmutableArray(Of Symbol).Empty, LookupResultKind.Empty)
Friend Shared NotNeeded As SymbolInfo = New SymbolInfo(ImmutableArray(Of Symbol).Empty, LookupResultKind.Good)
''' <summary>
''' The symbol that was referred to by the syntax node, if any. Returns null if the given
''' expression did not bind successfully to a single symbol. If null is returned, it may
''' still be that case that we have one or more "best guesses" as to what symbol was
''' intended. These best guesses are available via the CandidateSymbols property.
''' </summary>
Public ReadOnly Property Symbol As Symbol
Get
If _resultKind = LookupResultKind.Good AndAlso _symbols.Length > 0 Then
Debug.Assert(_symbols.Length = 1)
Return _symbols(0)
Else
Return Nothing
End If
End Get
End Property
''' <summary>
''' If the expression did not successfully resolve to a symbol, but there were one or more
''' symbols that may have been considered but discarded, this property returns those
''' symbols. The reason that the symbols did not successfully resolve to a symbol are
''' available in the CandidateReason property. For example, if the symbol was inaccessible,
''' ambiguous, or used in the wrong context.
''' </summary>
Public ReadOnly Property CandidateSymbols As ImmutableArray(Of Symbol)
Get
If _resultKind <> LookupResultKind.Good AndAlso Not _symbols.IsDefaultOrEmpty Then
Return _symbols
Else
Return ImmutableArray(Of Symbol).Empty
End If
End Get
End Property
'''<summary>
''' If the expression did not successfully resolve to a symbol, but there were one or more
''' symbols that may have been considered but discarded, this property describes why those
''' symbol or symbols were not considered suitable.
''' </summary>
Public ReadOnly Property CandidateReason As CandidateReason
Get
Return If(_resultKind = LookupResultKind.Good, CandidateReason.None, _resultKind.ToCandidateReason())
End Get
End Property
Friend Sub New(symbols As ImmutableArray(Of Symbol), resultKind As LookupResultKind)
Me._symbols = If(symbols.IsDefault, ImmutableArray(Of Symbol).Empty, symbols)
Me._resultKind = resultKind
If Not symbols.Any() AndAlso resultKind <> LookupResultKind.Good AndAlso resultKind <> LookupResultKind.LateBound Then
Me._resultKind = LookupResultKind.Empty
End If
End Sub
Public Overloads Function Equals(other As SymbolInfo) As Boolean Implements IEquatable(Of SymbolInfo).Equals
Return _symbols.SequenceEqual(other._symbols) AndAlso
_resultKind = other._resultKind
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return TypeOf obj Is SymbolInfo AndAlso
Equals(DirectCast(obj, SymbolInfo))
End Function
Public Overrides Function GetHashCode() As Integer
Return Hash.Combine(Hash.CombineValues(_symbols, 4), CInt(_resultKind))
End Function
Public Shared Widening Operator CType(info As SymbolInfo) As SymbolInfo
Return New SymbolInfo(info.Symbol, StaticCast(Of ISymbol).From(info.CandidateSymbols), info.CandidateReason)
End Operator
End Structure
#End If
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.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Class SymbolInfoFactory
Friend Shared Function Create(symbols As ImmutableArray(Of Symbol), resultKind As LookupResultKind) As SymbolInfo
Return Create(StaticCast(Of ISymbol).From(symbols), resultKind)
End Function
Friend Shared Function Create(symbols As ImmutableArray(Of ISymbol), resultKind As LookupResultKind) As SymbolInfo
Dim reason = If(resultKind = LookupResultKind.Good, CandidateReason.None, resultKind.ToCandidateReason())
Return Create(symbols, reason)
End Function
Friend Shared Function Create(symbols As ImmutableArray(Of ISymbol), reason As CandidateReason) As SymbolInfo
symbols = symbols.NullToEmpty()
If symbols.IsEmpty AndAlso Not (reason = CandidateReason.None OrElse reason = CandidateReason.LateBound) Then
reason = CandidateReason.None
End If
If symbols.Length = 1 AndAlso (reason = CandidateReason.None OrElse reason = CandidateReason.LateBound) Then
Return New SymbolInfo(symbols(0), reason)
Else
Return New SymbolInfo(symbols, reason)
End If
End Function
End Class
#If False Then
Public Structure SymbolInfo
Implements IEquatable(Of SymbolInfo)
Private ReadOnly _symbols As ImmutableArray(Of Symbol)
Private ReadOnly _resultKind As LookupResultKind
Friend ReadOnly Property AllSymbols As ImmutableArray(Of Symbol)
Get
Return _symbols
End Get
End Property
Friend ReadOnly Property ResultKind As LookupResultKind
Get
Return _resultKind
End Get
End Property
Friend Shared None As SymbolInfo = New SymbolInfo(ImmutableArray(Of Symbol).Empty, LookupResultKind.Empty)
Friend Shared NotNeeded As SymbolInfo = New SymbolInfo(ImmutableArray(Of Symbol).Empty, LookupResultKind.Good)
''' <summary>
''' The symbol that was referred to by the syntax node, if any. Returns null if the given
''' expression did not bind successfully to a single symbol. If null is returned, it may
''' still be that case that we have one or more "best guesses" as to what symbol was
''' intended. These best guesses are available via the CandidateSymbols property.
''' </summary>
Public ReadOnly Property Symbol As Symbol
Get
If _resultKind = LookupResultKind.Good AndAlso _symbols.Length > 0 Then
Debug.Assert(_symbols.Length = 1)
Return _symbols(0)
Else
Return Nothing
End If
End Get
End Property
''' <summary>
''' If the expression did not successfully resolve to a symbol, but there were one or more
''' symbols that may have been considered but discarded, this property returns those
''' symbols. The reason that the symbols did not successfully resolve to a symbol are
''' available in the CandidateReason property. For example, if the symbol was inaccessible,
''' ambiguous, or used in the wrong context.
''' </summary>
Public ReadOnly Property CandidateSymbols As ImmutableArray(Of Symbol)
Get
If _resultKind <> LookupResultKind.Good AndAlso Not _symbols.IsDefaultOrEmpty Then
Return _symbols
Else
Return ImmutableArray(Of Symbol).Empty
End If
End Get
End Property
'''<summary>
''' If the expression did not successfully resolve to a symbol, but there were one or more
''' symbols that may have been considered but discarded, this property describes why those
''' symbol or symbols were not considered suitable.
''' </summary>
Public ReadOnly Property CandidateReason As CandidateReason
Get
Return If(_resultKind = LookupResultKind.Good, CandidateReason.None, _resultKind.ToCandidateReason())
End Get
End Property
Friend Sub New(symbols As ImmutableArray(Of Symbol), resultKind As LookupResultKind)
Me._symbols = If(symbols.IsDefault, ImmutableArray(Of Symbol).Empty, symbols)
Me._resultKind = resultKind
If Not symbols.Any() AndAlso resultKind <> LookupResultKind.Good AndAlso resultKind <> LookupResultKind.LateBound Then
Me._resultKind = LookupResultKind.Empty
End If
End Sub
Public Overloads Function Equals(other As SymbolInfo) As Boolean Implements IEquatable(Of SymbolInfo).Equals
Return _symbols.SequenceEqual(other._symbols) AndAlso
_resultKind = other._resultKind
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return TypeOf obj Is SymbolInfo AndAlso
Equals(DirectCast(obj, SymbolInfo))
End Function
Public Overrides Function GetHashCode() As Integer
Return Hash.Combine(Hash.CombineValues(_symbols, 4), CInt(_resultKind))
End Function
Public Shared Widening Operator CType(info As SymbolInfo) As SymbolInfo
Return New SymbolInfo(info.Symbol, StaticCast(Of ISymbol).From(info.CandidateSymbols), info.CandidateReason)
End Operator
End Structure
#End If
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/Core/Portable/Syntax/SyntaxNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
#pragma warning disable CA1200 // Avoid using cref tags with a prefix
/// <summary>
/// Represents a non-terminal node in the syntax tree. This is the language agnostic equivalent of <see
/// cref="T:Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode"/> and <see cref="T:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode"/>.
/// </summary>
#pragma warning restore CA1200 // Avoid using cref tags with a prefix
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
public abstract partial class SyntaxNode
{
private readonly SyntaxNode? _parent;
internal SyntaxTree? _syntaxTree;
internal SyntaxNode(GreenNode green, SyntaxNode? parent, int position)
{
RoslynDebug.Assert(position >= 0, "position cannot be negative");
RoslynDebug.Assert(parent?.Green.IsList != true, "list cannot be a parent");
Position = position;
Green = green;
_parent = parent;
}
/// <summary>
/// Used by structured trivia which has "parent == null", and therefore must know its
/// SyntaxTree explicitly when created.
/// </summary>
internal SyntaxNode(GreenNode green, int position, SyntaxTree syntaxTree)
: this(green, null, position)
{
this._syntaxTree = syntaxTree;
}
private string GetDebuggerDisplay()
{
return GetType().Name + " " + KindText + " " + ToString();
}
/// <summary>
/// An integer representing the language specific kind of this node.
/// </summary>
public int RawKind => Green.RawKind;
protected string KindText => Green.KindText;
/// <summary>
/// The language name that this node is syntax of.
/// </summary>
public abstract string Language { get; }
internal GreenNode Green { get; }
internal int Position { get; }
internal int EndPosition => Position + Green.FullWidth;
/// <summary>
/// Returns SyntaxTree that owns the node or null if node does not belong to a
/// SyntaxTree
/// </summary>
public SyntaxTree SyntaxTree => this.SyntaxTreeCore;
internal bool IsList => this.Green.IsList;
/// <summary>
/// The absolute span of this node in characters, including its leading and trailing trivia.
/// </summary>
public TextSpan FullSpan => new TextSpan(this.Position, this.Green.FullWidth);
internal int SlotCount => this.Green.SlotCount;
/// <summary>
/// The absolute span of this node in characters, not including its leading and trailing trivia.
/// </summary>
public TextSpan Span
{
get
{
// Start with the full span.
var start = Position;
var width = this.Green.FullWidth;
// adjust for preceding trivia (avoid calling this twice, do not call Green.Width)
var precedingWidth = this.Green.GetLeadingTriviaWidth();
start += precedingWidth;
width -= precedingWidth;
// adjust for following trivia width
width -= this.Green.GetTrailingTriviaWidth();
Debug.Assert(width >= 0);
return new TextSpan(start, width);
}
}
/// <summary>
/// Same as accessing <see cref="TextSpan.Start"/> on <see cref="Span"/>.
/// </summary>
/// <remarks>
/// Slight performance improvement.
/// </remarks>
public int SpanStart => Position + Green.GetLeadingTriviaWidth();
/// <summary>
/// The width of the node in characters, not including leading and trailing trivia.
/// </summary>
/// <remarks>
/// The Width property returns the same value as Span.Length, but is somewhat more efficient.
/// </remarks>
internal int Width => this.Green.Width;
/// <summary>
/// The complete width of the node in characters, including leading and trailing trivia.
/// </summary>
/// <remarks>The FullWidth property returns the same value as FullSpan.Length, but is
/// somewhat more efficient.</remarks>
internal int FullWidth => this.Green.FullWidth;
// this is used in cases where we know that a child is a node of particular type.
internal SyntaxNode? GetRed(ref SyntaxNode? field, int slot)
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(slot);
if (green != null)
{
Interlocked.CompareExchange(ref field, green.CreateRed(this, this.GetChildPosition(slot)), null);
result = field;
}
}
return result;
}
// special case of above function where slot = 0, does not need GetChildPosition
internal SyntaxNode? GetRedAtZero(ref SyntaxNode? field)
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(0);
if (green != null)
{
Interlocked.CompareExchange(ref field, green.CreateRed(this, this.Position), null);
result = field;
}
}
return result;
}
protected T? GetRed<T>(ref T? field, int slot) where T : SyntaxNode
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(slot);
if (green != null)
{
Interlocked.CompareExchange(ref field, (T)green.CreateRed(this, this.GetChildPosition(slot)), null);
result = field;
}
}
return result;
}
// special case of above function where slot = 0, does not need GetChildPosition
protected T? GetRedAtZero<T>(ref T? field) where T : SyntaxNode
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(0);
if (green != null)
{
Interlocked.CompareExchange(ref field, (T)green.CreateRed(this, this.Position), null);
result = field;
}
}
return result;
}
/// <summary>
/// This works the same as GetRed, but intended to be used in lists
/// The only difference is that the public parent of the node is not the list,
/// but the list's parent. (element's grand parent).
/// </summary>
internal SyntaxNode? GetRedElement(ref SyntaxNode? element, int slot)
{
Debug.Assert(this.IsList);
var result = element;
if (result == null)
{
var green = this.Green.GetRequiredSlot(slot);
// passing list's parent
Interlocked.CompareExchange(ref element, green.CreateRed(this.Parent, this.GetChildPosition(slot)), null);
result = element;
}
return result;
}
/// <summary>
/// special cased helper for 2 and 3 children lists where child #1 may map to a token
/// </summary>
internal SyntaxNode? GetRedElementIfNotToken(ref SyntaxNode? element)
{
Debug.Assert(this.IsList);
var result = element;
if (result == null)
{
var green = this.Green.GetRequiredSlot(1);
if (!green.IsToken)
{
// passing list's parent
Interlocked.CompareExchange(ref element, green.CreateRed(this.Parent, this.GetChildPosition(1)), null);
result = element;
}
}
return result;
}
internal SyntaxNode GetWeakRedElement(ref WeakReference<SyntaxNode>? slot, int index)
{
SyntaxNode? value = null;
if (slot?.TryGetTarget(out value) == true)
{
return value!;
}
return CreateWeakItem(ref slot, index);
}
// handle a miss
private SyntaxNode CreateWeakItem(ref WeakReference<SyntaxNode>? slot, int index)
{
var greenChild = this.Green.GetRequiredSlot(index);
var newNode = greenChild.CreateRed(this.Parent, GetChildPosition(index));
var newWeakReference = new WeakReference<SyntaxNode>(newNode);
while (true)
{
SyntaxNode? previousNode = null;
WeakReference<SyntaxNode>? previousWeakReference = slot;
if (previousWeakReference?.TryGetTarget(out previousNode) == true)
{
return previousNode!;
}
if (Interlocked.CompareExchange(ref slot, newWeakReference, previousWeakReference) == previousWeakReference)
{
return newNode;
}
}
}
/// <summary>
/// Returns the string representation of this node, not including its leading and trailing trivia.
/// </summary>
/// <returns>The string representation of this node, not including its leading and trailing trivia.</returns>
/// <remarks>The length of the returned string is always the same as Span.Length</remarks>
public override string ToString()
{
return this.Green.ToString();
}
/// <summary>
/// Returns full string representation of this node including its leading and trailing trivia.
/// </summary>
/// <returns>The full string representation of this node including its leading and trailing trivia.</returns>
/// <remarks>The length of the returned string is always the same as FullSpan.Length</remarks>
public virtual string ToFullString()
{
return this.Green.ToFullString();
}
/// <summary>
/// Writes the full text of this node to the specified <see cref="TextWriter"/>.
/// </summary>
public virtual void WriteTo(TextWriter writer)
{
this.Green.WriteTo(writer, leading: true, trailing: true);
}
/// <summary>
/// Gets the full text of this node as a new <see cref="SourceText"/> instance.
/// </summary>
/// <param name="encoding">
/// Encoding of the file that the text was read from or is going to be saved to.
/// <c>null</c> if the encoding is unspecified.
/// If the encoding is not specified the <see cref="SourceText"/> isn't debuggable.
/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public SourceText GetText(Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
var builder = new StringBuilder();
this.WriteTo(new StringWriter(builder));
return new StringBuilderText(builder, encoding, checksumAlgorithm);
}
/// <summary>
/// Determine whether this node is structurally equivalent to another.
/// </summary>
public bool IsEquivalentTo([NotNullWhen(true)] SyntaxNode? other)
{
if (this == other)
{
return true;
}
if (other == null)
{
return false;
}
return this.Green.IsEquivalentTo(other.Green);
}
/// <summary>
/// Returns true if these two nodes are considered "incrementally identical". An incrementally identical node
/// occurs when a <see cref="SyntaxTree"/> is incrementally parsed using <see cref="SyntaxTree.WithChangedText"/>
/// and the incremental parser is able to take the node from the original tree and use it in its entirety in the
/// new tree. In this case, the <see cref="SyntaxNode.ToFullString()"/> of each node will be the same, though
/// they could have different parents, and may occur at different positions in their respective trees. If two nodes are
/// incrementally identical, all children of each node will be incrementally identical as well.
/// </summary>
/// <remarks>
/// Incrementally identical nodes can also appear within the same syntax tree, or syntax trees that did not arise
/// from <see cref="SyntaxTree.WithChangedText"/>. This can happen as the parser is allowed to construct parse
/// trees from shared nodes for efficiency. In all these cases though, it will still remain true that the incrementally
/// identical nodes could have different parents and may occur at different positions in their respective trees.
/// </remarks>
public bool IsIncrementallyIdenticalTo([NotNullWhen(true)] SyntaxNode? other)
=> this.Green != null && this.Green == other?.Green;
/// <summary>
/// Determines whether the node represents a language construct that was actually parsed
/// from the source code. Missing nodes are generated by the parser in error scenarios to
/// represent constructs that should have been present in the source code in order to
/// compile successfully but were actually missing.
/// </summary>
public bool IsMissing
{
get
{
return this.Green.IsMissing;
}
}
/// <summary>
/// Determines whether this node is a descendant of a structured trivia.
/// </summary>
public bool IsPartOfStructuredTrivia()
{
for (SyntaxNode? node = this; node != null; node = node.Parent)
{
if (node.IsStructuredTrivia)
return true;
}
return false;
}
/// <summary>
/// Determines whether this node represents a structured trivia.
/// </summary>
public bool IsStructuredTrivia
{
get
{
return this.Green.IsStructuredTrivia;
}
}
/// <summary>
/// Determines whether a descendant trivia of this node is structured.
/// </summary>
public bool HasStructuredTrivia
{
get
{
return this.Green.ContainsStructuredTrivia && !this.Green.IsStructuredTrivia;
}
}
/// <summary>
/// Determines whether this node has any descendant skipped text.
/// </summary>
public bool ContainsSkippedText
{
get
{
return this.Green.ContainsSkippedText;
}
}
/// <summary>
/// Determines whether this node has any descendant preprocessor directives.
/// </summary>
public bool ContainsDirectives
{
get
{
return this.Green.ContainsDirectives;
}
}
/// <summary>
/// Determines whether this node or any of its descendant nodes, tokens or trivia have any diagnostics on them.
/// </summary>
public bool ContainsDiagnostics
{
get
{
return this.Green.ContainsDiagnostics;
}
}
/// <summary>
/// Determines if the specified node is a descendant of this node.
/// Returns true for current node.
/// </summary>
public bool Contains(SyntaxNode? node)
{
if (node == null || !this.FullSpan.Contains(node.FullSpan))
{
return false;
}
while (node != null)
{
if (node == this)
{
return true;
}
if (node.Parent != null)
{
node = node.Parent;
}
else if (node.IsStructuredTrivia)
{
node = ((IStructuredTriviaSyntax)node).ParentTrivia.Token.Parent;
}
else
{
node = null;
}
}
return false;
}
/// <summary>
/// Determines whether this node has any leading trivia.
/// </summary>
public bool HasLeadingTrivia
{
get
{
return this.GetLeadingTrivia().Count > 0;
}
}
/// <summary>
/// Determines whether this node has any trailing trivia.
/// </summary>
public bool HasTrailingTrivia
{
get
{
return this.GetTrailingTrivia().Count > 0;
}
}
/// <summary>
/// Gets a node at given node index without forcing its creation.
/// If node was not created it would return null.
/// </summary>
internal abstract SyntaxNode? GetCachedSlot(int index);
internal int GetChildIndex(int slot)
{
int index = 0;
for (int i = 0; i < slot; i++)
{
var item = this.Green.GetSlot(i);
if (item != null)
{
if (item.IsList)
{
index += item.SlotCount;
}
else
{
index++;
}
}
}
return index;
}
/// <summary>
/// This function calculates the offset of a child at given position. It is very common that
/// some children to the left of the given index already know their positions so we first
/// check if that is the case. In a worst case the cost is O(n), but it is not generally an
/// issue because number of children in regular nodes is fixed and small. In a case where
/// the number of children could be large (lists) this function is overridden with more
/// efficient implementations.
/// </summary>
internal virtual int GetChildPosition(int index)
{
int offset = 0;
var green = this.Green;
while (index > 0)
{
index--;
var prevSibling = this.GetCachedSlot(index);
if (prevSibling != null)
{
return prevSibling.EndPosition + offset;
}
var greenChild = green.GetSlot(index);
if (greenChild != null)
{
offset += greenChild.FullWidth;
}
}
return this.Position + offset;
}
public Location GetLocation()
{
return this.SyntaxTree.GetLocation(this.Span);
}
internal Location Location
{
get
{
// SyntaxNodes always has a non-null SyntaxTree, however the tree might be rooted at a node which is not a CompilationUnit.
// These kind of nodes may be seen during binding in couple of scenarios:
// (a) Compiler synthesized syntax nodes (e.g. missing nodes, qualified names for command line using directives, etc.)
// (b) Speculatively binding syntax nodes through the semantic model.
//
// For scenario (a), we need to ensure that we return NoLocation for generating location agnostic compiler diagnostics.
// For scenario (b), at present, we do not expose the diagnostics for speculative binding, hence we can return NoLocation.
// In future, if we decide to support this, we will need some mechanism to distinguish between scenarios (a) and (b) here.
var tree = this.SyntaxTree;
RoslynDebug.Assert(tree != null);
return !tree.SupportsLocations ? NoLocation.Singleton : new SourceLocation(this);
}
}
/// <summary>
/// Gets a list of all the diagnostics in the sub tree that has this node as its root.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public IEnumerable<Diagnostic> GetDiagnostics()
{
return this.SyntaxTree.GetDiagnostics(this);
}
/// <summary>
/// Gets a <see cref="SyntaxReference"/> for this syntax node. CommonSyntaxReferences can be used to
/// regain access to a syntax node without keeping the entire tree and source text in
/// memory.
/// </summary>
public SyntaxReference GetReference()
{
return this.SyntaxTree.GetReference(this);
}
#region Node Lookup
/// <summary>
/// The node that contains this node in its <see cref="ChildNodes"/> collection.
/// </summary>
public SyntaxNode? Parent
{
get
{
return _parent;
}
}
public virtual SyntaxTrivia ParentTrivia
{
get
{
return default(SyntaxTrivia);
}
}
internal SyntaxNode? ParentOrStructuredTriviaParent
{
get
{
return GetParent(this, ascendOutOfTrivia: true);
}
}
/// <summary>
/// The list of child nodes and tokens of this node, where each element is a SyntaxNodeOrToken instance.
/// </summary>
public ChildSyntaxList ChildNodesAndTokens()
{
return new ChildSyntaxList(this);
}
public virtual SyntaxNodeOrToken ChildThatContainsPosition(int position)
{
//PERF: it is very important to keep this method fast.
if (!FullSpan.Contains(position))
{
throw new ArgumentOutOfRangeException(nameof(position));
}
SyntaxNodeOrToken childNodeOrToken = ChildSyntaxList.ChildThatContainsPosition(this, position);
Debug.Assert(childNodeOrToken.FullSpan.Contains(position), "ChildThatContainsPosition's return value does not contain the requested position.");
return childNodeOrToken;
}
/// <summary>
/// Gets node at given node index.
/// This WILL force node creation if node has not yet been created.
/// Can still return null for invalid slot numbers
/// </summary>
internal abstract SyntaxNode? GetNodeSlot(int slot);
internal SyntaxNode GetRequiredNodeSlot(int slot)
{
var syntaxNode = GetNodeSlot(slot);
RoslynDebug.Assert(syntaxNode is object);
return syntaxNode;
}
/// <summary>
/// Gets a list of the child nodes in prefix document order.
/// </summary>
public IEnumerable<SyntaxNode> ChildNodes()
{
foreach (var nodeOrToken in this.ChildNodesAndTokens())
{
if (nodeOrToken.AsNode(out var node))
{
yield return node;
}
}
}
/// <summary>
/// Gets a list of ancestor nodes
/// </summary>
public IEnumerable<SyntaxNode> Ancestors(bool ascendOutOfTrivia = true)
{
return this.Parent?
.AncestorsAndSelf(ascendOutOfTrivia) ??
SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
/// <summary>
/// Gets a list of ancestor nodes (including this node)
/// </summary>
public IEnumerable<SyntaxNode> AncestorsAndSelf(bool ascendOutOfTrivia = true)
{
for (SyntaxNode? node = this; node != null; node = GetParent(node, ascendOutOfTrivia))
{
yield return node;
}
}
private static SyntaxNode? GetParent(SyntaxNode node, bool ascendOutOfTrivia)
{
var parent = node.Parent;
if (parent == null && ascendOutOfTrivia)
{
var structuredTrivia = node as IStructuredTriviaSyntax;
if (structuredTrivia != null)
{
parent = structuredTrivia.ParentTrivia.Token.Parent;
}
}
return parent;
}
/// <summary>
/// Gets the first node of type TNode that matches the predicate.
/// </summary>
public TNode? FirstAncestorOrSelf<TNode>(Func<TNode, bool>? predicate = null, bool ascendOutOfTrivia = true)
where TNode : SyntaxNode
{
for (SyntaxNode? node = this; node != null; node = GetParent(node, ascendOutOfTrivia))
{
var tnode = node as TNode;
if (tnode != null && (predicate == null || predicate(tnode)))
{
return tnode;
}
}
return null;
}
/// <summary>
/// Gets the first node of type TNode that matches the predicate.
/// </summary>
[SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required for consistent API usage patterns.")]
public TNode? FirstAncestorOrSelf<TNode, TArg>(Func<TNode, TArg, bool> predicate, TArg argument, bool ascendOutOfTrivia = true)
where TNode : SyntaxNode
{
for (var node = this; node != null; node = GetParent(node, ascendOutOfTrivia))
{
if (node is TNode tnode && predicate(tnode, argument))
{
return tnode;
}
}
return null;
}
/// <summary>
/// Gets a list of descendant nodes in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodes(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of descendant nodes in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodes(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of descendant nodes (including this node) in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodesAndSelf(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Gets a list of descendant nodes (including this node) in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodesAndSelf(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Gets a list of descendant nodes and tokens in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokens(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of the descendant nodes and tokens in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokens(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of descendant nodes and tokens (including this node) in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensAndSelf(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Gets a list of the descendant nodes and tokens (including this node) in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensAndSelf(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Finds the node with the smallest <see cref="FullSpan"/> that contains <paramref name="span"/>.
/// <paramref name="getInnermostNodeForTie"/> is used to determine the behavior in case of a tie (i.e. a node having the same span as its parent).
/// If <paramref name="getInnermostNodeForTie"/> is true, then it returns lowest descending node encompassing the given <paramref name="span"/>.
/// Otherwise, it returns the outermost node encompassing the given <paramref name="span"/>.
/// </summary>
/// <devdoc>
/// TODO: This should probably be reimplemented with <see cref="ChildThatContainsPosition"/>
/// </devdoc>
/// <exception cref="ArgumentOutOfRangeException">This exception is thrown if <see cref="FullSpan"/> doesn't contain the given span.</exception>
public SyntaxNode FindNode(TextSpan span, bool findInsideTrivia = false, bool getInnermostNodeForTie = false)
{
if (!this.FullSpan.Contains(span))
{
throw new ArgumentOutOfRangeException(nameof(span));
}
var node = FindToken(span.Start, findInsideTrivia)
.Parent
!.FirstAncestorOrSelf<SyntaxNode, TextSpan>((a, span) => a.FullSpan.Contains(span), span);
RoslynDebug.Assert(node is object);
SyntaxNode? cuRoot = node.SyntaxTree?.GetRoot();
// Tie-breaking.
if (!getInnermostNodeForTie)
{
while (true)
{
var parent = node.Parent;
// NOTE: We care about FullSpan equality, but FullWidth is cheaper and equivalent.
if (parent == null || parent.FullWidth != node.FullWidth) break;
// prefer child over compilation unit
if (parent == cuRoot) break;
node = parent;
}
}
return node;
}
#endregion
#region Token Lookup
/// <summary>
/// Finds a descendant token of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the token relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">
/// True to return tokens that are part of trivia. If false finds the token whose full span (including trivia)
/// includes the position.
/// </param>
public SyntaxToken FindToken(int position, bool findInsideTrivia = false)
{
return FindTokenCore(position, findInsideTrivia);
}
/// <summary>
/// Gets the first token of the tree rooted by this node. Skips zero-width tokens.
/// </summary>
/// <returns>The first token or <c>default(SyntaxToken)</c> if it doesn't exist.</returns>
public SyntaxToken GetFirstToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return SyntaxNavigator.Instance.GetFirstToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Gets the last token of the tree rooted by this node. Skips zero-width tokens.
/// </summary>
/// <returns>The last token or <c>default(SyntaxToken)</c> if it doesn't exist.</returns>
public SyntaxToken GetLastToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return SyntaxNavigator.Instance.GetLastToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Gets a list of the direct child tokens of this node.
/// </summary>
public IEnumerable<SyntaxToken> ChildTokens()
{
foreach (var nodeOrToken in this.ChildNodesAndTokens())
{
if (nodeOrToken.IsToken)
{
yield return nodeOrToken.AsToken();
}
}
}
/// <summary>
/// Gets a list of all the tokens in the span of this node.
/// </summary>
public IEnumerable<SyntaxToken> DescendantTokens(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return this.DescendantNodesAndTokens(descendIntoChildren, descendIntoTrivia).Where(sn => sn.IsToken).Select(sn => sn.AsToken());
}
/// <summary>
/// Gets a list of all the tokens in the full span of this node.
/// </summary>
public IEnumerable<SyntaxToken> DescendantTokens(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return this.DescendantNodesAndTokens(span, descendIntoChildren, descendIntoTrivia).Where(sn => sn.IsToken).Select(sn => sn.AsToken());
}
#endregion
#region Trivia Lookup
/// <summary>
/// The list of trivia that appears before this node in the source code and are attached to a token that is a
/// descendant of this node.
/// </summary>
public SyntaxTriviaList GetLeadingTrivia()
{
return GetFirstToken(includeZeroWidth: true).LeadingTrivia;
}
/// <summary>
/// The list of trivia that appears after this node in the source code and are attached to a token that is a
/// descendant of this node.
/// </summary>
public SyntaxTriviaList GetTrailingTrivia()
{
return GetLastToken(includeZeroWidth: true).TrailingTrivia;
}
/// <summary>
/// Finds a descendant trivia of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">
/// True to return tokens that are part of trivia. If false finds the token whose full span (including trivia)
/// includes the position.
/// </param>
public SyntaxTrivia FindTrivia(int position, bool findInsideTrivia = false)
{
return FindTrivia(position, findInsideTrivia ? SyntaxTrivia.Any : null);
}
/// <summary>
/// Finds a descendant trivia of this node at the specified position, where the position is
/// within the span of the node.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of
/// the file.</param>
/// <param name="stepInto">Specifies a function that determines per trivia node, whether to
/// descend into structured trivia of that node.</param>
/// <returns></returns>
public SyntaxTrivia FindTrivia(int position, Func<SyntaxTrivia, bool>? stepInto)
{
if (this.FullSpan.Contains(position))
{
return FindTriviaByOffset(this, position - this.Position, stepInto);
}
return default(SyntaxTrivia);
}
internal static SyntaxTrivia FindTriviaByOffset(SyntaxNode node, int textOffset, Func<SyntaxTrivia, bool>? stepInto = null)
{
recurse:
if (textOffset >= 0)
{
foreach (var element in node.ChildNodesAndTokens())
{
var fullWidth = element.FullWidth;
if (textOffset < fullWidth)
{
if (element.AsNode(out var elementNode))
{
node = elementNode;
goto recurse;
}
else if (element.IsToken)
{
var token = element.AsToken();
var leading = token.LeadingWidth;
if (textOffset < token.LeadingWidth)
{
foreach (var trivia in token.LeadingTrivia)
{
if (textOffset < trivia.FullWidth)
{
if (trivia.HasStructure && stepInto != null && stepInto(trivia))
{
node = trivia.GetStructure()!;
goto recurse;
}
return trivia;
}
textOffset -= trivia.FullWidth;
}
}
else if (textOffset >= leading + token.Width)
{
textOffset -= leading + token.Width;
foreach (var trivia in token.TrailingTrivia)
{
if (textOffset < trivia.FullWidth)
{
if (trivia.HasStructure && stepInto != null && stepInto(trivia))
{
node = trivia.GetStructure()!;
goto recurse;
}
return trivia;
}
textOffset -= trivia.FullWidth;
}
}
return default(SyntaxTrivia);
}
}
textOffset -= fullWidth;
}
}
return default(SyntaxTrivia);
}
/// <summary>
/// Get a list of all the trivia associated with the descendant nodes and tokens.
/// </summary>
public IEnumerable<SyntaxTrivia> DescendantTrivia(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantTriviaImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia);
}
/// <summary>
/// Get a list of all the trivia associated with the descendant nodes and tokens.
/// </summary>
public IEnumerable<SyntaxTrivia> DescendantTrivia(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantTriviaImpl(span, descendIntoChildren, descendIntoTrivia);
}
#endregion
#region Annotations
/// <summary>
/// Determines whether this node or any sub node, token or trivia has annotations.
/// </summary>
public bool ContainsAnnotations
{
get { return this.Green.ContainsAnnotations; }
}
/// <summary>
/// Determines whether this node has any annotations with the specific annotation kind.
/// </summary>
public bool HasAnnotations(string annotationKind)
{
return this.Green.HasAnnotations(annotationKind);
}
/// <summary>
/// Determines whether this node has any annotations with any of the specific annotation kinds.
/// </summary>
public bool HasAnnotations(IEnumerable<string> annotationKinds)
{
return this.Green.HasAnnotations(annotationKinds);
}
/// <summary>
/// Determines whether this node has the specific annotation.
/// </summary>
public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation)
{
return this.Green.HasAnnotation(annotation);
}
/// <summary>
/// Gets all the annotations with the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxAnnotation> GetAnnotations(string annotationKind)
{
return this.Green.GetAnnotations(annotationKind);
}
/// <summary>
/// Gets all the annotations with the specified annotation kinds.
/// </summary>
public IEnumerable<SyntaxAnnotation> GetAnnotations(IEnumerable<string> annotationKinds)
{
return this.Green.GetAnnotations(annotationKinds);
}
internal SyntaxAnnotation[] GetAnnotations()
{
return this.Green.GetAnnotations();
}
/// <summary>
/// Gets all nodes and tokens with an annotation of the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxNodeOrToken> GetAnnotatedNodesAndTokens(string annotationKind)
{
return this.DescendantNodesAndTokensAndSelf(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(t => t.HasAnnotations(annotationKind));
}
/// <summary>
/// Gets all nodes and tokens with an annotation of the specified annotation kinds.
/// </summary>
public IEnumerable<SyntaxNodeOrToken> GetAnnotatedNodesAndTokens(params string[] annotationKinds)
{
return this.DescendantNodesAndTokensAndSelf(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(t => t.HasAnnotations(annotationKinds));
}
/// <summary>
/// Gets all nodes and tokens with the specified annotation.
/// </summary>
public IEnumerable<SyntaxNodeOrToken> GetAnnotatedNodesAndTokens(SyntaxAnnotation annotation)
{
return this.DescendantNodesAndTokensAndSelf(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(t => t.HasAnnotation(annotation));
}
/// <summary>
/// Gets all nodes with the specified annotation.
/// </summary>
public IEnumerable<SyntaxNode> GetAnnotatedNodes(SyntaxAnnotation syntaxAnnotation)
{
return this.GetAnnotatedNodesAndTokens(syntaxAnnotation).Where(n => n.IsNode).Select(n => n.AsNode()!);
}
/// <summary>
/// Gets all nodes with the specified annotation kind.
/// </summary>
/// <param name="annotationKind"></param>
/// <returns></returns>
public IEnumerable<SyntaxNode> GetAnnotatedNodes(string annotationKind)
{
return this.GetAnnotatedNodesAndTokens(annotationKind).Where(n => n.IsNode).Select(n => n.AsNode()!);
}
/// <summary>
/// Gets all tokens with the specified annotation.
/// </summary>
public IEnumerable<SyntaxToken> GetAnnotatedTokens(SyntaxAnnotation syntaxAnnotation)
{
return this.GetAnnotatedNodesAndTokens(syntaxAnnotation).Where(n => n.IsToken).Select(n => n.AsToken());
}
/// <summary>
/// Gets all tokens with the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxToken> GetAnnotatedTokens(string annotationKind)
{
return this.GetAnnotatedNodesAndTokens(annotationKind).Where(n => n.IsToken).Select(n => n.AsToken());
}
/// <summary>
/// Gets all trivia with an annotation of the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxTrivia> GetAnnotatedTrivia(string annotationKind)
{
return this.DescendantTrivia(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(tr => tr.HasAnnotations(annotationKind));
}
/// <summary>
/// Gets all trivia with an annotation of the specified annotation kinds.
/// </summary>
public IEnumerable<SyntaxTrivia> GetAnnotatedTrivia(params string[] annotationKinds)
{
return this.DescendantTrivia(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(tr => tr.HasAnnotations(annotationKinds));
}
/// <summary>
/// Gets all trivia with the specified annotation.
/// </summary>
public IEnumerable<SyntaxTrivia> GetAnnotatedTrivia(SyntaxAnnotation annotation)
{
return this.DescendantTrivia(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(tr => tr.HasAnnotation(annotation));
}
internal SyntaxNode WithAdditionalAnnotationsInternal(IEnumerable<SyntaxAnnotation> annotations)
{
return this.Green.WithAdditionalAnnotationsGreen(annotations).CreateRed();
}
internal SyntaxNode GetNodeWithoutAnnotations(IEnumerable<SyntaxAnnotation> annotations)
{
return this.Green.WithoutAnnotationsGreen(annotations).CreateRed();
}
/// <summary>
/// Copies all SyntaxAnnotations, if any, from this SyntaxNode instance and attaches them to a new instance based on <paramref name="node" />.
/// </summary>
/// <remarks>
/// <para>
/// If no annotations are copied, just returns <paramref name="node" />.
/// </para>
/// <para>
/// It can also be used manually to preserve annotations in a more complex tree
/// modification, even if the type of a node changes.
/// </para>
/// </remarks>
public T? CopyAnnotationsTo<T>(T? node) where T : SyntaxNode
{
if (node == null)
{
return null;
}
var annotations = this.Green.GetAnnotations();
if (annotations?.Length > 0)
{
return (T)(node.Green.WithAdditionalAnnotationsGreen(annotations)).CreateRed();
}
return node;
}
#endregion
/// <summary>
/// Determines if two nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="node">The node to compare against.</param>
/// <param name="topLevel"> If true then the nodes are equivalent if the contained nodes and
/// tokens declaring metadata visible symbolic information are equivalent, ignoring any
/// differences of nodes inside method bodies or initializer expressions, otherwise all
/// nodes and tokens must be equivalent.
/// </param>
public bool IsEquivalentTo(SyntaxNode node, bool topLevel = false)
{
return IsEquivalentToCore(node, topLevel);
}
/// <summary>
/// Serializes the node to the given <paramref name="stream"/>.
/// Leaves the <paramref name="stream"/> open for further writes.
/// </summary>
public virtual void SerializeTo(Stream stream, CancellationToken cancellationToken = default)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanWrite)
{
throw new InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeWrittenTo);
}
using var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken);
writer.WriteValue(Green);
}
#region Core Methods
/// <summary>
/// Determine if this node is structurally equivalent to another.
/// </summary>
protected virtual bool EquivalentToCore(SyntaxNode other)
{
return IsEquivalentTo(other);
}
/// <summary>
/// Returns SyntaxTree that owns the node. If the node does not belong to a tree then
/// one will be generated.
/// </summary>
protected abstract SyntaxTree SyntaxTreeCore { get; }
/// <summary>
/// Finds a descendant token of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the token relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">
/// True to return tokens that are part of trivia.
/// If false finds the token whose full span (including trivia) includes the position.
/// </param>
protected virtual SyntaxToken FindTokenCore(int position, bool findInsideTrivia)
{
if (findInsideTrivia)
{
return this.FindToken(position, SyntaxTrivia.Any);
}
SyntaxToken EoF;
if (this.TryGetEofAt(position, out EoF))
{
return EoF;
}
if (!this.FullSpan.Contains(position))
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return this.FindTokenInternal(position);
}
private bool TryGetEofAt(int position, out SyntaxToken Eof)
{
if (position == this.EndPosition)
{
var compilationUnit = this as ICompilationUnitSyntax;
if (compilationUnit != null)
{
Eof = compilationUnit.EndOfFileToken;
Debug.Assert(Eof.EndPosition == position);
return true;
}
}
Eof = default(SyntaxToken);
return false;
}
internal SyntaxToken FindTokenInternal(int position)
{
// While maintaining invariant curNode.Position <= position < curNode.FullSpan.End
// go down the tree until a token is found
SyntaxNodeOrToken curNode = this;
while (true)
{
Debug.Assert(curNode.RawKind != 0);
Debug.Assert(curNode.FullSpan.Contains(position));
var node = curNode.AsNode();
if (node != null)
{
//find a child that includes the position
curNode = node.ChildThatContainsPosition(position);
}
else
{
return curNode.AsToken();
}
}
}
private SyntaxToken FindToken(int position, Func<SyntaxTrivia, bool> findInsideTrivia)
{
return FindTokenCore(position, findInsideTrivia);
}
/// <summary>
/// Finds a descendant token of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the token relative to the beginning of the file.</param>
/// <param name="stepInto">
/// Applied on every structured trivia. Return false if the tokens included in the trivia should be skipped.
/// Pass null to skip all structured trivia.
/// </param>
protected virtual SyntaxToken FindTokenCore(int position, Func<SyntaxTrivia, bool> stepInto)
{
var token = this.FindToken(position, findInsideTrivia: false);
if (stepInto != null)
{
var trivia = GetTriviaFromSyntaxToken(position, token);
if (trivia.HasStructure && stepInto(trivia))
{
token = trivia.GetStructure()!.FindTokenInternal(position);
}
}
return token;
}
internal static SyntaxTrivia GetTriviaFromSyntaxToken(int position, in SyntaxToken token)
{
var span = token.Span;
var trivia = new SyntaxTrivia();
if (position < span.Start && token.HasLeadingTrivia)
{
trivia = GetTriviaThatContainsPosition(token.LeadingTrivia, position);
}
else if (position >= span.End && token.HasTrailingTrivia)
{
trivia = GetTriviaThatContainsPosition(token.TrailingTrivia, position);
}
return trivia;
}
internal static SyntaxTrivia GetTriviaThatContainsPosition(in SyntaxTriviaList list, int position)
{
foreach (var trivia in list)
{
if (trivia.FullSpan.Contains(position))
{
return trivia;
}
if (trivia.Position > position)
{
break;
}
}
return default(SyntaxTrivia);
}
/// <summary>
/// Finds a descendant trivia of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">Whether to search inside structured trivia.</param>
protected virtual SyntaxTrivia FindTriviaCore(int position, bool findInsideTrivia)
{
return FindTrivia(position, findInsideTrivia);
}
/// <summary>
/// Creates a new tree of nodes with the specified nodes, tokens or trivia replaced.
/// </summary>
protected internal abstract SyntaxNode ReplaceCore<TNode>(
IEnumerable<TNode>? nodes = null,
Func<TNode, TNode, SyntaxNode>? computeReplacementNode = null,
IEnumerable<SyntaxToken>? tokens = null,
Func<SyntaxToken, SyntaxToken, SyntaxToken>? computeReplacementToken = null,
IEnumerable<SyntaxTrivia>? trivia = null,
Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia>? computeReplacementTrivia = null)
where TNode : SyntaxNode;
protected internal abstract SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable<SyntaxNode> replacementNodes);
protected internal abstract SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable<SyntaxNode> nodesToInsert, bool insertBefore);
protected internal abstract SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens);
protected internal abstract SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens, bool insertBefore);
protected internal abstract SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia);
protected internal abstract SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia, bool insertBefore);
/// <summary>
/// Creates a new tree of nodes with the specified node removed.
/// </summary>
protected internal abstract SyntaxNode? RemoveNodesCore(
IEnumerable<SyntaxNode> nodes,
SyntaxRemoveOptions options);
protected internal abstract SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia);
/// <summary>
/// Determines if two nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="node">The node to compare against.</param>
/// <param name="topLevel"> If true then the nodes are equivalent if the contained nodes and
/// tokens declaring metadata visible symbolic information are equivalent, ignoring any
/// differences of nodes inside method bodies or initializer expressions, otherwise all
/// nodes and tokens must be equivalent.
/// </param>
protected abstract bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false);
#endregion
/// <summary>
/// Whether or not this parent node wants its child SyntaxList node to be
/// converted to a Weak-SyntaxList when creating the red-node equivalent.
/// For example, in C# the statements of a Block-Node that is parented by a
/// MethodDeclaration will be held weakly.
/// </summary>
internal virtual bool ShouldCreateWeakList()
{
return false;
}
internal bool HasErrors
{
get
{
if (!this.ContainsDiagnostics)
{
return false;
}
return HasErrorsSlow();
}
}
private bool HasErrorsSlow()
{
return new Syntax.InternalSyntax.SyntaxDiagnosticInfoList(this.Green).Any(
info => info.Severity == DiagnosticSeverity.Error);
}
/// <summary>
/// Creates a clone of a red node that can be used as a root of given syntaxTree.
/// New node has no parents, position == 0, and syntaxTree as specified.
/// </summary>
internal static T CloneNodeAsRoot<T>(T node, SyntaxTree syntaxTree) where T : SyntaxNode
{
var clone = (T)node.Green.CreateRed(null, 0);
clone._syntaxTree = syntaxTree;
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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
#pragma warning disable CA1200 // Avoid using cref tags with a prefix
/// <summary>
/// Represents a non-terminal node in the syntax tree. This is the language agnostic equivalent of <see
/// cref="T:Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode"/> and <see cref="T:Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode"/>.
/// </summary>
#pragma warning restore CA1200 // Avoid using cref tags with a prefix
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
public abstract partial class SyntaxNode
{
private readonly SyntaxNode? _parent;
internal SyntaxTree? _syntaxTree;
internal SyntaxNode(GreenNode green, SyntaxNode? parent, int position)
{
RoslynDebug.Assert(position >= 0, "position cannot be negative");
RoslynDebug.Assert(parent?.Green.IsList != true, "list cannot be a parent");
Position = position;
Green = green;
_parent = parent;
}
/// <summary>
/// Used by structured trivia which has "parent == null", and therefore must know its
/// SyntaxTree explicitly when created.
/// </summary>
internal SyntaxNode(GreenNode green, int position, SyntaxTree syntaxTree)
: this(green, null, position)
{
this._syntaxTree = syntaxTree;
}
private string GetDebuggerDisplay()
{
return GetType().Name + " " + KindText + " " + ToString();
}
/// <summary>
/// An integer representing the language specific kind of this node.
/// </summary>
public int RawKind => Green.RawKind;
protected string KindText => Green.KindText;
/// <summary>
/// The language name that this node is syntax of.
/// </summary>
public abstract string Language { get; }
internal GreenNode Green { get; }
internal int Position { get; }
internal int EndPosition => Position + Green.FullWidth;
/// <summary>
/// Returns SyntaxTree that owns the node or null if node does not belong to a
/// SyntaxTree
/// </summary>
public SyntaxTree SyntaxTree => this.SyntaxTreeCore;
internal bool IsList => this.Green.IsList;
/// <summary>
/// The absolute span of this node in characters, including its leading and trailing trivia.
/// </summary>
public TextSpan FullSpan => new TextSpan(this.Position, this.Green.FullWidth);
internal int SlotCount => this.Green.SlotCount;
/// <summary>
/// The absolute span of this node in characters, not including its leading and trailing trivia.
/// </summary>
public TextSpan Span
{
get
{
// Start with the full span.
var start = Position;
var width = this.Green.FullWidth;
// adjust for preceding trivia (avoid calling this twice, do not call Green.Width)
var precedingWidth = this.Green.GetLeadingTriviaWidth();
start += precedingWidth;
width -= precedingWidth;
// adjust for following trivia width
width -= this.Green.GetTrailingTriviaWidth();
Debug.Assert(width >= 0);
return new TextSpan(start, width);
}
}
/// <summary>
/// Same as accessing <see cref="TextSpan.Start"/> on <see cref="Span"/>.
/// </summary>
/// <remarks>
/// Slight performance improvement.
/// </remarks>
public int SpanStart => Position + Green.GetLeadingTriviaWidth();
/// <summary>
/// The width of the node in characters, not including leading and trailing trivia.
/// </summary>
/// <remarks>
/// The Width property returns the same value as Span.Length, but is somewhat more efficient.
/// </remarks>
internal int Width => this.Green.Width;
/// <summary>
/// The complete width of the node in characters, including leading and trailing trivia.
/// </summary>
/// <remarks>The FullWidth property returns the same value as FullSpan.Length, but is
/// somewhat more efficient.</remarks>
internal int FullWidth => this.Green.FullWidth;
// this is used in cases where we know that a child is a node of particular type.
internal SyntaxNode? GetRed(ref SyntaxNode? field, int slot)
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(slot);
if (green != null)
{
Interlocked.CompareExchange(ref field, green.CreateRed(this, this.GetChildPosition(slot)), null);
result = field;
}
}
return result;
}
// special case of above function where slot = 0, does not need GetChildPosition
internal SyntaxNode? GetRedAtZero(ref SyntaxNode? field)
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(0);
if (green != null)
{
Interlocked.CompareExchange(ref field, green.CreateRed(this, this.Position), null);
result = field;
}
}
return result;
}
protected T? GetRed<T>(ref T? field, int slot) where T : SyntaxNode
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(slot);
if (green != null)
{
Interlocked.CompareExchange(ref field, (T)green.CreateRed(this, this.GetChildPosition(slot)), null);
result = field;
}
}
return result;
}
// special case of above function where slot = 0, does not need GetChildPosition
protected T? GetRedAtZero<T>(ref T? field) where T : SyntaxNode
{
var result = field;
if (result == null)
{
var green = this.Green.GetSlot(0);
if (green != null)
{
Interlocked.CompareExchange(ref field, (T)green.CreateRed(this, this.Position), null);
result = field;
}
}
return result;
}
/// <summary>
/// This works the same as GetRed, but intended to be used in lists
/// The only difference is that the public parent of the node is not the list,
/// but the list's parent. (element's grand parent).
/// </summary>
internal SyntaxNode? GetRedElement(ref SyntaxNode? element, int slot)
{
Debug.Assert(this.IsList);
var result = element;
if (result == null)
{
var green = this.Green.GetRequiredSlot(slot);
// passing list's parent
Interlocked.CompareExchange(ref element, green.CreateRed(this.Parent, this.GetChildPosition(slot)), null);
result = element;
}
return result;
}
/// <summary>
/// special cased helper for 2 and 3 children lists where child #1 may map to a token
/// </summary>
internal SyntaxNode? GetRedElementIfNotToken(ref SyntaxNode? element)
{
Debug.Assert(this.IsList);
var result = element;
if (result == null)
{
var green = this.Green.GetRequiredSlot(1);
if (!green.IsToken)
{
// passing list's parent
Interlocked.CompareExchange(ref element, green.CreateRed(this.Parent, this.GetChildPosition(1)), null);
result = element;
}
}
return result;
}
internal SyntaxNode GetWeakRedElement(ref WeakReference<SyntaxNode>? slot, int index)
{
SyntaxNode? value = null;
if (slot?.TryGetTarget(out value) == true)
{
return value!;
}
return CreateWeakItem(ref slot, index);
}
// handle a miss
private SyntaxNode CreateWeakItem(ref WeakReference<SyntaxNode>? slot, int index)
{
var greenChild = this.Green.GetRequiredSlot(index);
var newNode = greenChild.CreateRed(this.Parent, GetChildPosition(index));
var newWeakReference = new WeakReference<SyntaxNode>(newNode);
while (true)
{
SyntaxNode? previousNode = null;
WeakReference<SyntaxNode>? previousWeakReference = slot;
if (previousWeakReference?.TryGetTarget(out previousNode) == true)
{
return previousNode!;
}
if (Interlocked.CompareExchange(ref slot, newWeakReference, previousWeakReference) == previousWeakReference)
{
return newNode;
}
}
}
/// <summary>
/// Returns the string representation of this node, not including its leading and trailing trivia.
/// </summary>
/// <returns>The string representation of this node, not including its leading and trailing trivia.</returns>
/// <remarks>The length of the returned string is always the same as Span.Length</remarks>
public override string ToString()
{
return this.Green.ToString();
}
/// <summary>
/// Returns full string representation of this node including its leading and trailing trivia.
/// </summary>
/// <returns>The full string representation of this node including its leading and trailing trivia.</returns>
/// <remarks>The length of the returned string is always the same as FullSpan.Length</remarks>
public virtual string ToFullString()
{
return this.Green.ToFullString();
}
/// <summary>
/// Writes the full text of this node to the specified <see cref="TextWriter"/>.
/// </summary>
public virtual void WriteTo(TextWriter writer)
{
this.Green.WriteTo(writer, leading: true, trailing: true);
}
/// <summary>
/// Gets the full text of this node as a new <see cref="SourceText"/> instance.
/// </summary>
/// <param name="encoding">
/// Encoding of the file that the text was read from or is going to be saved to.
/// <c>null</c> if the encoding is unspecified.
/// If the encoding is not specified the <see cref="SourceText"/> isn't debuggable.
/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public SourceText GetText(Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
var builder = new StringBuilder();
this.WriteTo(new StringWriter(builder));
return new StringBuilderText(builder, encoding, checksumAlgorithm);
}
/// <summary>
/// Determine whether this node is structurally equivalent to another.
/// </summary>
public bool IsEquivalentTo([NotNullWhen(true)] SyntaxNode? other)
{
if (this == other)
{
return true;
}
if (other == null)
{
return false;
}
return this.Green.IsEquivalentTo(other.Green);
}
/// <summary>
/// Returns true if these two nodes are considered "incrementally identical". An incrementally identical node
/// occurs when a <see cref="SyntaxTree"/> is incrementally parsed using <see cref="SyntaxTree.WithChangedText"/>
/// and the incremental parser is able to take the node from the original tree and use it in its entirety in the
/// new tree. In this case, the <see cref="SyntaxNode.ToFullString()"/> of each node will be the same, though
/// they could have different parents, and may occur at different positions in their respective trees. If two nodes are
/// incrementally identical, all children of each node will be incrementally identical as well.
/// </summary>
/// <remarks>
/// Incrementally identical nodes can also appear within the same syntax tree, or syntax trees that did not arise
/// from <see cref="SyntaxTree.WithChangedText"/>. This can happen as the parser is allowed to construct parse
/// trees from shared nodes for efficiency. In all these cases though, it will still remain true that the incrementally
/// identical nodes could have different parents and may occur at different positions in their respective trees.
/// </remarks>
public bool IsIncrementallyIdenticalTo([NotNullWhen(true)] SyntaxNode? other)
=> this.Green != null && this.Green == other?.Green;
/// <summary>
/// Determines whether the node represents a language construct that was actually parsed
/// from the source code. Missing nodes are generated by the parser in error scenarios to
/// represent constructs that should have been present in the source code in order to
/// compile successfully but were actually missing.
/// </summary>
public bool IsMissing
{
get
{
return this.Green.IsMissing;
}
}
/// <summary>
/// Determines whether this node is a descendant of a structured trivia.
/// </summary>
public bool IsPartOfStructuredTrivia()
{
for (SyntaxNode? node = this; node != null; node = node.Parent)
{
if (node.IsStructuredTrivia)
return true;
}
return false;
}
/// <summary>
/// Determines whether this node represents a structured trivia.
/// </summary>
public bool IsStructuredTrivia
{
get
{
return this.Green.IsStructuredTrivia;
}
}
/// <summary>
/// Determines whether a descendant trivia of this node is structured.
/// </summary>
public bool HasStructuredTrivia
{
get
{
return this.Green.ContainsStructuredTrivia && !this.Green.IsStructuredTrivia;
}
}
/// <summary>
/// Determines whether this node has any descendant skipped text.
/// </summary>
public bool ContainsSkippedText
{
get
{
return this.Green.ContainsSkippedText;
}
}
/// <summary>
/// Determines whether this node has any descendant preprocessor directives.
/// </summary>
public bool ContainsDirectives
{
get
{
return this.Green.ContainsDirectives;
}
}
/// <summary>
/// Determines whether this node or any of its descendant nodes, tokens or trivia have any diagnostics on them.
/// </summary>
public bool ContainsDiagnostics
{
get
{
return this.Green.ContainsDiagnostics;
}
}
/// <summary>
/// Determines if the specified node is a descendant of this node.
/// Returns true for current node.
/// </summary>
public bool Contains(SyntaxNode? node)
{
if (node == null || !this.FullSpan.Contains(node.FullSpan))
{
return false;
}
while (node != null)
{
if (node == this)
{
return true;
}
if (node.Parent != null)
{
node = node.Parent;
}
else if (node.IsStructuredTrivia)
{
node = ((IStructuredTriviaSyntax)node).ParentTrivia.Token.Parent;
}
else
{
node = null;
}
}
return false;
}
/// <summary>
/// Determines whether this node has any leading trivia.
/// </summary>
public bool HasLeadingTrivia
{
get
{
return this.GetLeadingTrivia().Count > 0;
}
}
/// <summary>
/// Determines whether this node has any trailing trivia.
/// </summary>
public bool HasTrailingTrivia
{
get
{
return this.GetTrailingTrivia().Count > 0;
}
}
/// <summary>
/// Gets a node at given node index without forcing its creation.
/// If node was not created it would return null.
/// </summary>
internal abstract SyntaxNode? GetCachedSlot(int index);
internal int GetChildIndex(int slot)
{
int index = 0;
for (int i = 0; i < slot; i++)
{
var item = this.Green.GetSlot(i);
if (item != null)
{
if (item.IsList)
{
index += item.SlotCount;
}
else
{
index++;
}
}
}
return index;
}
/// <summary>
/// This function calculates the offset of a child at given position. It is very common that
/// some children to the left of the given index already know their positions so we first
/// check if that is the case. In a worst case the cost is O(n), but it is not generally an
/// issue because number of children in regular nodes is fixed and small. In a case where
/// the number of children could be large (lists) this function is overridden with more
/// efficient implementations.
/// </summary>
internal virtual int GetChildPosition(int index)
{
int offset = 0;
var green = this.Green;
while (index > 0)
{
index--;
var prevSibling = this.GetCachedSlot(index);
if (prevSibling != null)
{
return prevSibling.EndPosition + offset;
}
var greenChild = green.GetSlot(index);
if (greenChild != null)
{
offset += greenChild.FullWidth;
}
}
return this.Position + offset;
}
public Location GetLocation()
{
return this.SyntaxTree.GetLocation(this.Span);
}
internal Location Location
{
get
{
// SyntaxNodes always has a non-null SyntaxTree, however the tree might be rooted at a node which is not a CompilationUnit.
// These kind of nodes may be seen during binding in couple of scenarios:
// (a) Compiler synthesized syntax nodes (e.g. missing nodes, qualified names for command line using directives, etc.)
// (b) Speculatively binding syntax nodes through the semantic model.
//
// For scenario (a), we need to ensure that we return NoLocation for generating location agnostic compiler diagnostics.
// For scenario (b), at present, we do not expose the diagnostics for speculative binding, hence we can return NoLocation.
// In future, if we decide to support this, we will need some mechanism to distinguish between scenarios (a) and (b) here.
var tree = this.SyntaxTree;
RoslynDebug.Assert(tree != null);
return !tree.SupportsLocations ? NoLocation.Singleton : new SourceLocation(this);
}
}
/// <summary>
/// Gets a list of all the diagnostics in the sub tree that has this node as its root.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public IEnumerable<Diagnostic> GetDiagnostics()
{
return this.SyntaxTree.GetDiagnostics(this);
}
/// <summary>
/// Gets a <see cref="SyntaxReference"/> for this syntax node. CommonSyntaxReferences can be used to
/// regain access to a syntax node without keeping the entire tree and source text in
/// memory.
/// </summary>
public SyntaxReference GetReference()
{
return this.SyntaxTree.GetReference(this);
}
#region Node Lookup
/// <summary>
/// The node that contains this node in its <see cref="ChildNodes"/> collection.
/// </summary>
public SyntaxNode? Parent
{
get
{
return _parent;
}
}
public virtual SyntaxTrivia ParentTrivia
{
get
{
return default(SyntaxTrivia);
}
}
internal SyntaxNode? ParentOrStructuredTriviaParent
{
get
{
return GetParent(this, ascendOutOfTrivia: true);
}
}
/// <summary>
/// The list of child nodes and tokens of this node, where each element is a SyntaxNodeOrToken instance.
/// </summary>
public ChildSyntaxList ChildNodesAndTokens()
{
return new ChildSyntaxList(this);
}
public virtual SyntaxNodeOrToken ChildThatContainsPosition(int position)
{
//PERF: it is very important to keep this method fast.
if (!FullSpan.Contains(position))
{
throw new ArgumentOutOfRangeException(nameof(position));
}
SyntaxNodeOrToken childNodeOrToken = ChildSyntaxList.ChildThatContainsPosition(this, position);
Debug.Assert(childNodeOrToken.FullSpan.Contains(position), "ChildThatContainsPosition's return value does not contain the requested position.");
return childNodeOrToken;
}
/// <summary>
/// Gets node at given node index.
/// This WILL force node creation if node has not yet been created.
/// Can still return null for invalid slot numbers
/// </summary>
internal abstract SyntaxNode? GetNodeSlot(int slot);
internal SyntaxNode GetRequiredNodeSlot(int slot)
{
var syntaxNode = GetNodeSlot(slot);
RoslynDebug.Assert(syntaxNode is object);
return syntaxNode;
}
/// <summary>
/// Gets a list of the child nodes in prefix document order.
/// </summary>
public IEnumerable<SyntaxNode> ChildNodes()
{
foreach (var nodeOrToken in this.ChildNodesAndTokens())
{
if (nodeOrToken.AsNode(out var node))
{
yield return node;
}
}
}
/// <summary>
/// Gets a list of ancestor nodes
/// </summary>
public IEnumerable<SyntaxNode> Ancestors(bool ascendOutOfTrivia = true)
{
return this.Parent?
.AncestorsAndSelf(ascendOutOfTrivia) ??
SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
/// <summary>
/// Gets a list of ancestor nodes (including this node)
/// </summary>
public IEnumerable<SyntaxNode> AncestorsAndSelf(bool ascendOutOfTrivia = true)
{
for (SyntaxNode? node = this; node != null; node = GetParent(node, ascendOutOfTrivia))
{
yield return node;
}
}
private static SyntaxNode? GetParent(SyntaxNode node, bool ascendOutOfTrivia)
{
var parent = node.Parent;
if (parent == null && ascendOutOfTrivia)
{
var structuredTrivia = node as IStructuredTriviaSyntax;
if (structuredTrivia != null)
{
parent = structuredTrivia.ParentTrivia.Token.Parent;
}
}
return parent;
}
/// <summary>
/// Gets the first node of type TNode that matches the predicate.
/// </summary>
public TNode? FirstAncestorOrSelf<TNode>(Func<TNode, bool>? predicate = null, bool ascendOutOfTrivia = true)
where TNode : SyntaxNode
{
for (SyntaxNode? node = this; node != null; node = GetParent(node, ascendOutOfTrivia))
{
var tnode = node as TNode;
if (tnode != null && (predicate == null || predicate(tnode)))
{
return tnode;
}
}
return null;
}
/// <summary>
/// Gets the first node of type TNode that matches the predicate.
/// </summary>
[SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required for consistent API usage patterns.")]
public TNode? FirstAncestorOrSelf<TNode, TArg>(Func<TNode, TArg, bool> predicate, TArg argument, bool ascendOutOfTrivia = true)
where TNode : SyntaxNode
{
for (var node = this; node != null; node = GetParent(node, ascendOutOfTrivia))
{
if (node is TNode tnode && predicate(tnode, argument))
{
return tnode;
}
}
return null;
}
/// <summary>
/// Gets a list of descendant nodes in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodes(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of descendant nodes in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodes(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of descendant nodes (including this node) in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodesAndSelf(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Gets a list of descendant nodes (including this node) in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNode> DescendantNodesAndSelf(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Gets a list of descendant nodes and tokens in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokens(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of the descendant nodes and tokens in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokens(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: false);
}
/// <summary>
/// Gets a list of descendant nodes and tokens (including this node) in prefix document order.
/// </summary>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensAndSelf(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Gets a list of the descendant nodes and tokens (including this node) in prefix document order.
/// </summary>
/// <param name="span">The span the node's full span must intersect.</param>
/// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param>
/// <param name="descendIntoTrivia">Determines if nodes that are part of structured trivia are included in the list.</param>
public IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensAndSelf(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantNodesAndTokensImpl(span, descendIntoChildren, descendIntoTrivia, includeSelf: true);
}
/// <summary>
/// Finds the node with the smallest <see cref="FullSpan"/> that contains <paramref name="span"/>.
/// <paramref name="getInnermostNodeForTie"/> is used to determine the behavior in case of a tie (i.e. a node having the same span as its parent).
/// If <paramref name="getInnermostNodeForTie"/> is true, then it returns lowest descending node encompassing the given <paramref name="span"/>.
/// Otherwise, it returns the outermost node encompassing the given <paramref name="span"/>.
/// </summary>
/// <devdoc>
/// TODO: This should probably be reimplemented with <see cref="ChildThatContainsPosition"/>
/// </devdoc>
/// <exception cref="ArgumentOutOfRangeException">This exception is thrown if <see cref="FullSpan"/> doesn't contain the given span.</exception>
public SyntaxNode FindNode(TextSpan span, bool findInsideTrivia = false, bool getInnermostNodeForTie = false)
{
if (!this.FullSpan.Contains(span))
{
throw new ArgumentOutOfRangeException(nameof(span));
}
var node = FindToken(span.Start, findInsideTrivia)
.Parent
!.FirstAncestorOrSelf<SyntaxNode, TextSpan>((a, span) => a.FullSpan.Contains(span), span);
RoslynDebug.Assert(node is object);
SyntaxNode? cuRoot = node.SyntaxTree?.GetRoot();
// Tie-breaking.
if (!getInnermostNodeForTie)
{
while (true)
{
var parent = node.Parent;
// NOTE: We care about FullSpan equality, but FullWidth is cheaper and equivalent.
if (parent == null || parent.FullWidth != node.FullWidth) break;
// prefer child over compilation unit
if (parent == cuRoot) break;
node = parent;
}
}
return node;
}
#endregion
#region Token Lookup
/// <summary>
/// Finds a descendant token of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the token relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">
/// True to return tokens that are part of trivia. If false finds the token whose full span (including trivia)
/// includes the position.
/// </param>
public SyntaxToken FindToken(int position, bool findInsideTrivia = false)
{
return FindTokenCore(position, findInsideTrivia);
}
/// <summary>
/// Gets the first token of the tree rooted by this node. Skips zero-width tokens.
/// </summary>
/// <returns>The first token or <c>default(SyntaxToken)</c> if it doesn't exist.</returns>
public SyntaxToken GetFirstToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return SyntaxNavigator.Instance.GetFirstToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Gets the last token of the tree rooted by this node. Skips zero-width tokens.
/// </summary>
/// <returns>The last token or <c>default(SyntaxToken)</c> if it doesn't exist.</returns>
public SyntaxToken GetLastToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return SyntaxNavigator.Instance.GetLastToken(this, includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Gets a list of the direct child tokens of this node.
/// </summary>
public IEnumerable<SyntaxToken> ChildTokens()
{
foreach (var nodeOrToken in this.ChildNodesAndTokens())
{
if (nodeOrToken.IsToken)
{
yield return nodeOrToken.AsToken();
}
}
}
/// <summary>
/// Gets a list of all the tokens in the span of this node.
/// </summary>
public IEnumerable<SyntaxToken> DescendantTokens(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return this.DescendantNodesAndTokens(descendIntoChildren, descendIntoTrivia).Where(sn => sn.IsToken).Select(sn => sn.AsToken());
}
/// <summary>
/// Gets a list of all the tokens in the full span of this node.
/// </summary>
public IEnumerable<SyntaxToken> DescendantTokens(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return this.DescendantNodesAndTokens(span, descendIntoChildren, descendIntoTrivia).Where(sn => sn.IsToken).Select(sn => sn.AsToken());
}
#endregion
#region Trivia Lookup
/// <summary>
/// The list of trivia that appears before this node in the source code and are attached to a token that is a
/// descendant of this node.
/// </summary>
public SyntaxTriviaList GetLeadingTrivia()
{
return GetFirstToken(includeZeroWidth: true).LeadingTrivia;
}
/// <summary>
/// The list of trivia that appears after this node in the source code and are attached to a token that is a
/// descendant of this node.
/// </summary>
public SyntaxTriviaList GetTrailingTrivia()
{
return GetLastToken(includeZeroWidth: true).TrailingTrivia;
}
/// <summary>
/// Finds a descendant trivia of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">
/// True to return tokens that are part of trivia. If false finds the token whose full span (including trivia)
/// includes the position.
/// </param>
public SyntaxTrivia FindTrivia(int position, bool findInsideTrivia = false)
{
return FindTrivia(position, findInsideTrivia ? SyntaxTrivia.Any : null);
}
/// <summary>
/// Finds a descendant trivia of this node at the specified position, where the position is
/// within the span of the node.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of
/// the file.</param>
/// <param name="stepInto">Specifies a function that determines per trivia node, whether to
/// descend into structured trivia of that node.</param>
/// <returns></returns>
public SyntaxTrivia FindTrivia(int position, Func<SyntaxTrivia, bool>? stepInto)
{
if (this.FullSpan.Contains(position))
{
return FindTriviaByOffset(this, position - this.Position, stepInto);
}
return default(SyntaxTrivia);
}
internal static SyntaxTrivia FindTriviaByOffset(SyntaxNode node, int textOffset, Func<SyntaxTrivia, bool>? stepInto = null)
{
recurse:
if (textOffset >= 0)
{
foreach (var element in node.ChildNodesAndTokens())
{
var fullWidth = element.FullWidth;
if (textOffset < fullWidth)
{
if (element.AsNode(out var elementNode))
{
node = elementNode;
goto recurse;
}
else if (element.IsToken)
{
var token = element.AsToken();
var leading = token.LeadingWidth;
if (textOffset < token.LeadingWidth)
{
foreach (var trivia in token.LeadingTrivia)
{
if (textOffset < trivia.FullWidth)
{
if (trivia.HasStructure && stepInto != null && stepInto(trivia))
{
node = trivia.GetStructure()!;
goto recurse;
}
return trivia;
}
textOffset -= trivia.FullWidth;
}
}
else if (textOffset >= leading + token.Width)
{
textOffset -= leading + token.Width;
foreach (var trivia in token.TrailingTrivia)
{
if (textOffset < trivia.FullWidth)
{
if (trivia.HasStructure && stepInto != null && stepInto(trivia))
{
node = trivia.GetStructure()!;
goto recurse;
}
return trivia;
}
textOffset -= trivia.FullWidth;
}
}
return default(SyntaxTrivia);
}
}
textOffset -= fullWidth;
}
}
return default(SyntaxTrivia);
}
/// <summary>
/// Get a list of all the trivia associated with the descendant nodes and tokens.
/// </summary>
public IEnumerable<SyntaxTrivia> DescendantTrivia(Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantTriviaImpl(this.FullSpan, descendIntoChildren, descendIntoTrivia);
}
/// <summary>
/// Get a list of all the trivia associated with the descendant nodes and tokens.
/// </summary>
public IEnumerable<SyntaxTrivia> DescendantTrivia(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return DescendantTriviaImpl(span, descendIntoChildren, descendIntoTrivia);
}
#endregion
#region Annotations
/// <summary>
/// Determines whether this node or any sub node, token or trivia has annotations.
/// </summary>
public bool ContainsAnnotations
{
get { return this.Green.ContainsAnnotations; }
}
/// <summary>
/// Determines whether this node has any annotations with the specific annotation kind.
/// </summary>
public bool HasAnnotations(string annotationKind)
{
return this.Green.HasAnnotations(annotationKind);
}
/// <summary>
/// Determines whether this node has any annotations with any of the specific annotation kinds.
/// </summary>
public bool HasAnnotations(IEnumerable<string> annotationKinds)
{
return this.Green.HasAnnotations(annotationKinds);
}
/// <summary>
/// Determines whether this node has the specific annotation.
/// </summary>
public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation)
{
return this.Green.HasAnnotation(annotation);
}
/// <summary>
/// Gets all the annotations with the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxAnnotation> GetAnnotations(string annotationKind)
{
return this.Green.GetAnnotations(annotationKind);
}
/// <summary>
/// Gets all the annotations with the specified annotation kinds.
/// </summary>
public IEnumerable<SyntaxAnnotation> GetAnnotations(IEnumerable<string> annotationKinds)
{
return this.Green.GetAnnotations(annotationKinds);
}
internal SyntaxAnnotation[] GetAnnotations()
{
return this.Green.GetAnnotations();
}
/// <summary>
/// Gets all nodes and tokens with an annotation of the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxNodeOrToken> GetAnnotatedNodesAndTokens(string annotationKind)
{
return this.DescendantNodesAndTokensAndSelf(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(t => t.HasAnnotations(annotationKind));
}
/// <summary>
/// Gets all nodes and tokens with an annotation of the specified annotation kinds.
/// </summary>
public IEnumerable<SyntaxNodeOrToken> GetAnnotatedNodesAndTokens(params string[] annotationKinds)
{
return this.DescendantNodesAndTokensAndSelf(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(t => t.HasAnnotations(annotationKinds));
}
/// <summary>
/// Gets all nodes and tokens with the specified annotation.
/// </summary>
public IEnumerable<SyntaxNodeOrToken> GetAnnotatedNodesAndTokens(SyntaxAnnotation annotation)
{
return this.DescendantNodesAndTokensAndSelf(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(t => t.HasAnnotation(annotation));
}
/// <summary>
/// Gets all nodes with the specified annotation.
/// </summary>
public IEnumerable<SyntaxNode> GetAnnotatedNodes(SyntaxAnnotation syntaxAnnotation)
{
return this.GetAnnotatedNodesAndTokens(syntaxAnnotation).Where(n => n.IsNode).Select(n => n.AsNode()!);
}
/// <summary>
/// Gets all nodes with the specified annotation kind.
/// </summary>
/// <param name="annotationKind"></param>
/// <returns></returns>
public IEnumerable<SyntaxNode> GetAnnotatedNodes(string annotationKind)
{
return this.GetAnnotatedNodesAndTokens(annotationKind).Where(n => n.IsNode).Select(n => n.AsNode()!);
}
/// <summary>
/// Gets all tokens with the specified annotation.
/// </summary>
public IEnumerable<SyntaxToken> GetAnnotatedTokens(SyntaxAnnotation syntaxAnnotation)
{
return this.GetAnnotatedNodesAndTokens(syntaxAnnotation).Where(n => n.IsToken).Select(n => n.AsToken());
}
/// <summary>
/// Gets all tokens with the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxToken> GetAnnotatedTokens(string annotationKind)
{
return this.GetAnnotatedNodesAndTokens(annotationKind).Where(n => n.IsToken).Select(n => n.AsToken());
}
/// <summary>
/// Gets all trivia with an annotation of the specified annotation kind.
/// </summary>
public IEnumerable<SyntaxTrivia> GetAnnotatedTrivia(string annotationKind)
{
return this.DescendantTrivia(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(tr => tr.HasAnnotations(annotationKind));
}
/// <summary>
/// Gets all trivia with an annotation of the specified annotation kinds.
/// </summary>
public IEnumerable<SyntaxTrivia> GetAnnotatedTrivia(params string[] annotationKinds)
{
return this.DescendantTrivia(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(tr => tr.HasAnnotations(annotationKinds));
}
/// <summary>
/// Gets all trivia with the specified annotation.
/// </summary>
public IEnumerable<SyntaxTrivia> GetAnnotatedTrivia(SyntaxAnnotation annotation)
{
return this.DescendantTrivia(n => n.ContainsAnnotations, descendIntoTrivia: true)
.Where(tr => tr.HasAnnotation(annotation));
}
internal SyntaxNode WithAdditionalAnnotationsInternal(IEnumerable<SyntaxAnnotation> annotations)
{
return this.Green.WithAdditionalAnnotationsGreen(annotations).CreateRed();
}
internal SyntaxNode GetNodeWithoutAnnotations(IEnumerable<SyntaxAnnotation> annotations)
{
return this.Green.WithoutAnnotationsGreen(annotations).CreateRed();
}
/// <summary>
/// Copies all SyntaxAnnotations, if any, from this SyntaxNode instance and attaches them to a new instance based on <paramref name="node" />.
/// </summary>
/// <remarks>
/// <para>
/// If no annotations are copied, just returns <paramref name="node" />.
/// </para>
/// <para>
/// It can also be used manually to preserve annotations in a more complex tree
/// modification, even if the type of a node changes.
/// </para>
/// </remarks>
public T? CopyAnnotationsTo<T>(T? node) where T : SyntaxNode
{
if (node == null)
{
return null;
}
var annotations = this.Green.GetAnnotations();
if (annotations?.Length > 0)
{
return (T)(node.Green.WithAdditionalAnnotationsGreen(annotations)).CreateRed();
}
return node;
}
#endregion
/// <summary>
/// Determines if two nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="node">The node to compare against.</param>
/// <param name="topLevel"> If true then the nodes are equivalent if the contained nodes and
/// tokens declaring metadata visible symbolic information are equivalent, ignoring any
/// differences of nodes inside method bodies or initializer expressions, otherwise all
/// nodes and tokens must be equivalent.
/// </param>
public bool IsEquivalentTo(SyntaxNode node, bool topLevel = false)
{
return IsEquivalentToCore(node, topLevel);
}
/// <summary>
/// Serializes the node to the given <paramref name="stream"/>.
/// Leaves the <paramref name="stream"/> open for further writes.
/// </summary>
public virtual void SerializeTo(Stream stream, CancellationToken cancellationToken = default)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanWrite)
{
throw new InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeWrittenTo);
}
using var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken);
writer.WriteValue(Green);
}
#region Core Methods
/// <summary>
/// Determine if this node is structurally equivalent to another.
/// </summary>
protected virtual bool EquivalentToCore(SyntaxNode other)
{
return IsEquivalentTo(other);
}
/// <summary>
/// Returns SyntaxTree that owns the node. If the node does not belong to a tree then
/// one will be generated.
/// </summary>
protected abstract SyntaxTree SyntaxTreeCore { get; }
/// <summary>
/// Finds a descendant token of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the token relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">
/// True to return tokens that are part of trivia.
/// If false finds the token whose full span (including trivia) includes the position.
/// </param>
protected virtual SyntaxToken FindTokenCore(int position, bool findInsideTrivia)
{
if (findInsideTrivia)
{
return this.FindToken(position, SyntaxTrivia.Any);
}
SyntaxToken EoF;
if (this.TryGetEofAt(position, out EoF))
{
return EoF;
}
if (!this.FullSpan.Contains(position))
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return this.FindTokenInternal(position);
}
private bool TryGetEofAt(int position, out SyntaxToken Eof)
{
if (position == this.EndPosition)
{
var compilationUnit = this as ICompilationUnitSyntax;
if (compilationUnit != null)
{
Eof = compilationUnit.EndOfFileToken;
Debug.Assert(Eof.EndPosition == position);
return true;
}
}
Eof = default(SyntaxToken);
return false;
}
internal SyntaxToken FindTokenInternal(int position)
{
// While maintaining invariant curNode.Position <= position < curNode.FullSpan.End
// go down the tree until a token is found
SyntaxNodeOrToken curNode = this;
while (true)
{
Debug.Assert(curNode.RawKind != 0);
Debug.Assert(curNode.FullSpan.Contains(position));
var node = curNode.AsNode();
if (node != null)
{
//find a child that includes the position
curNode = node.ChildThatContainsPosition(position);
}
else
{
return curNode.AsToken();
}
}
}
private SyntaxToken FindToken(int position, Func<SyntaxTrivia, bool> findInsideTrivia)
{
return FindTokenCore(position, findInsideTrivia);
}
/// <summary>
/// Finds a descendant token of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the token relative to the beginning of the file.</param>
/// <param name="stepInto">
/// Applied on every structured trivia. Return false if the tokens included in the trivia should be skipped.
/// Pass null to skip all structured trivia.
/// </param>
protected virtual SyntaxToken FindTokenCore(int position, Func<SyntaxTrivia, bool> stepInto)
{
var token = this.FindToken(position, findInsideTrivia: false);
if (stepInto != null)
{
var trivia = GetTriviaFromSyntaxToken(position, token);
if (trivia.HasStructure && stepInto(trivia))
{
token = trivia.GetStructure()!.FindTokenInternal(position);
}
}
return token;
}
internal static SyntaxTrivia GetTriviaFromSyntaxToken(int position, in SyntaxToken token)
{
var span = token.Span;
var trivia = new SyntaxTrivia();
if (position < span.Start && token.HasLeadingTrivia)
{
trivia = GetTriviaThatContainsPosition(token.LeadingTrivia, position);
}
else if (position >= span.End && token.HasTrailingTrivia)
{
trivia = GetTriviaThatContainsPosition(token.TrailingTrivia, position);
}
return trivia;
}
internal static SyntaxTrivia GetTriviaThatContainsPosition(in SyntaxTriviaList list, int position)
{
foreach (var trivia in list)
{
if (trivia.FullSpan.Contains(position))
{
return trivia;
}
if (trivia.Position > position)
{
break;
}
}
return default(SyntaxTrivia);
}
/// <summary>
/// Finds a descendant trivia of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of the file.</param>
/// <param name="findInsideTrivia">Whether to search inside structured trivia.</param>
protected virtual SyntaxTrivia FindTriviaCore(int position, bool findInsideTrivia)
{
return FindTrivia(position, findInsideTrivia);
}
/// <summary>
/// Creates a new tree of nodes with the specified nodes, tokens or trivia replaced.
/// </summary>
protected internal abstract SyntaxNode ReplaceCore<TNode>(
IEnumerable<TNode>? nodes = null,
Func<TNode, TNode, SyntaxNode>? computeReplacementNode = null,
IEnumerable<SyntaxToken>? tokens = null,
Func<SyntaxToken, SyntaxToken, SyntaxToken>? computeReplacementToken = null,
IEnumerable<SyntaxTrivia>? trivia = null,
Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia>? computeReplacementTrivia = null)
where TNode : SyntaxNode;
protected internal abstract SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable<SyntaxNode> replacementNodes);
protected internal abstract SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable<SyntaxNode> nodesToInsert, bool insertBefore);
protected internal abstract SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens);
protected internal abstract SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens, bool insertBefore);
protected internal abstract SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia);
protected internal abstract SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia, bool insertBefore);
/// <summary>
/// Creates a new tree of nodes with the specified node removed.
/// </summary>
protected internal abstract SyntaxNode? RemoveNodesCore(
IEnumerable<SyntaxNode> nodes,
SyntaxRemoveOptions options);
protected internal abstract SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia);
/// <summary>
/// Determines if two nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="node">The node to compare against.</param>
/// <param name="topLevel"> If true then the nodes are equivalent if the contained nodes and
/// tokens declaring metadata visible symbolic information are equivalent, ignoring any
/// differences of nodes inside method bodies or initializer expressions, otherwise all
/// nodes and tokens must be equivalent.
/// </param>
protected abstract bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false);
#endregion
/// <summary>
/// Whether or not this parent node wants its child SyntaxList node to be
/// converted to a Weak-SyntaxList when creating the red-node equivalent.
/// For example, in C# the statements of a Block-Node that is parented by a
/// MethodDeclaration will be held weakly.
/// </summary>
internal virtual bool ShouldCreateWeakList()
{
return false;
}
internal bool HasErrors
{
get
{
if (!this.ContainsDiagnostics)
{
return false;
}
return HasErrorsSlow();
}
}
private bool HasErrorsSlow()
{
return new Syntax.InternalSyntax.SyntaxDiagnosticInfoList(this.Green).Any(
info => info.Severity == DiagnosticSeverity.Error);
}
/// <summary>
/// Creates a clone of a red node that can be used as a root of given syntaxTree.
/// New node has no parents, position == 0, and syntaxTree as specified.
/// </summary>
internal static T CloneNodeAsRoot<T>(T node, SyntaxTree syntaxTree) where T : SyntaxNode
{
var clone = (T)node.Green.CreateRed(null, 0);
clone._syntaxTree = syntaxTree;
return clone;
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.pl.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="pl" original="../VBCodeStyleResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Usuń tę wartość, gdy dodawana jest kolejna.</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="pl" original="../VBCodeStyleResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Usuń tę wartość, gdy dodawana jest kolejna.</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/InvalidDynamicAttributeArgs.il | // ilasm /dll InvalidDynamicAttributeArgs.il
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly extern System.Core
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly C
{
.ver 0:0:0:0
}
.class public C extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
// F1 - no value, 2 required
.field public class [mscorlib]System.Collections.Generic.List`1<object> F1
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
// F2 - no value, 1 required
.field public object F2
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
// F3 - 2 values { false, true }, 3 required
.field public class [mscorlib]System.Collections.Generic.Dictionary`2<object, object> F3
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 )
// F4 - no true value { false, false }
.field public class [mscorlib]System.Collections.Generic.List`1<object> F4
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 00 00 00 )
// F5 - true value for non-object { false, false, true }
.field public class [mscorlib]System.Collections.Generic.Dictionary`2<object, bool> F5
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 00 01 00 00 )
// F6 - true for modified type { false, true }
.field public class [mscorlib]System.Collections.Generic.List`1<object> modopt([mscorlib]System.Runtime.CompilerServices.IsConst) F6
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 )
// M1
.method public hidebysig instance class [mscorlib]System.Collections.Generic.List`1<object> M1()
{
// No bool values.
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ldnull
ret
}
// M2
.method public hidebysig instance class [mscorlib]System.Collections.Generic.List`1<object> M2()
{
// No bool values.
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ldnull
ret
}
// P1
.method public hidebysig specialname instance object get_P1()
{
// No bool values.
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ldnull
ret
}
.method public hidebysig specialname instance void set_P1(object 'value')
{
// No bool values.
.param [1]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ret
}
.property instance object P1()
{
// No bool values.
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
.get instance object C::get_P1()
.set instance void C::set_P1(object)
}
// P2
.method public hidebysig specialname instance class [mscorlib]System.Collections.Generic.List`1<object> get_P2()
{
// No bool values.
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ldnull
ret
}
.method public hidebysig specialname instance void set_P2(class [mscorlib]System.Collections.Generic.List`1<object> 'value')
{
// No bool values.
.param [1]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ret
}
.property instance class [mscorlib]System.Collections.Generic.List`1<object> P2()
{
// No bool values.
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
.get instance class [mscorlib]System.Collections.Generic.List`1<object> C::get_P2()
.set instance void C::set_P2(class [mscorlib]System.Collections.Generic.List`1<object>)
}
} | // ilasm /dll InvalidDynamicAttributeArgs.il
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly extern System.Core
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly C
{
.ver 0:0:0:0
}
.class public C extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
// F1 - no value, 2 required
.field public class [mscorlib]System.Collections.Generic.List`1<object> F1
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
// F2 - no value, 1 required
.field public object F2
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
// F3 - 2 values { false, true }, 3 required
.field public class [mscorlib]System.Collections.Generic.Dictionary`2<object, object> F3
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 )
// F4 - no true value { false, false }
.field public class [mscorlib]System.Collections.Generic.List`1<object> F4
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 00 00 00 )
// F5 - true value for non-object { false, false, true }
.field public class [mscorlib]System.Collections.Generic.Dictionary`2<object, bool> F5
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 00 01 00 00 )
// F6 - true for modified type { false, true }
.field public class [mscorlib]System.Collections.Generic.List`1<object> modopt([mscorlib]System.Runtime.CompilerServices.IsConst) F6
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 )
// M1
.method public hidebysig instance class [mscorlib]System.Collections.Generic.List`1<object> M1()
{
// No bool values.
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ldnull
ret
}
// M2
.method public hidebysig instance class [mscorlib]System.Collections.Generic.List`1<object> M2()
{
// No bool values.
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ldnull
ret
}
// P1
.method public hidebysig specialname instance object get_P1()
{
// No bool values.
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ldnull
ret
}
.method public hidebysig specialname instance void set_P1(object 'value')
{
// No bool values.
.param [1]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ret
}
.property instance object P1()
{
// No bool values.
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
.get instance object C::get_P1()
.set instance void C::set_P1(object)
}
// P2
.method public hidebysig specialname instance class [mscorlib]System.Collections.Generic.List`1<object> get_P2()
{
// No bool values.
.param [0]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ldnull
ret
}
.method public hidebysig specialname instance void set_P2(class [mscorlib]System.Collections.Generic.List`1<object> 'value')
{
// No bool values.
.param [1]
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
ret
}
.property instance class [mscorlib]System.Collections.Generic.List`1<object> P2()
{
// No bool values.
.custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 )
.get instance class [mscorlib]System.Collections.Generic.List`1<object> C::get_P2()
.set instance void C::set_P2(class [mscorlib]System.Collections.Generic.List`1<object>)
}
} | -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Features/LanguageServer/Protocol/Handler/ProvidesMethodAttribute.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;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
internal class ProvidesMethodAttribute : Attribute
{
public string Method { get; }
public ProvidesMethodAttribute(string method)
{
Method = method;
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
internal class ProvidesMethodAttribute : Attribute
{
public string Method { get; }
public ProvidesMethodAttribute(string method)
{
Method = method;
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/Core/Portable/Syntax/SyntaxNodeOrTokenListBuilder.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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Syntax
{
internal class SyntaxNodeOrTokenListBuilder
{
private GreenNode?[] _nodes;
private int _count;
public SyntaxNodeOrTokenListBuilder(int size)
{
_nodes = new GreenNode?[size];
_count = 0;
}
public static SyntaxNodeOrTokenListBuilder Create()
{
return new SyntaxNodeOrTokenListBuilder(8);
}
public int Count
{
get { return _count; }
}
public void Clear()
{
_count = 0;
}
public SyntaxNodeOrToken this[int index]
{
get
{
var innerNode = _nodes[index];
RoslynDebug.Assert(innerNode is object);
if (innerNode.IsToken == true)
{
// getting internal token so we do not know the position
return new SyntaxNodeOrToken(null, innerNode, 0, 0);
}
else
{
return innerNode.CreateRed();
}
}
set
{
_nodes[index] = value.UnderlyingNode;
}
}
internal void Add(GreenNode item)
{
if (_count >= _nodes.Length)
{
this.Grow(_count == 0 ? 8 : _nodes.Length * 2);
}
_nodes[_count++] = item;
}
public void Add(SyntaxNode item)
{
this.Add(item.Green);
}
public void Add(in SyntaxToken item)
{
RoslynDebug.Assert(item.Node is object);
this.Add(item.Node);
}
public void Add(in SyntaxNodeOrToken item)
{
RoslynDebug.Assert(item.UnderlyingNode is object);
this.Add(item.UnderlyingNode);
}
public void Add(SyntaxNodeOrTokenList list)
{
this.Add(list, 0, list.Count);
}
public void Add(SyntaxNodeOrTokenList list, int offset, int length)
{
if (_count + length > _nodes.Length)
{
this.Grow(_count + length);
}
list.CopyTo(offset, _nodes, _count, length);
_count += length;
}
public void Add(IEnumerable<SyntaxNodeOrToken> nodeOrTokens)
{
foreach (var n in nodeOrTokens)
{
this.Add(n);
}
}
internal void RemoveLast()
{
_count--;
_nodes[_count] = null;
}
private void Grow(int size)
{
var tmp = new GreenNode[size];
Array.Copy(_nodes, tmp, _nodes.Length);
_nodes = tmp;
}
public SyntaxNodeOrTokenList ToList()
{
if (_count > 0)
{
switch (_count)
{
case 1:
if (_nodes[0]!.IsToken)
{
return new SyntaxNodeOrTokenList(
InternalSyntax.SyntaxList.List(new[] { _nodes[0]! }).CreateRed(),
index: 0);
}
else
{
return new SyntaxNodeOrTokenList(_nodes[0]!.CreateRed(), index: 0);
}
case 2:
return new SyntaxNodeOrTokenList(
InternalSyntax.SyntaxList.List(_nodes[0]!, _nodes[1]!).CreateRed(),
index: 0);
case 3:
return new SyntaxNodeOrTokenList(
InternalSyntax.SyntaxList.List(_nodes[0]!, _nodes[1]!, _nodes[2]!).CreateRed(),
index: 0);
default:
var tmp = new ArrayElement<GreenNode>[_count];
for (int i = 0; i < _count; i++)
{
tmp[i].Value = _nodes[i]!;
}
return new SyntaxNodeOrTokenList(InternalSyntax.SyntaxList.List(tmp).CreateRed(), index: 0);
}
}
else
{
return default(SyntaxNodeOrTokenList);
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Syntax
{
internal class SyntaxNodeOrTokenListBuilder
{
private GreenNode?[] _nodes;
private int _count;
public SyntaxNodeOrTokenListBuilder(int size)
{
_nodes = new GreenNode?[size];
_count = 0;
}
public static SyntaxNodeOrTokenListBuilder Create()
{
return new SyntaxNodeOrTokenListBuilder(8);
}
public int Count
{
get { return _count; }
}
public void Clear()
{
_count = 0;
}
public SyntaxNodeOrToken this[int index]
{
get
{
var innerNode = _nodes[index];
RoslynDebug.Assert(innerNode is object);
if (innerNode.IsToken == true)
{
// getting internal token so we do not know the position
return new SyntaxNodeOrToken(null, innerNode, 0, 0);
}
else
{
return innerNode.CreateRed();
}
}
set
{
_nodes[index] = value.UnderlyingNode;
}
}
internal void Add(GreenNode item)
{
if (_count >= _nodes.Length)
{
this.Grow(_count == 0 ? 8 : _nodes.Length * 2);
}
_nodes[_count++] = item;
}
public void Add(SyntaxNode item)
{
this.Add(item.Green);
}
public void Add(in SyntaxToken item)
{
RoslynDebug.Assert(item.Node is object);
this.Add(item.Node);
}
public void Add(in SyntaxNodeOrToken item)
{
RoslynDebug.Assert(item.UnderlyingNode is object);
this.Add(item.UnderlyingNode);
}
public void Add(SyntaxNodeOrTokenList list)
{
this.Add(list, 0, list.Count);
}
public void Add(SyntaxNodeOrTokenList list, int offset, int length)
{
if (_count + length > _nodes.Length)
{
this.Grow(_count + length);
}
list.CopyTo(offset, _nodes, _count, length);
_count += length;
}
public void Add(IEnumerable<SyntaxNodeOrToken> nodeOrTokens)
{
foreach (var n in nodeOrTokens)
{
this.Add(n);
}
}
internal void RemoveLast()
{
_count--;
_nodes[_count] = null;
}
private void Grow(int size)
{
var tmp = new GreenNode[size];
Array.Copy(_nodes, tmp, _nodes.Length);
_nodes = tmp;
}
public SyntaxNodeOrTokenList ToList()
{
if (_count > 0)
{
switch (_count)
{
case 1:
if (_nodes[0]!.IsToken)
{
return new SyntaxNodeOrTokenList(
InternalSyntax.SyntaxList.List(new[] { _nodes[0]! }).CreateRed(),
index: 0);
}
else
{
return new SyntaxNodeOrTokenList(_nodes[0]!.CreateRed(), index: 0);
}
case 2:
return new SyntaxNodeOrTokenList(
InternalSyntax.SyntaxList.List(_nodes[0]!, _nodes[1]!).CreateRed(),
index: 0);
case 3:
return new SyntaxNodeOrTokenList(
InternalSyntax.SyntaxList.List(_nodes[0]!, _nodes[1]!, _nodes[2]!).CreateRed(),
index: 0);
default:
var tmp = new ArrayElement<GreenNode>[_count];
for (int i = 0; i < _count; i++)
{
tmp[i].Value = _nodes[i]!;
}
return new SyntaxNodeOrTokenList(InternalSyntax.SyntaxList.List(tmp).CreateRed(), index: 0);
}
}
else
{
return default(SyntaxNodeOrTokenList);
}
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/VisualBasic/Portable/Binding/CatchBlockBinder.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.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binder used to bind Catch blocks.
''' It hosts the control variable (if one is declared)
''' and inherits BlockBaseBinder since there are no Exit/Continue for catch blocks.
''' </summary>
Friend NotInheritable Class CatchBlockBinder
Inherits BlockBaseBinder
Private ReadOnly _syntax As CatchBlockSyntax
Private _locals As ImmutableArray(Of LocalSymbol) = Nothing
Public Sub New(enclosing As Binder, syntax As CatchBlockSyntax)
MyBase.New(enclosing)
Debug.Assert(syntax IsNot Nothing)
_syntax = syntax
End Sub
Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
If _locals.IsDefault Then
ImmutableInterlocked.InterlockedCompareExchange(_locals, BuildLocals(), Nothing)
End If
Return _locals
End Get
End Property
' Build a read only array of all the local variables declared By the Catch declaration statement.
' There can only be 0 or 1 variable.
Private Function BuildLocals() As ImmutableArray(Of LocalSymbol)
Dim catchStatement = _syntax.CatchStatement
Dim asClauseOptSyntax = catchStatement.AsClause
' catch variables cannot be declared without As clause
' missing As means that we need to bind to something already declared.
If asClauseOptSyntax IsNot Nothing Then
Debug.Assert(catchStatement.IdentifierName IsNot Nothing)
Dim localVar = LocalSymbol.Create(Me.ContainingMember,
Me,
catchStatement.IdentifierName.Identifier,
Nothing,
asClauseOptSyntax,
Nothing,
LocalDeclarationKind.Catch)
Return ImmutableArray.Create(localVar)
End If
Return ImmutableArray(Of LocalSymbol).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 Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binder used to bind Catch blocks.
''' It hosts the control variable (if one is declared)
''' and inherits BlockBaseBinder since there are no Exit/Continue for catch blocks.
''' </summary>
Friend NotInheritable Class CatchBlockBinder
Inherits BlockBaseBinder
Private ReadOnly _syntax As CatchBlockSyntax
Private _locals As ImmutableArray(Of LocalSymbol) = Nothing
Public Sub New(enclosing As Binder, syntax As CatchBlockSyntax)
MyBase.New(enclosing)
Debug.Assert(syntax IsNot Nothing)
_syntax = syntax
End Sub
Friend Overrides ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
If _locals.IsDefault Then
ImmutableInterlocked.InterlockedCompareExchange(_locals, BuildLocals(), Nothing)
End If
Return _locals
End Get
End Property
' Build a read only array of all the local variables declared By the Catch declaration statement.
' There can only be 0 or 1 variable.
Private Function BuildLocals() As ImmutableArray(Of LocalSymbol)
Dim catchStatement = _syntax.CatchStatement
Dim asClauseOptSyntax = catchStatement.AsClause
' catch variables cannot be declared without As clause
' missing As means that we need to bind to something already declared.
If asClauseOptSyntax IsNot Nothing Then
Debug.Assert(catchStatement.IdentifierName IsNot Nothing)
Dim localVar = LocalSymbol.Create(Me.ContainingMember,
Me,
catchStatement.IdentifierName.Identifier,
Nothing,
asClauseOptSyntax,
Nothing,
LocalDeclarationKind.Catch)
Return ImmutableArray.Create(localVar)
End If
Return ImmutableArray(Of LocalSymbol).Empty
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/VisualBasic/Portable/Semantics/OverloadResolution.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.Diagnostics
Imports System.Linq
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend NotInheritable Class OverloadResolution
Private Sub New()
Throw ExceptionUtilities.Unreachable
End Sub
''' <summary>
''' Information about a candidate from a group.
''' Will have different implementation for methods, extension methods and properties.
''' </summary>
''' <remarks></remarks>
Public MustInherit Class Candidate
Public MustOverride ReadOnly Property UnderlyingSymbol As Symbol
Friend MustOverride Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
''' <summary>
''' Whether the method is used as extension method vs. called as a static method.
''' </summary>
Public Overridable ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Whether the method is used as an operator.
''' </summary>
Public Overridable ReadOnly Property IsOperator As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Whether the method is used in a lifted to nullable form.
''' </summary>
Public Overridable ReadOnly Property IsLifted As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Precedence level for an extension method.
''' </summary>
Public Overridable ReadOnly Property PrecedenceLevel As Integer
Get
Return 0
End Get
End Property
''' <summary>
''' Extension method type parameters that were fixed during currying, if any.
''' If none were fixed, BitArray.Null should be returned.
''' </summary>
Public Overridable ReadOnly Property FixedTypeParameters As BitVector
Get
Return BitVector.Null
End Get
End Property
Public MustOverride ReadOnly Property IsGeneric As Boolean
Public MustOverride ReadOnly Property ParameterCount As Integer
Public MustOverride Function Parameters(index As Integer) As ParameterSymbol
Public MustOverride ReadOnly Property ReturnType As TypeSymbol
Public MustOverride ReadOnly Property Arity As Integer
Public MustOverride ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Friend Sub GetAllParameterCounts(
ByRef requiredCount As Integer,
ByRef maxCount As Integer,
ByRef hasParamArray As Boolean
)
maxCount = Me.ParameterCount
hasParamArray = False
requiredCount = -1
Dim last = maxCount - 1
For i As Integer = 0 To last Step 1
Dim param As ParameterSymbol = Me.Parameters(i)
If i = last AndAlso param.IsParamArray Then
hasParamArray = True
ElseIf Not param.IsOptional Then
requiredCount = i
End If
Next
requiredCount += 1
End Sub
Friend Function TryGetNamedParamIndex(name As String, ByRef index As Integer) As Boolean
For i As Integer = 0 To Me.ParameterCount - 1 Step 1
Dim param As ParameterSymbol = Me.Parameters(i)
If IdentifierComparison.Equals(name, param.Name) Then
index = i
Return True
End If
Next
index = -1
Return False
End Function
''' <summary>
''' Receiver type for extension method. Otherwise, containing type.
''' </summary>
Public MustOverride ReadOnly Property ReceiverType As TypeSymbol
''' <summary>
''' For extension methods, the type of the fist parameter in method's definition (i.e. before type parameters are substituted).
''' Otherwise, same as the ReceiverType.
''' </summary>
Public MustOverride ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Friend MustOverride Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
End Class
''' <summary>
''' Implementation for an ordinary method (based on usage).
''' </summary>
Public Class MethodCandidate
Inherits Candidate
Protected ReadOnly m_Method As MethodSymbol
Public Sub New(method As MethodSymbol)
Debug.Assert(method IsNot Nothing)
Debug.Assert(method.ReducedFrom Is Nothing OrElse Me.IsExtensionMethod)
m_Method = method
End Sub
Friend Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
Return New MethodCandidate(m_Method.Construct(typeArguments))
End Function
Public Overrides ReadOnly Property IsGeneric As Boolean
Get
Return m_Method.IsGenericMethod
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return m_Method.ParameterCount
End Get
End Property
Public Overrides Function Parameters(index As Integer) As ParameterSymbol
Return m_Method.Parameters(index)
End Function
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return m_Method.ReturnType
End Get
End Property
Public Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return m_Method.ContainingType
End Get
End Property
Public Overrides ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Get
Return m_Method.ContainingType
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return m_Method.Arity
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return m_Method.TypeParameters
End Get
End Property
Public Overrides ReadOnly Property UnderlyingSymbol As Symbol
Get
Return m_Method
End Get
End Property
Friend Overrides Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
Dim definition As MethodSymbol = m_Method.OriginalDefinition
If definition.IsOverridable OrElse definition.IsOverrides OrElse definition.IsMustOverride Then
Dim otherMethod As MethodSymbol = DirectCast(otherSymbol, MethodSymbol).OverriddenMethod
While otherMethod IsNot Nothing
If otherMethod.OriginalDefinition.Equals(definition) Then
Return True
End If
otherMethod = otherMethod.OverriddenMethod
End While
End If
Return False
End Function
End Class
''' <summary>
''' Implementation for an extension method, i.e. it is used as an extension method.
''' </summary>
Public NotInheritable Class ExtensionMethodCandidate
Inherits MethodCandidate
Private _fixedTypeParameters As BitVector
Public Sub New(method As MethodSymbol)
Me.New(method, GetFixedTypeParameters(method))
End Sub
' TODO: Consider building this bitmap lazily, on demand.
Private Shared Function GetFixedTypeParameters(method As MethodSymbol) As BitVector
If method.FixedTypeParameters.Length > 0 Then
Dim fixedTypeParameters = BitVector.Create(method.ReducedFrom.Arity)
For Each fixed As KeyValuePair(Of TypeParameterSymbol, TypeSymbol) In method.FixedTypeParameters
fixedTypeParameters(fixed.Key.Ordinal) = True
Next
Return fixedTypeParameters
End If
Return Nothing
End Function
Private Sub New(method As MethodSymbol, fixedTypeParameters As BitVector)
MyBase.New(method)
Debug.Assert(method.ReducedFrom IsNot Nothing)
_fixedTypeParameters = fixedTypeParameters
End Sub
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property PrecedenceLevel As Integer
Get
Return m_Method.Proximity
End Get
End Property
Public Overrides ReadOnly Property FixedTypeParameters As BitVector
Get
Return _fixedTypeParameters
End Get
End Property
Friend Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
Return New ExtensionMethodCandidate(m_Method.Construct(typeArguments), _fixedTypeParameters)
End Function
Public Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return m_Method.ReceiverType
End Get
End Property
Public Overrides ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Get
Return m_Method.ReducedFrom.Parameters(0).Type
End Get
End Property
Friend Overrides Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
Return False ' Extension methods never override/overridden
End Function
End Class
''' <summary>
''' Implementation for an operator
''' </summary>
Public Class OperatorCandidate
Inherits MethodCandidate
Public Sub New(method As MethodSymbol)
MyBase.New(method)
End Sub
Public NotOverridable Overrides ReadOnly Property IsOperator As Boolean
Get
Return True
End Get
End Property
End Class
''' <summary>
''' Implementation for a lifted operator.
''' </summary>
Public Class LiftedOperatorCandidate
Inherits OperatorCandidate
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _returnType As TypeSymbol
Public Sub New(method As MethodSymbol, parameters As ImmutableArray(Of ParameterSymbol), returnType As TypeSymbol)
MyBase.New(method)
Debug.Assert(parameters.Length = method.ParameterCount)
_parameters = parameters
_returnType = returnType
End Sub
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return _parameters.Length
End Get
End Property
Public Overrides Function Parameters(index As Integer) As ParameterSymbol
Return _parameters(index)
End Function
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property IsLifted As Boolean
Get
Return True
End Get
End Property
End Class
''' <summary>
''' Implementation for a property.
''' </summary>
Public NotInheritable Class PropertyCandidate
Inherits Candidate
Private ReadOnly _property As PropertySymbol
Public Sub New([property] As PropertySymbol)
Debug.Assert([property] IsNot Nothing)
_property = [property]
End Sub
Friend Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides ReadOnly Property IsGeneric As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return _property.Parameters.Length
End Get
End Property
Public Overrides Function Parameters(index As Integer) As ParameterSymbol
Return _property.Parameters(index)
End Function
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _property.Type
End Get
End Property
Public Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return _property.ContainingType
End Get
End Property
Public Overrides ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Get
Return _property.ContainingType
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property UnderlyingSymbol As Symbol
Get
Return _property
End Get
End Property
Friend Overrides Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
Dim definition As PropertySymbol = _property.OriginalDefinition
If definition.IsOverridable OrElse definition.IsOverrides OrElse definition.IsMustOverride Then
Dim otherProperty As PropertySymbol = DirectCast(otherSymbol, PropertySymbol).OverriddenProperty
While otherProperty IsNot Nothing
If otherProperty.OriginalDefinition.Equals(definition) Then
Return True
End If
otherProperty = otherProperty.OverriddenProperty
End While
End If
Return False
End Function
End Class
Private Const s_stateSize = 8 ' bit size of the following enum
Public Enum CandidateAnalysisResultState As Byte
Applicable
' All following states are to indicate inapplicability
HasUnsupportedMetadata
HasUseSiteError
Ambiguous
BadGenericArity
ArgumentCountMismatch
TypeInferenceFailed
ArgumentMismatch
GenericConstraintsViolated
RequiresNarrowing
RequiresNarrowingNotFromObject
ExtensionMethodVsInstanceMethod
Shadowed
LessApplicable
ExtensionMethodVsLateBinding
Count
End Enum
<Flags()>
Private Enum SmallFieldMask As Integer
State = (1 << s_stateSize) - 1
IsExpandedParamArrayForm = 1 << (s_stateSize + 0)
InferenceLevelShift = (s_stateSize + 1)
InferenceLevelMask = 3 << InferenceLevelShift ' 2 bits are used
ArgumentMatchingDone = 1 << (s_stateSize + 3)
RequiresNarrowingConversion = 1 << (s_stateSize + 4)
RequiresNarrowingNotFromObject = 1 << (s_stateSize + 5)
RequiresNarrowingNotFromNumericConstant = 1 << (s_stateSize + 6)
' Must be equal to ConversionKind.DelegateRelaxationLevelMask
' Compile time "asserts" below enforce it by reporting a compilation error in case of a violation.
' I am not using the form of
' DelegateRelaxationLevelMask = ConversionKind.DelegateRelaxationLevelMask
' to make it easier to reason about bits used relative to other values in this enum.
DelegateRelaxationLevelMask = 7 << (s_stateSize + 7) ' 3 bits used!
SomeInferenceFailed = 1 << (s_stateSize + 10)
AllFailedInferenceIsDueToObject = 1 << (s_stateSize + 11)
InferenceErrorReasonsShift = (s_stateSize + 12)
InferenceErrorReasonsMask = 3 << InferenceErrorReasonsShift
IgnoreExtensionMethods = 1 << (s_stateSize + 14)
IllegalInAttribute = 1 << (s_stateSize + 15)
End Enum
#If DEBUG Then
' Compile time asserts.
Private Const s_delegateRelaxationLevelMask_AssertZero = SmallFieldMask.DelegateRelaxationLevelMask - ConversionKind.DelegateRelaxationLevelMask
Private ReadOnly _delegateRelaxationLevelMask_Assert1(s_delegateRelaxationLevelMask_AssertZero) As Boolean
Private ReadOnly _delegateRelaxationLevelMask_Assert2(-s_delegateRelaxationLevelMask_AssertZero) As Boolean
Private Const s_inferenceLevelMask_AssertZero = CByte((SmallFieldMask.InferenceLevelMask >> SmallFieldMask.InferenceLevelShift) <> ((TypeArgumentInference.InferenceLevel.Invalid << 1) - 1))
Private ReadOnly _inferenceLevelMask_Assert1(s_inferenceLevelMask_AssertZero) As Boolean
Private ReadOnly _inferenceLevelMask_Assert2(-s_inferenceLevelMask_AssertZero) As Boolean
#End If
Public Structure OptionalArgument
Public ReadOnly DefaultValue As BoundExpression
Public ReadOnly Conversion As KeyValuePair(Of ConversionKind, MethodSymbol)
Public ReadOnly Dependencies As ImmutableArray(Of AssemblySymbol)
Public Sub New(value As BoundExpression, conversion As KeyValuePair(Of ConversionKind, MethodSymbol), dependencies As ImmutableArray(Of AssemblySymbol))
Me.DefaultValue = value
Me.Conversion = conversion
Me.Dependencies = dependencies.NullToEmpty()
End Sub
End Structure
Public Structure CandidateAnalysisResult
Public ReadOnly Property IsExpandedParamArrayForm As Boolean
Get
Return (_smallFields And SmallFieldMask.IsExpandedParamArrayForm) <> 0
End Get
End Property
Public Sub SetIsExpandedParamArrayForm()
_smallFields = _smallFields Or SmallFieldMask.IsExpandedParamArrayForm
End Sub
Public ReadOnly Property InferenceLevel As TypeArgumentInference.InferenceLevel
Get
Return CType((_smallFields And SmallFieldMask.InferenceLevelMask) >> SmallFieldMask.InferenceLevelShift, TypeArgumentInference.InferenceLevel)
End Get
End Property
Public Sub SetInferenceLevel(level As TypeArgumentInference.InferenceLevel)
Dim value As Integer = CInt(level) << SmallFieldMask.InferenceLevelShift
Debug.Assert((value And SmallFieldMask.InferenceLevelMask) = value)
_smallFields = (_smallFields And (Not SmallFieldMask.InferenceLevelMask)) Or (value And SmallFieldMask.InferenceLevelMask)
End Sub
Public ReadOnly Property ArgumentMatchingDone As Boolean
Get
Return (_smallFields And SmallFieldMask.ArgumentMatchingDone) <> 0
End Get
End Property
Public Sub SetArgumentMatchingDone()
_smallFields = _smallFields Or SmallFieldMask.ArgumentMatchingDone
End Sub
Public ReadOnly Property RequiresNarrowingConversion As Boolean
Get
Return (_smallFields And SmallFieldMask.RequiresNarrowingConversion) <> 0
End Get
End Property
Public Sub SetRequiresNarrowingConversion()
_smallFields = _smallFields Or SmallFieldMask.RequiresNarrowingConversion
End Sub
Public ReadOnly Property RequiresNarrowingNotFromObject As Boolean
Get
Return (_smallFields And SmallFieldMask.RequiresNarrowingNotFromObject) <> 0
End Get
End Property
Public Sub SetRequiresNarrowingNotFromObject()
_smallFields = _smallFields Or SmallFieldMask.RequiresNarrowingNotFromObject
End Sub
Public ReadOnly Property RequiresNarrowingNotFromNumericConstant As Boolean
Get
Return (_smallFields And SmallFieldMask.RequiresNarrowingNotFromNumericConstant) <> 0
End Get
End Property
Public Sub SetRequiresNarrowingNotFromNumericConstant()
Debug.Assert(RequiresNarrowingConversion)
IgnoreExtensionMethods = False
_smallFields = _smallFields Or SmallFieldMask.RequiresNarrowingNotFromNumericConstant
End Sub
''' <summary>
''' Only bits specific to delegate relaxation level are returned.
''' </summary>
Public ReadOnly Property MaxDelegateRelaxationLevel As ConversionKind
Get
Return CType(_smallFields And SmallFieldMask.DelegateRelaxationLevelMask, ConversionKind)
End Get
End Property
Public Sub RegisterDelegateRelaxationLevel(conversionKind As ConversionKind)
Dim relaxationLevel As Integer = (conversionKind And SmallFieldMask.DelegateRelaxationLevelMask)
If relaxationLevel > (_smallFields And SmallFieldMask.DelegateRelaxationLevelMask) Then
Debug.Assert(relaxationLevel <= ConversionKind.DelegateRelaxationLevelNarrowing)
If relaxationLevel = ConversionKind.DelegateRelaxationLevelNarrowing Then
IgnoreExtensionMethods = False
End If
_smallFields = (_smallFields And (Not SmallFieldMask.DelegateRelaxationLevelMask)) Or relaxationLevel
End If
End Sub
Public Sub SetSomeInferenceFailed()
_smallFields = _smallFields Or SmallFieldMask.SomeInferenceFailed
End Sub
Public ReadOnly Property SomeInferenceFailed As Boolean
Get
Return (_smallFields And SmallFieldMask.SomeInferenceFailed) <> 0
End Get
End Property
Public Sub SetIllegalInAttribute()
_smallFields = _smallFields Or SmallFieldMask.IllegalInAttribute
End Sub
Public ReadOnly Property IsIllegalInAttribute As Boolean
Get
Return (_smallFields And SmallFieldMask.IllegalInAttribute) <> 0
End Get
End Property
Public Sub SetAllFailedInferenceIsDueToObject()
_smallFields = _smallFields Or SmallFieldMask.AllFailedInferenceIsDueToObject
End Sub
Public ReadOnly Property AllFailedInferenceIsDueToObject As Boolean
Get
Return (_smallFields And SmallFieldMask.AllFailedInferenceIsDueToObject) <> 0
End Get
End Property
Public Sub SetInferenceErrorReasons(reasons As InferenceErrorReasons)
Dim value As Integer = CInt(reasons) << SmallFieldMask.InferenceErrorReasonsShift
Debug.Assert((value And SmallFieldMask.InferenceErrorReasonsMask) = value)
_smallFields = (_smallFields And (Not SmallFieldMask.InferenceErrorReasonsMask)) Or (value And SmallFieldMask.InferenceErrorReasonsMask)
End Sub
Public ReadOnly Property InferenceErrorReasons As InferenceErrorReasons
Get
Return CType((_smallFields And SmallFieldMask.InferenceErrorReasonsMask) >> SmallFieldMask.InferenceErrorReasonsShift, InferenceErrorReasons)
End Get
End Property
Public Property State As CandidateAnalysisResultState
Get
Return CType(_smallFields And SmallFieldMask.State, CandidateAnalysisResultState)
End Get
Set(value As CandidateAnalysisResultState)
Debug.Assert((value And (Not SmallFieldMask.State)) = 0)
Dim newFields = _smallFields And (Not SmallFieldMask.State)
newFields = newFields Or value
_smallFields = newFields
End Set
End Property
Public Property IgnoreExtensionMethods As Boolean
Get
Return (_smallFields And SmallFieldMask.IgnoreExtensionMethods) <> 0
End Get
Set(value As Boolean)
If value Then
_smallFields = _smallFields Or SmallFieldMask.IgnoreExtensionMethods
Else
_smallFields = _smallFields And (Not SmallFieldMask.IgnoreExtensionMethods)
End If
End Set
End Property
Private _smallFields As Integer
Public Candidate As Candidate
Public ExpandedParamArrayArgumentsUsed As Integer
Public EquallyApplicableCandidatesBucket As Integer
' When this is null, it means that arguments map to parameters sequentially
Public ArgsToParamsOpt As ImmutableArray(Of Integer)
' When these are null, it means that all conversions are identity conversions
Public ConversionsOpt As ImmutableArray(Of KeyValuePair(Of ConversionKind, MethodSymbol))
Public ConversionsBackOpt As ImmutableArray(Of KeyValuePair(Of ConversionKind, MethodSymbol))
' When this is null, it means that there aren't any optional arguments
' This array is indexed by parameter index, not the argument index.
Public OptionalArguments As ImmutableArray(Of OptionalArgument)
Public ReadOnly Property UsedOptionalParameterDefaultValue As Boolean
Get
Return Not OptionalArguments.IsDefault
End Get
End Property
Public NotInferredTypeArguments As BitVector
Public TypeArgumentInferenceDiagnosticsOpt As BindingDiagnosticBag
Public Sub New(candidate As Candidate, state As CandidateAnalysisResultState)
Me.Candidate = candidate
Me.State = state
End Sub
Public Sub New(candidate As Candidate)
Me.Candidate = candidate
Me.State = CandidateAnalysisResultState.Applicable
End Sub
End Structure
' Represents a simple overload resolution result
Friend Structure OverloadResolutionResult
Private ReadOnly _bestResult As CandidateAnalysisResult?
Private ReadOnly _allResults As ImmutableArray(Of CandidateAnalysisResult)
Private ReadOnly _resolutionIsLateBound As Boolean
Private ReadOnly _remainingCandidatesRequireNarrowingConversion As Boolean
Public ReadOnly AsyncLambdaSubToFunctionMismatch As ImmutableArray(Of BoundExpression)
' Create an overload resolution result from a full set of results.
Public Sub New(allResults As ImmutableArray(Of CandidateAnalysisResult), resolutionIsLateBound As Boolean,
remainingCandidatesRequireNarrowingConversion As Boolean,
asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression))
Me._allResults = allResults
Me._resolutionIsLateBound = resolutionIsLateBound
Me._remainingCandidatesRequireNarrowingConversion = remainingCandidatesRequireNarrowingConversion
Me.AsyncLambdaSubToFunctionMismatch = If(asyncLambdaSubToFunctionMismatch Is Nothing,
ImmutableArray(Of BoundExpression).Empty,
asyncLambdaSubToFunctionMismatch.ToArray().AsImmutableOrNull())
If Not resolutionIsLateBound Then
Me._bestResult = GetBestResult(allResults)
End If
End Sub
Public ReadOnly Property Candidates As ImmutableArray(Of CandidateAnalysisResult)
Get
Return _allResults
End Get
End Property
' Returns the best method. Note that if overload resolution succeeded, the set of conversion kinds will NOT be returned.
Public ReadOnly Property BestResult As CandidateAnalysisResult?
Get
Return _bestResult
End Get
End Property
Public ReadOnly Property ResolutionIsLateBound As Boolean
Get
Return _resolutionIsLateBound
End Get
End Property
''' <summary>
''' This might simplify error reporting. If not, consider getting rid of this property.
''' </summary>
Public ReadOnly Property RemainingCandidatesRequireNarrowingConversion As Boolean
Get
Return _remainingCandidatesRequireNarrowingConversion
End Get
End Property
Private Shared Function GetBestResult(allResults As ImmutableArray(Of CandidateAnalysisResult)) As CandidateAnalysisResult?
Dim best As CandidateAnalysisResult? = Nothing
Dim i As Integer = 0
While i < allResults.Length
Dim current = allResults(i)
If current.State = CandidateAnalysisResultState.Applicable Then
If best IsNot Nothing Then
Return Nothing
End If
best = current
End If
i = i + 1
End While
Return best
End Function
End Structure
''' <summary>
''' Perform overload resolution on the given method or property group, with the given arguments and names.
''' The names can be null if no names were supplied to any arguments.
''' </summary>
Public Shared Function MethodOrPropertyInvocationOverloadResolution(
group As BoundMethodOrPropertyGroup,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
callerInfoOpt As SyntaxNode,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional includeEliminatedCandidates As Boolean = False,
Optional forceExpandedForm As Boolean = False
) As OverloadResolutionResult
If group.Kind = BoundKind.MethodGroup Then
Dim methodGroup = DirectCast(group, BoundMethodGroup)
Return MethodInvocationOverloadResolution(
methodGroup,
arguments,
argumentNames,
binder,
callerInfoOpt,
useSiteInfo,
includeEliminatedCandidates,
forceExpandedForm:=forceExpandedForm)
Else
Dim propertyGroup = DirectCast(group, BoundPropertyGroup)
Return PropertyInvocationOverloadResolution(
propertyGroup,
arguments,
argumentNames,
binder,
callerInfoOpt,
useSiteInfo,
includeEliminatedCandidates)
End If
End Function
''' <summary>
''' Perform overload resolution on the given method group, with the given arguments.
''' </summary>
Public Shared Function QueryOperatorInvocationOverloadResolution(
methodGroup As BoundMethodGroup,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional includeEliminatedCandidates As Boolean = False
) As OverloadResolutionResult
Return MethodInvocationOverloadResolution(
methodGroup,
arguments,
Nothing,
binder,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo,
includeEliminatedCandidates:=includeEliminatedCandidates,
lateBindingIsAllowed:=False,
isQueryOperatorInvocation:=True)
End Function
''' <summary>
''' Perform overload resolution on the given method group, with the given arguments and names.
''' The names can be null if no names were supplied to any arguments.
''' </summary>
Public Shared Function MethodInvocationOverloadResolution(
methodGroup As BoundMethodGroup,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
callerInfoOpt As SyntaxNode,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional includeEliminatedCandidates As Boolean = False,
Optional delegateReturnType As TypeSymbol = Nothing,
Optional delegateReturnTypeReferenceBoundNode As BoundNode = Nothing,
Optional lateBindingIsAllowed As Boolean = True,
Optional isQueryOperatorInvocation As Boolean = False,
Optional forceExpandedForm As Boolean = False
) As OverloadResolutionResult
Debug.Assert(methodGroup.ResultKind = LookupResultKind.Good OrElse methodGroup.ResultKind = LookupResultKind.Inaccessible)
Dim typeArguments = If(methodGroup.TypeArgumentsOpt IsNot Nothing, methodGroup.TypeArgumentsOpt.Arguments, ImmutableArray(Of TypeSymbol).Empty)
' To simplify code later
If typeArguments.IsDefault Then
typeArguments = ImmutableArray(Of TypeSymbol).Empty
End If
If arguments.IsDefault Then
arguments = ImmutableArray(Of BoundExpression).Empty
End If
Dim candidates = ArrayBuilder(Of CandidateAnalysisResult).GetInstance()
Dim instanceCandidates As ArrayBuilder(Of Candidate) = ArrayBuilder(Of Candidate).GetInstance()
Dim curriedCandidates As ArrayBuilder(Of Candidate) = ArrayBuilder(Of Candidate).GetInstance()
Dim methods As ImmutableArray(Of MethodSymbol) = methodGroup.Methods
If Not methods.IsDefault Then
' Create MethodCandidates for ordinary methods and ExtensionMethodCandidates
' for curried methods, separating them.
For Each method As MethodSymbol In methods
If method.ReducedFrom Is Nothing Then
instanceCandidates.Add(New MethodCandidate(method))
Else
curriedCandidates.Add(New ExtensionMethodCandidate(method))
End If
Next
End If
Dim asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) = Nothing
Dim applicableNarrowingCandidateCount As Integer = 0
Dim applicableInstanceCandidateCount As Integer = 0
' First collect instance methods.
If instanceCandidates.Count > 0 Then
CollectOverloadedCandidates(
binder, candidates, instanceCandidates, typeArguments,
arguments, argumentNames, delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, isQueryOperatorInvocation, forceExpandedForm, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
applicableInstanceCandidateCount = EliminateNotApplicableToArguments(methodGroup, candidates, arguments, argumentNames, binder,
applicableNarrowingCandidateCount, asyncLambdaSubToFunctionMismatch,
callerInfoOpt,
forceExpandedForm,
useSiteInfo)
End If
instanceCandidates.Free()
instanceCandidates = Nothing
' Now add extension methods if they should be considered.
Dim addedExtensionMethods As Boolean = False
If ShouldConsiderExtensionMethods(candidates) Then
' Request additional extension methods, if any available.
If methodGroup.ResultKind = LookupResultKind.Good Then
methods = methodGroup.AdditionalExtensionMethods(useSiteInfo)
For Each method As MethodSymbol In methods
curriedCandidates.Add(New ExtensionMethodCandidate(method))
Next
End If
If curriedCandidates.Count > 0 Then
addedExtensionMethods = True
CollectOverloadedCandidates(
binder, candidates, curriedCandidates, typeArguments,
arguments, argumentNames, delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, isQueryOperatorInvocation, forceExpandedForm, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
End If
End If
curriedCandidates.Free()
Dim result As OverloadResolutionResult
If applicableInstanceCandidateCount = 0 AndAlso Not addedExtensionMethods Then
result = ReportOverloadResolutionFailedOrLateBound(candidates, applicableInstanceCandidateCount, lateBindingIsAllowed AndAlso binder.OptionStrict <> OptionStrict.On, asyncLambdaSubToFunctionMismatch)
Else
result = ResolveOverloading(methodGroup, candidates, arguments, argumentNames, delegateReturnType, lateBindingIsAllowed, binder, asyncLambdaSubToFunctionMismatch, callerInfoOpt, forceExpandedForm,
useSiteInfo)
End If
candidates.Free()
Return result
End Function
Private Shared Function ReportOverloadResolutionFailedOrLateBound(candidates As ArrayBuilder(Of CandidateAnalysisResult),
applicableNarrowingCandidateCount As Integer,
lateBindingIsAllowed As Boolean,
asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression)) As OverloadResolutionResult
Dim isLateBound As Boolean = False
If lateBindingIsAllowed Then
For Each candidate In candidates
If candidate.State = CandidateAnalysisResultState.TypeInferenceFailed Then
If candidate.AllFailedInferenceIsDueToObject AndAlso Not candidate.Candidate.IsExtensionMethod Then
isLateBound = True
Exit For
End If
End If
Next
End If
Return New OverloadResolutionResult(candidates.ToImmutable, isLateBound, applicableNarrowingCandidateCount > 0, asyncLambdaSubToFunctionMismatch)
End Function
''' <summary>
''' Perform overload resolution on the given array of property symbols.
''' </summary>
Public Shared Function PropertyInvocationOverloadResolution(
propertyGroup As BoundPropertyGroup,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
callerInfoOpt As SyntaxNode,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional includeEliminatedCandidates As Boolean = False
) As OverloadResolutionResult
Debug.Assert(propertyGroup.ResultKind = LookupResultKind.Good OrElse propertyGroup.ResultKind = LookupResultKind.Inaccessible)
Dim properties As ImmutableArray(Of PropertySymbol) = propertyGroup.Properties
' To simplify code later
If arguments.IsDefault Then
arguments = ImmutableArray(Of BoundExpression).Empty
End If
Dim results = ArrayBuilder(Of CandidateAnalysisResult).GetInstance()
Dim candidates = ArrayBuilder(Of Candidate).GetInstance(properties.Length - 1)
For i As Integer = 0 To properties.Length - 1 Step 1
candidates.Add(New PropertyCandidate(properties(i)))
Next
Dim asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) = Nothing
CollectOverloadedCandidates(binder, results, candidates, ImmutableArray(Of TypeSymbol).Empty,
arguments, argumentNames, Nothing, Nothing, includeEliminatedCandidates,
isQueryOperatorInvocation:=False, forceExpandedForm:=False, asyncLambdaSubToFunctionMismatch:=asyncLambdaSubToFunctionMismatch,
useSiteInfo:=useSiteInfo)
Debug.Assert(asyncLambdaSubToFunctionMismatch Is Nothing)
candidates.Free()
Dim result = ResolveOverloading(propertyGroup, results, arguments, argumentNames, delegateReturnType:=Nothing, lateBindingIsAllowed:=True, binder:=binder,
asyncLambdaSubToFunctionMismatch:=asyncLambdaSubToFunctionMismatch, callerInfoOpt:=callerInfoOpt, forceExpandedForm:=False,
useSiteInfo:=useSiteInfo)
results.Free()
Return result
End Function
''' <summary>
''' Given instance method candidates gone through applicability analysis,
''' figure out if we should consider extension methods, if any.
''' </summary>
Private Shared Function ShouldConsiderExtensionMethods(
candidates As ArrayBuilder(Of CandidateAnalysisResult)
) As Boolean
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim candidate = candidates(i)
Debug.Assert(Not candidate.Candidate.IsExtensionMethod)
If candidate.IgnoreExtensionMethods Then
Return False
End If
Next
Return True
End Function
Private Shared Function ResolveOverloading(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
lateBindingIsAllowed As Boolean,
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
callerInfoOpt As SyntaxNode,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As OverloadResolutionResult
Debug.Assert(argumentNames.IsDefault OrElse argumentNames.Length = arguments.Length)
Dim applicableCandidates As Integer
Dim resolutionIsLateBound As Boolean = False
Dim narrowingCandidatesRemainInTheSet As Boolean = False
Dim applicableNarrowingCandidates As Integer = 0
'TODO: Where does this fit?
'Semantics::ResolveOverloading
'// See if type inference failed for all candidates and it failed from
'// Object. For this scenario, in non-strict mode, treat the call
'// as latebound.
'§11.8.1 Overloaded Method Resolution
'2. Next, eliminate all members from the set that are inaccessible or not applicable to the argument list.
' Note, similar to Dev10 compiler this process will eliminate candidates requiring narrowing conversions
' if strict semantics is used, exception are candidates that require narrowing only from numeric constants.
applicableCandidates = EliminateNotApplicableToArguments(methodOrPropertyGroup, candidates, arguments, argumentNames, binder,
applicableNarrowingCandidates, asyncLambdaSubToFunctionMismatch,
callerInfoOpt,
forceExpandedForm,
useSiteInfo)
If applicableCandidates < 2 Then
narrowingCandidatesRemainInTheSet = (applicableNarrowingCandidates > 0)
GoTo ResolutionComplete
End If
' §11.8.1 Overloaded Method Resolution.
' 7.8. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
' delegate types in M match exactly, but not all do in N, eliminate N from the set.
' 7.9. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
' delegate types in M are widening conversions, but not all are in N, eliminate N from the set.
'
' The spec implies that this rule is applied to the set of most applicable candidate as one of the tie breaking rules.
' However, doing it there wouldn't have any effect because all candidates in the set of most applicable candidates
' are equally applicable, therefore, have the same types for corresponding parameters. Thus all the candidates
' have exactly the same delegate relaxation level and none would be eliminated.
' Dev10 applies this rule much earlier, even before eliminating narrowing candidates, and it does it across the board.
' I am going to do the same.
applicableCandidates = ShadowBasedOnDelegateRelaxation(candidates, applicableNarrowingCandidates)
If applicableCandidates < 2 Then
narrowingCandidatesRemainInTheSet = (applicableNarrowingCandidates > 0)
GoTo ResolutionComplete
End If
' §11.8.1 Overloaded Method Resolution.
'7.7. If M and N both required type inference to produce type arguments, and M did not
' require determining the dominant type for any of its type arguments (i.e. each the
' type arguments inferred to a single type), but N did, eliminate N from the set.
' Despite what the spec says, this rule is applied after shadowing based on delegate relaxation
' level, however it needs other tie breaking rules applied to equally applicable candidates prior
' to figuring out the minimal inference level to use as the filter.
ShadowBasedOnInferenceLevel(candidates, arguments, Not argumentNames.IsDefault, delegateReturnType, binder,
applicableCandidates, applicableNarrowingCandidates, useSiteInfo)
If applicableCandidates < 2 Then
narrowingCandidatesRemainInTheSet = (applicableNarrowingCandidates > 0)
GoTo ResolutionComplete
End If
'3. Next, eliminate all members from the set that require narrowing conversions
' to be applicable to the argument list, except for the case where the argument
' expression type is Object.
'4. Next, eliminate all remaining members from the set that require narrowing coercions
' to be applicable to the argument list. If the set is empty, the type containing the
' method group is not an interface, and strict semantics are not being used, the
' invocation target expression is reclassified as a late-bound method access.
' Otherwise, the normal rules apply.
If applicableCandidates = applicableNarrowingCandidates Then
' All remaining candidates are narrowing, deal with them.
narrowingCandidatesRemainInTheSet = True
applicableCandidates = AnalyzeNarrowingCandidates(candidates, arguments, delegateReturnType,
lateBindingIsAllowed AndAlso binder.OptionStrict <> OptionStrict.On, binder,
resolutionIsLateBound,
useSiteInfo)
Else
If applicableNarrowingCandidates > 0 Then
Debug.Assert(applicableNarrowingCandidates < applicableCandidates)
applicableCandidates = EliminateNarrowingCandidates(candidates)
Debug.Assert(applicableCandidates > 0)
If applicableCandidates < 2 Then
GoTo ResolutionComplete
End If
End If
'5. Next, if any instance methods remain in the set,
' eliminate all extension methods from the set.
' !!! I don't think we need to do this explicitly. ResolveMethodOverloading doesn't add
' !!! extension methods in the list if we need to remove them here.
'applicableCandidates = EliminateExtensionMethodsInPresenceOfInstanceMethods(candidates)
'If applicableCandidates < 2 Then
' GoTo ResolutionComplete
'End If
'6. Next, if, given any two members of the set, M and N, M is more applicable than N
' to the argument list, eliminate N from the set. If more than one member remains
' in the set and the remaining members are not equally applicable to the argument
' list, a compile-time error results.
'7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
applicableCandidates = EliminateLessApplicableToTheArguments(candidates, arguments, delegateReturnType,
False, ' appliedTieBreakingRules
binder, useSiteInfo)
End If
ResolutionComplete:
If Not resolutionIsLateBound AndAlso applicableCandidates = 0 Then
Return ReportOverloadResolutionFailedOrLateBound(candidates, applicableCandidates, lateBindingIsAllowed AndAlso binder.OptionStrict <> OptionStrict.On, asyncLambdaSubToFunctionMismatch)
End If
Return New OverloadResolutionResult(candidates.ToImmutable(), resolutionIsLateBound, narrowingCandidatesRemainInTheSet, asyncLambdaSubToFunctionMismatch)
End Function
Private Shared Function EliminateNarrowingCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult)
) As Integer
Dim applicableCandidates As Integer = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
If current.RequiresNarrowingConversion Then
current.State = CandidateAnalysisResultState.RequiresNarrowing
candidates(i) = current
Else
applicableCandidates += 1
End If
End If
Next
Return applicableCandidates
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 6. Next, if, given any two members of the set, M and N, M is more applicable than N
''' to the argument list, eliminate N from the set. If more than one member remains
''' in the set and the remaining members are not equally applicable to the argument
''' list, a compile-time error results.
''' 7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
'''
''' Returns amount of applicable candidates left.
'''
''' Note that less applicable candidates are going to be eliminated if and only if there are most applicable
''' candidates.
''' </summary>
Private Shared Function EliminateLessApplicableToTheArguments(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
appliedTieBreakingRules As Boolean,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional mostApplicableMustNarrowOnlyFromNumericConstants As Boolean = False
) As Integer
Dim applicableCandidates As Integer
Dim indexesOfEqualMostApplicableCandidates As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance()
If FastFindMostApplicableCandidates(candidates, arguments, indexesOfEqualMostApplicableCandidates, binder, useSiteInfo) AndAlso
(mostApplicableMustNarrowOnlyFromNumericConstants = False OrElse
candidates(indexesOfEqualMostApplicableCandidates(0)).RequiresNarrowingNotFromNumericConstant = False OrElse
indexesOfEqualMostApplicableCandidates.Count = CountApplicableCandidates(candidates)) Then
' We have most applicable candidates.
' Mark those that lost applicability comparison.
' Applicable candidates with indexes before the first value in indexesOfEqualMostApplicableCandidates,
' after the last value in indexesOfEqualMostApplicableCandidates and in between consecutive values in
' indexesOfEqualMostApplicableCandidates are less applicable.
Debug.Assert(indexesOfEqualMostApplicableCandidates.Count > 0)
Dim nextMostApplicable As Integer = 0 ' and index into indexesOfEqualMostApplicableCandidates
Dim indexOfNextMostApplicable As Integer = indexesOfEqualMostApplicableCandidates(nextMostApplicable)
For i As Integer = 0 To candidates.Count - 1 Step 1
If i = indexOfNextMostApplicable Then
nextMostApplicable += 1
If nextMostApplicable < indexesOfEqualMostApplicableCandidates.Count Then
indexOfNextMostApplicable = indexesOfEqualMostApplicableCandidates(nextMostApplicable)
Else
indexOfNextMostApplicable = candidates.Count
End If
Continue For
End If
Dim contender As CandidateAnalysisResult = candidates(i)
If contender.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
contender.State = CandidateAnalysisResultState.LessApplicable
candidates(i) = contender
Next
' Apply tie-breaking rules
If Not appliedTieBreakingRules Then
applicableCandidates = ApplyTieBreakingRules(candidates, indexesOfEqualMostApplicableCandidates, arguments, delegateReturnType, binder, useSiteInfo)
Else
applicableCandidates = indexesOfEqualMostApplicableCandidates.Count
End If
ElseIf Not appliedTieBreakingRules Then
' Overload resolution failed, we couldn't find most applicable candidates.
' We still need to apply shadowing rules to the sets of equally applicable candidates,
' this will provide better error reporting experience. As we are doing this, we will redo
' applicability comparisons that we've done earlier in FastFindMostApplicableCandidates, but we are willing to
' pay the price for erroneous code.
applicableCandidates = ApplyTieBreakingRulesToEquallyApplicableCandidates(candidates, arguments, delegateReturnType, binder, useSiteInfo)
Else
applicableCandidates = CountApplicableCandidates(candidates)
End If
indexesOfEqualMostApplicableCandidates.Free()
Return applicableCandidates
End Function
Private Shared Function CountApplicableCandidates(candidates As ArrayBuilder(Of CandidateAnalysisResult)) As Integer
Dim applicableCandidates As Integer = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
If candidates(i).State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
applicableCandidates += 1
Next
Return applicableCandidates
End Function
''' <summary>
''' Returns amount of applicable candidates left.
''' </summary>
Private Shared Function ApplyTieBreakingRulesToEquallyApplicableCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Integer
' First, let's break all remaining candidates into buckets of equally applicable candidates
Dim buckets = GroupEquallyApplicableCandidates(candidates, arguments, binder)
Debug.Assert(buckets.Count > 0)
Dim applicableCandidates As Integer = 0
' Apply tie-breaking rules
For i As Integer = 0 To buckets.Count - 1 Step 1
applicableCandidates += ApplyTieBreakingRules(candidates, buckets(i), arguments, delegateReturnType, binder, useSiteInfo)
Next
' Release memory we no longer need.
For i As Integer = 0 To buckets.Count - 1 Step 1
buckets(i).Free()
Next
buckets.Free()
Return applicableCandidates
End Function
''' <summary>
''' Returns True if there are most applicable candidates.
'''
''' indexesOfMostApplicableCandidates will contain indexes of equally applicable candidates, which are most applicable
''' by comparison to the other (non-equal) candidates. The indexes will be in ascending order.
''' </summary>
Private Shared Function FastFindMostApplicableCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
indexesOfMostApplicableCandidates As ArrayBuilder(Of Integer),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
Dim mightBeTheMostApplicableIndex As Integer = -1
Dim mightBeTheMostApplicable As CandidateAnalysisResult = Nothing
indexesOfMostApplicableCandidates.Clear()
' Use linear complexity algorithm to find the first most applicable candidate.
' We are saying "the first" because there could be a number of candidates equally applicable
' by comparison to the one we find, their indexes are collected in indexesOfMostApplicableCandidates.
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim contender As CandidateAnalysisResult = candidates(i)
If contender.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
If mightBeTheMostApplicableIndex = -1 Then
mightBeTheMostApplicableIndex = i
mightBeTheMostApplicable = contender
indexesOfMostApplicableCandidates.Add(i)
Else
Dim cmp As ApplicabilityComparisonResult = CompareApplicabilityToTheArguments(mightBeTheMostApplicable, contender, arguments, binder, useSiteInfo)
If cmp = ApplicabilityComparisonResult.RightIsMoreApplicable Then
mightBeTheMostApplicableIndex = i
mightBeTheMostApplicable = contender
indexesOfMostApplicableCandidates.Clear()
indexesOfMostApplicableCandidates.Add(i)
ElseIf cmp = ApplicabilityComparisonResult.Undefined Then
mightBeTheMostApplicableIndex = -1
indexesOfMostApplicableCandidates.Clear()
ElseIf cmp = ApplicabilityComparisonResult.EquallyApplicable Then
indexesOfMostApplicableCandidates.Add(i)
Else
Debug.Assert(cmp = ApplicabilityComparisonResult.LeftIsMoreApplicable)
End If
End If
Next
For i As Integer = 0 To mightBeTheMostApplicableIndex - 1 Step 1
Dim contender As CandidateAnalysisResult = candidates(i)
If contender.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
Dim cmp As ApplicabilityComparisonResult = CompareApplicabilityToTheArguments(mightBeTheMostApplicable, contender, arguments, binder, useSiteInfo)
If cmp = ApplicabilityComparisonResult.RightIsMoreApplicable OrElse
cmp = ApplicabilityComparisonResult.Undefined OrElse
cmp = ApplicabilityComparisonResult.EquallyApplicable Then
' We do this for equal applicability too because this contender was dropped during the first loop, so,
' if we continue, the mightBeTheMostApplicable candidate will be definitely dropped too.
mightBeTheMostApplicableIndex = -1
Exit For
Else
Debug.Assert(cmp = ApplicabilityComparisonResult.LeftIsMoreApplicable)
End If
Next
Return (mightBeTheMostApplicableIndex > -1)
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
''' </summary>
Private Shared Function ApplyTieBreakingRules(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
bucket As ArrayBuilder(Of Integer),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Integer
Dim leftWins As Boolean
Dim rightWins As Boolean
Dim applicableCandidates As Integer = bucket.Count
For i = 0 To bucket.Count - 1 Step 1
Dim left = candidates(bucket(i))
If left.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
For j = i + 1 To bucket.Count - 1 Step 1
Dim right = candidates(bucket(j))
If right.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
If ShadowBasedOnTieBreakingRules(left, right, arguments, delegateReturnType, leftWins, rightWins, binder, useSiteInfo) Then
Debug.Assert(Not (leftWins AndAlso rightWins))
If leftWins Then
right.State = CandidateAnalysisResultState.Shadowed
candidates(bucket(j)) = right
applicableCandidates -= 1
Else
Debug.Assert(rightWins)
left.State = CandidateAnalysisResultState.Shadowed
candidates(bucket(i)) = left
applicableCandidates -= 1
Exit For
End If
End If
Next
Next
Debug.Assert(applicableCandidates >= 0)
Return applicableCandidates
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
''' </summary>
Private Shared Function ShadowBasedOnTieBreakingRules(
left As CandidateAnalysisResult,
right As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
ByRef leftWins As Boolean,
ByRef rightWins As Boolean,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
' Let's apply various shadowing and tie-breaking rules
' from section 7 of §11.8.1 Overloaded Method Resolution.
leftWins = False
rightWins = False
'• If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
If ShadowBasedOnParamArrayUsage(left, right, leftWins, rightWins) Then
Return True
End If
'7.1. If M is defined in a more derived type than N, eliminate N from the set.
' This rule also applies to the types that extension methods are defined on.
'7.2. If M and N are extension methods and the target type of M is a class or
' structure and the target type of N is an interface, eliminate N from the set.
If ShadowBasedOnReceiverType(left, right, leftWins, rightWins, useSiteInfo) Then
Return True ' I believe we can get here only in presence of named arguments and optional parameters. Otherwise, CombineCandidates takes care of this shadowing.
End If
'7.3. If M and N are extension methods and the target type of M has fewer type
' parameters than the target type of N, eliminate N from the set.
' !!! Note that spec talks about "fewer type parameters", but it is not really about count.
' !!! It is about one refers to a type parameter and the other one doesn't.
If ShadowBasedOnExtensionMethodTargetTypeGenericity(left, right, leftWins, rightWins) Then
Return True ' I believe we can get here only in presence of named arguments and optional parameters. Otherwise, CombineCandidates takes care of this shadowing.
End If
'7.4. If M is less generic than N, eliminate N from the set.
If ShadowBasedOnGenericity(left, right, leftWins, rightWins, arguments, binder) Then
Return True
End If
'7.5. If M is not an extension method and N is, eliminate N from the set.
'7.6. If M and N are extension methods and M was found before N, eliminate N from the set.
If ShadowBasedOnExtensionVsInstanceAndPrecedence(left, right, leftWins, rightWins) Then
Return True
End If
'7.7. If M and N both required type inference to produce type arguments, and M did not
' require determining the dominant type for any of its type arguments (i.e. each the
' type arguments inferred to a single type), but N did, eliminate N from the set.
' The spec is incorrect, this shadowing doesn't belong here, it is applied across the board
' after these tie breaking rules. For more information, see comment in ResolveOverloading.
'7.8. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding delegate types in M match exactly, but not all do in N, eliminate N from the set.
'7.9. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding delegate types in M are widening conversions, but not all are in N, eliminate N from the set.
' The spec is incorrect, this shadowing doesn't belong here, it is applied much earlier.
' For more information, see comment in ResolveOverloading.
' 7.9. If M did not use any optional parameter defaults in place of explicit
' arguments, but N did, then eliminate N from the set.
'
' !!!WARNING!!! The index (7.9) is based on "VB11 spec [draft 3]" version of documentation rather
' than Dev10 documentation.
If ShadowBasedOnOptionalParametersDefaultsUsed(left, right, leftWins, rightWins) Then
Return True
End If
'7.10. If the overload resolution is being done to resolve the target of a delegate-creation expression from an AddressOf expression and M is a function, while N is a subroutine, eliminate N from the set.
If ShadowBasedOnSubOrFunction(left, right, delegateReturnType, leftWins, rightWins) Then
Return True
End If
' 7.10. Before type arguments have been substituted, if M has greater depth of
' genericity (Section 11.8.1.3) than N, then eliminate N from the set.
'
' !!!WARNING!!! The index (7.10) is based on "VB11 spec [draft 3]" version of documentation
' rather than Dev10 documentation.
'
' NOTE: Dev11 puts this analysis in a second phase with the first phase
' performing analysis of { $11.8.1:6 + 7.9/7.10/7.11/7.8 }, see comments in
' OverloadResolution.cpp: bool Semantics::AreProceduresEquallySpecific(...)
'
' Placing this analysis here seems to be more natural than
' matching Dev11 implementation
If ShadowBasedOnDepthOfGenericity(left, right, leftWins, rightWins, arguments, binder) Then
Return True
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.10. If the overload resolution is being done to resolve the target of a
''' delegate-creation expression from an AddressOf expression and M is a
''' function, while N is a subroutine, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnSubOrFunction(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
delegateReturnType As TypeSymbol,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
' !!! Actually, the spec isn't accurate here. If the target delegate is a Sub, we prefer a Sub. !!!
' !!! If the target delegate is a Function, we prefer a Function. !!!
If delegateReturnType Is Nothing Then
Return False
End If
Dim leftReturnsVoid As Boolean = left.Candidate.ReturnType.IsVoidType()
Dim rightReturnsVoid As Boolean = right.Candidate.ReturnType.IsVoidType()
If leftReturnsVoid = rightReturnsVoid Then
Return False
End If
If delegateReturnType.IsVoidType() = leftReturnsVoid Then
leftWins = True
Return True
End If
Debug.Assert(delegateReturnType.IsVoidType() = rightReturnsVoid)
rightWins = True
Return True
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.8. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
''' delegate types in M match exactly, but not all do in N, eliminate N from the set.
''' 7.9. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
''' delegate types in M are widening conversions, but not all are in N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnDelegateRelaxation(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
ByRef applicableNarrowingCandidates As Integer
) As Integer
' Find the minimal MaxDelegateRelaxationLevel
Dim minMaxRelaxation As ConversionKind = ConversionKind.DelegateRelaxationLevelInvalid
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
Dim relaxation As ConversionKind = current.MaxDelegateRelaxationLevel
If relaxation < minMaxRelaxation Then
minMaxRelaxation = relaxation
End If
End If
Next
' Now eliminate all candidates with relaxation level bigger than the minimal.
Dim applicableCandidates As Integer = 0
applicableNarrowingCandidates = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
Dim relaxation As ConversionKind = current.MaxDelegateRelaxationLevel
If relaxation > minMaxRelaxation Then
current.State = CandidateAnalysisResultState.Shadowed
candidates(i) = current
Else
applicableCandidates += 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates += 1
End If
End If
Next
Return applicableCandidates
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.9. If M did not use any optional parameter defaults in place of explicit
''' arguments, but N did, then eliminate N from the set.
'''
''' !!!WARNING!!! The index (7.9) is based on "VB11 spec [draft 3]" version of documentation rather
''' than Dev10 documentation.
''' TODO: Update indexes of other overload method resolution rules
''' </summary>
Private Shared Function ShadowBasedOnOptionalParametersDefaultsUsed(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
Dim leftUsesOptionalParameterDefaults As Boolean = left.UsedOptionalParameterDefaultValue
If leftUsesOptionalParameterDefaults = right.UsedOptionalParameterDefaultValue Then
Return False ' No winner
End If
If Not leftUsesOptionalParameterDefaults Then
leftWins = True
Else
rightWins = True
End If
Return True
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.7. If M and N both required type inference to produce type arguments, and M did not
''' require determining the dominant type for any of its type arguments (i.e. each the
''' type arguments inferred to a single type), but N did, eliminate N from the set.
''' </summary>
Private Shared Sub ShadowBasedOnInferenceLevel(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
haveNamedArguments As Boolean,
delegateReturnType As TypeSymbol,
binder As Binder,
ByRef applicableCandidates As Integer,
ByRef applicableNarrowingCandidates As Integer,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(Not haveNamedArguments OrElse Not candidates(0).Candidate.IsOperator)
' See if there are candidates with different InferenceLevel
Dim haveDifferentInferenceLevel As Boolean = False
Dim theOnlyInferenceLevel As TypeArgumentInference.InferenceLevel = CType(Byte.MaxValue, TypeArgumentInference.InferenceLevel)
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = current.InferenceLevel
If theOnlyInferenceLevel = Byte.MaxValue Then
theOnlyInferenceLevel = inferenceLevel
ElseIf inferenceLevel <> theOnlyInferenceLevel Then
haveDifferentInferenceLevel = True
Exit For
End If
End If
Next
If Not haveDifferentInferenceLevel Then
' Nothing to do.
Return
End If
' Native compiler used to have a bug where CombineCandidates was applying shadowing in presence of named arguments
' before figuring out whether candidates are applicable. We fixed that. However, in cases when candidates were applicable
' after all, that shadowing had impact on the shadowing based on the inference level by affecting minimal inference level.
' To compensate, we will perform the CombineCandidates-style shadowing here. Note that we cannot simply call
' ApplyTieBreakingRulesToEquallyApplicableCandidates to do this because shadowing performed by CombineCandidates is more
' constrained.
If haveNamedArguments Then
Debug.Assert(Not candidates(0).Candidate.IsOperator)
Dim indexesOfApplicableCandidates = ArrayBuilder(Of Integer).GetInstance(applicableCandidates)
For i As Integer = 0 To candidates.Count - 1 Step 1
If candidates(i).State = CandidateAnalysisResultState.Applicable Then
indexesOfApplicableCandidates.Add(i)
End If
Next
Debug.Assert(indexesOfApplicableCandidates.Count = applicableCandidates)
' Sort indexes by inference level
indexesOfApplicableCandidates.Sort(New InferenceLevelComparer(candidates))
#If DEBUG Then
Dim level As TypeArgumentInference.InferenceLevel = TypeArgumentInference.InferenceLevel.None
For Each index As Integer In indexesOfApplicableCandidates
Debug.Assert(level <= candidates(index).InferenceLevel)
level = candidates(index).InferenceLevel
Next
#End If
' In order of sorted indexes, apply constrained shadowing rules looking for the first one survived.
' This will be sufficient to calculate "correct" minimal inference level. We don't have to apply
' shadowing to each pair of candidates.
For i As Integer = 0 To indexesOfApplicableCandidates.Count - 2
Dim left As CandidateAnalysisResult = candidates(indexesOfApplicableCandidates(i))
If left.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
For j As Integer = i + 1 To indexesOfApplicableCandidates.Count - 1
Dim right As CandidateAnalysisResult = candidates(indexesOfApplicableCandidates(j))
If right.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
' Shadowing is applied only to candidates that have the same types for corresponding parameters
' in virtual signatures
Dim equallyApplicable As Boolean = True
For k = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(k))
Dim rightParamType As TypeSymbol = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(k))
If Not leftParamType.IsSameTypeIgnoringAll(rightParamType) Then
' Signatures are different, shadowing rules do not apply
equallyApplicable = False
Exit For
End If
Next
If Not equallyApplicable Then
Continue For
End If
Dim signatureMatch As Boolean = True
' Compare complete signature, with no regard to arguments
If left.Candidate.ParameterCount <> right.Candidate.ParameterCount Then
signatureMatch = False
Else
For k As Integer = 0 To left.Candidate.ParameterCount - 1 Step 1
Dim leftType As TypeSymbol = left.Candidate.Parameters(k).Type
Dim rightType As TypeSymbol = right.Candidate.Parameters(k).Type
If Not leftType.IsSameTypeIgnoringAll(rightType) Then
signatureMatch = False
Exit For
End If
Next
End If
Dim leftWins As Boolean = False
Dim rightWins As Boolean = False
If (Not signatureMatch AndAlso ShadowBasedOnParamArrayUsage(left, right, leftWins, rightWins)) OrElse
ShadowBasedOnReceiverType(left, right, leftWins, rightWins, useSiteInfo) OrElse
ShadowBasedOnExtensionMethodTargetTypeGenericity(left, right, leftWins, rightWins) Then
Debug.Assert(leftWins Xor rightWins)
If leftWins Then
right.State = CandidateAnalysisResultState.Shadowed
candidates(indexesOfApplicableCandidates(j)) = right
ElseIf rightWins Then
left.State = CandidateAnalysisResultState.Shadowed
candidates(indexesOfApplicableCandidates(i)) = left
Exit For ' advance to the next left
End If
End If
Next
If left.State = CandidateAnalysisResultState.Applicable Then
' left has survived
Exit For
End If
Next
End If
' Find the minimal InferenceLevel
Dim minInferenceLevel = TypeArgumentInference.InferenceLevel.Invalid
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = current.InferenceLevel
If inferenceLevel < minInferenceLevel Then
minInferenceLevel = inferenceLevel
End If
End If
Next
' Now eliminate all candidates with inference level bigger than the minimal.
applicableCandidates = 0
applicableNarrowingCandidates = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = current.InferenceLevel
If inferenceLevel > minInferenceLevel Then
current.State = CandidateAnalysisResultState.Shadowed
candidates(i) = current
Else
applicableCandidates += 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates += 1
End If
End If
Next
' Done.
End Sub
Private Class InferenceLevelComparer
Implements IComparer(Of Integer)
Private ReadOnly _candidates As ArrayBuilder(Of CandidateAnalysisResult)
Public Sub New(candidates As ArrayBuilder(Of CandidateAnalysisResult))
_candidates = candidates
End Sub
Public Function Compare(indexX As Integer, indexY As Integer) As Integer Implements IComparer(Of Integer).Compare
Return CInt(_candidates(indexX).InferenceLevel).CompareTo(_candidates(indexY).InferenceLevel)
End Function
End Class
''' <summary>
''' §11.8.1.1 Applicability
''' </summary>
Private Shared Function CompareApplicabilityToTheArguments(
ByRef left As CandidateAnalysisResult,
ByRef right As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As ApplicabilityComparisonResult
' §11.8.1.1 Applicability
'A member M is considered more applicable than N if their signatures are different and at least one
'parameter type in M is more applicable than a parameter type in N, and no parameter type in N is more
'applicable than a parameter type in M.
Dim equallyApplicable As Boolean = True
Dim leftHasMoreApplicableParameterType As Boolean = False
Dim rightHasMoreApplicableParameterType As Boolean = False
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For i = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(i))
End If
Dim rightParamType As TypeSymbol
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(i))
End If
' Parameters matching omitted arguments do not participate.
If arguments(i).Kind = BoundKind.OmittedArgument Then
Continue For
End If
Dim cmp = CompareParameterTypeApplicability(leftParamType, rightParamType, arguments(i), binder, useSiteInfo)
If cmp = ApplicabilityComparisonResult.LeftIsMoreApplicable Then
leftHasMoreApplicableParameterType = True
If rightHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.Undefined ' Neither is more applicable
End If
equallyApplicable = False
ElseIf cmp = ApplicabilityComparisonResult.RightIsMoreApplicable Then
rightHasMoreApplicableParameterType = True
If leftHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.Undefined ' Neither is more applicable
End If
equallyApplicable = False
ElseIf cmp = ApplicabilityComparisonResult.Undefined Then
equallyApplicable = False
Else
Debug.Assert(cmp = ApplicabilityComparisonResult.EquallyApplicable)
End If
Next
Debug.Assert(Not (leftHasMoreApplicableParameterType AndAlso rightHasMoreApplicableParameterType))
If leftHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If rightHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
Return If(equallyApplicable, ApplicabilityComparisonResult.EquallyApplicable, ApplicabilityComparisonResult.Undefined)
End Function
Private Enum ApplicabilityComparisonResult
Undefined
EquallyApplicable
LeftIsMoreApplicable
RightIsMoreApplicable
End Enum
''' <summary>
''' §11.8.1.1 Applicability
''' </summary>
Private Shared Function CompareParameterTypeApplicability(
left As TypeSymbol,
right As TypeSymbol,
argument As BoundExpression,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As ApplicabilityComparisonResult
Debug.Assert(argument Is Nothing OrElse argument.Kind <> BoundKind.OmittedArgument)
' §11.8.1.1 Applicability
'Given a pair of parameters Mj and Nj that matches an argument Aj,
'the type of Mj is considered more applicable than the type of Nj if one of the following conditions is true:
Dim leftToRightConversion = Conversions.ClassifyConversion(left, right, useSiteInfo)
'1. Mj and Nj have identical types, or
' !!! Does this rule make sense? Not implementing it for now.
If Conversions.IsIdentityConversion(leftToRightConversion.Key) Then
Return ApplicabilityComparisonResult.EquallyApplicable
End If
'2. There exists a widening conversion from the type of Mj to the type Nj, or
If Conversions.IsWideningConversion(leftToRightConversion.Key) Then
' !!! For user defined conversions that widen in both directions there is a tie-breaking rule
' !!! not mentioned in the spec. The type that matches argument's type is more applicable.
' !!! Otherwise neither is more applicable.
If Conversions.IsWideningConversion(Conversions.ClassifyConversion(right, left, useSiteInfo).Key) Then
GoTo BreakTheTie
End If
' !!! Spec makes it look like rule #3 is a separate rule applied after the second, but this isn't the case
' !!! because enumerated type widens to its underlying type, however, if argument is a zero literal,
' !!! underlying type should win.
' !!! Also, based on Dev10 implementation, Mj doesn't have to be a numeric type, it is enough if it is not
' !!! an enumerated type.
'3. Aj is the literal 0, Mj is a numeric type and Nj is an enumerated type, or
If argument IsNot Nothing AndAlso argument.IsIntegerZeroLiteral AndAlso
left.TypeKind = TypeKind.Enum AndAlso right.TypeKind <> TypeKind.Enum Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If Conversions.IsWideningConversion(Conversions.ClassifyConversion(right, left, useSiteInfo).Key) Then
' !!! Spec makes it look like rule #3 is a separate rule applied after the second, but this isn't the case
' !!! because enumerated type widens to its underlying type, however, if argument is a zero literal,
' !!! underlying type should win.
' !!! Also, based on Dev10 implementation, Mj doesn't have to be a numeric type, it is enough if it is not
' !!! an enumerated type.
'3. Aj is the literal 0, Mj is a numeric type and Nj is an enumerated type, or
If argument IsNot Nothing AndAlso argument.IsIntegerZeroLiteral AndAlso
right.TypeKind = TypeKind.Enum AndAlso left.TypeKind <> TypeKind.Enum Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
''3. Aj is the literal 0, Mj is a numeric type and Nj is an enumerated type, or
'If argument IsNot Nothing AndAlso argument.IsIntegerZeroLiteral Then
' If left.IsNumericType() Then
' If right.TypeKind = TypeKind.Enum Then
' leftIsMoreApplicable = True
' Return
' End If
' ElseIf right.IsNumericType() Then
' If left.TypeKind = TypeKind.Enum Then
' rightIsMoreApplicable = True
' Return
' End If
' End If
'End If
'4. Mj is Byte and Nj is SByte, or
'5. Mj is Short and Nj is UShort, or
'6. Mj is Integer and Nj is UInteger, or
'7. Mj is Long and Nj is ULong.
'!!! Plus rules not mentioned in the spec
If left.IsNumericType() AndAlso right.IsNumericType() Then
Dim leftSpecialType = left.SpecialType
Dim rightSpecialType = right.SpecialType
If leftSpecialType = SpecialType.System_Byte AndAlso rightSpecialType = SpecialType.System_SByte Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If leftSpecialType = SpecialType.System_SByte AndAlso rightSpecialType = SpecialType.System_Byte Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
' This comparison depends on the ordering of the SpecialType enum. There is a unit-test that verifies the ordering.
If leftSpecialType < rightSpecialType Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
Else
Debug.Assert(rightSpecialType < leftSpecialType)
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
End If
'8. Mj and Nj are delegate function types and the return type of Mj is more specific than the return type of Nj.
' If Aj is classified as a lambda method, and Mj or Nj is System.Linq.Expressions.Expression(Of T), then the
' type argument of the type (assuming it is a delegate type) is substituted for the type being compared.
If argument IsNot Nothing Then
Dim leftIsExpressionTree As Boolean, rightIsExpressionTree As Boolean
Dim leftDelegateType As NamedTypeSymbol = left.DelegateOrExpressionDelegate(binder, leftIsExpressionTree)
Dim rightDelegateType As NamedTypeSymbol = right.DelegateOrExpressionDelegate(binder, rightIsExpressionTree)
' Native compiler will only compare D1 and D2 for Expression(Of D1) and D2 if the argument is a lambda. It will compare
' Expression(Of D1) and Expression (Of D2) regardless of the argument.
If leftDelegateType IsNot Nothing AndAlso rightDelegateType IsNot Nothing AndAlso
((leftIsExpressionTree = rightIsExpressionTree) OrElse argument.IsAnyLambda()) Then
Dim leftInvoke As MethodSymbol = leftDelegateType.DelegateInvokeMethod
Dim rightInvoke As MethodSymbol = rightDelegateType.DelegateInvokeMethod
If leftInvoke IsNot Nothing AndAlso Not leftInvoke.IsSub AndAlso rightInvoke IsNot Nothing AndAlso Not rightInvoke.IsSub Then
Dim newArgument As BoundExpression = Nothing
' TODO: Should probably handle GroupTypeInferenceLambda too.
If argument.Kind = BoundKind.QueryLambda Then
newArgument = DirectCast(argument, BoundQueryLambda).Expression
End If
Return CompareParameterTypeApplicability(leftInvoke.ReturnType, rightInvoke.ReturnType, newArgument, binder, useSiteInfo)
End If
End If
End If
BreakTheTie:
' !!! There is a tie-breaking rule not mentioned in the spec. The type that matches argument's type is more applicable.
' !!! Otherwise neither is more applicable.
If argument IsNot Nothing Then
Dim argType As TypeSymbol = If(argument.Kind <> BoundKind.ArrayLiteral, argument.Type, DirectCast(argument, BoundArrayLiteral).InferredType)
If argType IsNot Nothing Then
If left.IsSameTypeIgnoringAll(argType) Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If right.IsSameTypeIgnoringAll(argType) Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
End If
End If
' Neither is more applicable
Return ApplicabilityComparisonResult.Undefined
End Function
''' <summary>
''' This method groups equally applicable (§11.8.1.1 Applicability) candidates into buckets.
'''
''' Returns an ArrayBuilder of buckets. Each bucket is represented by an ArrayBuilder(Of Integer),
''' which contains indexes of equally applicable candidates from input parameter 'candidates'.
''' </summary>
Private Shared Function GroupEquallyApplicableCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As ArrayBuilder(Of ArrayBuilder(Of Integer))
Dim buckets = ArrayBuilder(Of ArrayBuilder(Of Integer)).GetInstance()
Dim i As Integer
Dim j As Integer
' §11.8.1.1 Applicability
' A member M is considered equally applicable as N if their signatures are the same or
' if each parameter type in M is the same as the corresponding parameter type in N.
For i = 0 To candidates.Count - 1 Step 1
Dim left As CandidateAnalysisResult = candidates(i)
If left.State <> CandidateAnalysisResultState.Applicable OrElse
left.EquallyApplicableCandidatesBucket > 0 Then
Continue For
End If
left.EquallyApplicableCandidatesBucket = buckets.Count + 1
candidates(i) = left
Dim b = ArrayBuilder(Of Integer).GetInstance()
b.Add(i)
buckets.Add(b)
For j = i + 1 To candidates.Count - 1 Step 1
Dim right As CandidateAnalysisResult = candidates(j)
If right.State <> CandidateAnalysisResultState.Applicable OrElse
right.EquallyApplicableCandidatesBucket > 0 OrElse
right.Candidate Is left.Candidate Then
Continue For
End If
If CandidatesAreEquallyApplicableToArguments(left, right, arguments, binder) Then
right.EquallyApplicableCandidatesBucket = left.EquallyApplicableCandidatesBucket
candidates(j) = right
b.Add(j)
End If
Next
Next
Return buckets
End Function
Private Shared Function CandidatesAreEquallyApplicableToArguments(
ByRef left As CandidateAnalysisResult,
ByRef right As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As Boolean
' §11.8.1.1 Applicability
' A member M is considered equally applicable as N if their signatures are the same or
' if each parameter type in M is the same as the corresponding parameter type in N.
' Compare types of corresponding parameters
Dim k As Integer
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For k = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(k))
End If
Dim rightParamType As TypeSymbol
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(k))
End If
' Parameters matching omitted arguments do not participate.
If arguments(k).Kind <> BoundKind.OmittedArgument AndAlso
Not ParametersAreEquallyApplicableToArgument(leftParamType, rightParamType, arguments(k), binder) Then
' Signatures are different
Exit For
End If
Next
Return k >= arguments.Length
End Function
Private Shared Function ParametersAreEquallyApplicableToArgument(
leftParamType As TypeSymbol,
rightParamType As TypeSymbol,
argument As BoundExpression,
binder As Binder
) As Boolean
Debug.Assert(argument Is Nothing OrElse argument.Kind <> BoundKind.OmittedArgument)
If Not leftParamType.IsSameTypeIgnoringAll(rightParamType) Then
If argument IsNot Nothing Then
Dim leftIsExpressionTree As Boolean, rightIsExpressionTree As Boolean
Dim leftDelegateType As NamedTypeSymbol = leftParamType.DelegateOrExpressionDelegate(binder, leftIsExpressionTree)
Dim rightDelegateType As NamedTypeSymbol = rightParamType.DelegateOrExpressionDelegate(binder, rightIsExpressionTree)
' Native compiler will only compare D1 and D2 for Expression(Of D1) and D2 if the argument is a lambda. It will compare
' Expression(Of D1) and Expression (Of D2) regardless of the argument.
If leftDelegateType IsNot Nothing AndAlso rightDelegateType IsNot Nothing AndAlso
((leftIsExpressionTree = rightIsExpressionTree) OrElse argument.IsAnyLambda()) Then
Dim leftInvoke As MethodSymbol = leftDelegateType.DelegateInvokeMethod
Dim rightInvoke As MethodSymbol = rightDelegateType.DelegateInvokeMethod
If leftInvoke IsNot Nothing AndAlso Not leftInvoke.IsSub AndAlso rightInvoke IsNot Nothing AndAlso Not rightInvoke.IsSub Then
Dim newArgument As BoundExpression = Nothing
' TODO: Should probably handle GroupTypeInferenceLambda too.
If argument.Kind = BoundKind.QueryLambda Then
newArgument = DirectCast(argument, BoundQueryLambda).Expression
End If
Return ParametersAreEquallyApplicableToArgument(leftInvoke.ReturnType, rightInvoke.ReturnType, newArgument, binder)
End If
End If
End If
' Signatures are different
Return False
End If
Return True
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 3. Next, eliminate all members from the set that require narrowing conversions
''' to be applicable to the argument list, except for the case where the argument
''' expression type is Object.
''' 4. Next, eliminate all remaining members from the set that require narrowing coercions
''' to be applicable to the argument list. If the set is empty, the type containing the
''' method group is not an interface, and strict semantics are not being used, the
''' invocation target expression is reclassified as a late-bound method access.
''' Otherwise, the normal rules apply.
'''
''' Returns amount of applicable candidates left.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Shared Function AnalyzeNarrowingCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
lateBindingIsAllowed As Boolean,
binder As Binder,
ByRef resolutionIsLateBound As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Integer
Dim applicableCandidates As Integer = 0
Dim appliedTieBreakingRules As Boolean = False
' Look through the candidate set for lifted operators that require narrowing conversions whose
' source operators also require narrowing conversions. In that case, we only want to keep one method in
' the set. If the source operator requires nullables to be unwrapped, then we discard it and keep the lifted operator.
' If it does not, then we discard the lifted operator and keep the source operator. This will prevent the presence of
' lifted operators from causing overload resolution conflicts where there otherwise wouldn't be one. However,
' if the source operator only requires narrowing conversions from numeric literals, then we keep both in the set,
' because the conversion in that case is not really narrowing.
If candidates(0).Candidate.IsOperator Then
' As an optimization, we can rely on the fact that lifted operator, if added, immediately
' follows source operator.
Dim i As Integer
For i = 0 To candidates.Count - 2 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
Debug.Assert(current.Candidate.IsOperator)
If current.State = CandidateAnalysisResultState.Applicable AndAlso
Not current.Candidate.IsLifted AndAlso
current.RequiresNarrowingNotFromNumericConstant Then
Dim contender As CandidateAnalysisResult = candidates(i + 1)
Debug.Assert(contender.Candidate.IsOperator)
If contender.State = CandidateAnalysisResultState.Applicable AndAlso
contender.Candidate.IsLifted AndAlso
current.Candidate.UnderlyingSymbol Is contender.Candidate.UnderlyingSymbol Then
Exit For
End If
End If
Next
If i < candidates.Count - 1 Then
' [i] is the index of the first "interesting" pair of source/lifted operators.
If Not appliedTieBreakingRules Then
' Apply shadowing rules, Dev10 compiler does that for narrowing candidates too.
applicableCandidates = ApplyTieBreakingRulesToEquallyApplicableCandidates(candidates, arguments, delegateReturnType, binder, useSiteInfo)
appliedTieBreakingRules = True
Debug.Assert(applicableCandidates > 1) ' source and lifted operators are not equally applicable.
End If
' Let's do the elimination pass now.
For i = i To candidates.Count - 2 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
Debug.Assert(current.Candidate.IsOperator)
If current.State = CandidateAnalysisResultState.Applicable AndAlso
Not current.Candidate.IsLifted AndAlso
current.RequiresNarrowingNotFromNumericConstant Then
Dim contender As CandidateAnalysisResult = candidates(i + 1)
Debug.Assert(contender.Candidate.IsOperator)
If contender.State = CandidateAnalysisResultState.Applicable AndAlso
contender.Candidate.IsLifted AndAlso
current.Candidate.UnderlyingSymbol Is contender.Candidate.UnderlyingSymbol Then
For j As Integer = 0 To arguments.Length - 1
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = current.ConversionsOpt(j)
If Conversions.IsNarrowingConversion(conv.Key) Then
Dim lost As Boolean = False
If (conv.Key And ConversionKind.UserDefined) = 0 Then
If IsUnwrappingNullable(conv.Key, arguments(j).Type, current.Candidate.Parameters(j).Type) Then
lost = True
End If
Else
' Lifted user-defined conversions don't unwrap nullables, they are marked with Nullable bit.
If (conv.Key And ConversionKind.Nullable) = 0 Then
If IsUnwrappingNullable(arguments(j).Type, conv.Value.Parameters(0).Type, useSiteInfo) Then
lost = True
ElseIf IsUnwrappingNullable(conv.Value.ReturnType, current.Candidate.Parameters(j).Type, useSiteInfo) Then
lost = True
End If
End If
End If
If lost Then
' unwrapping nullable, current lost
current.State = CandidateAnalysisResultState.Shadowed
candidates(i) = current
i = i + 1
GoTo Next_i
End If
End If
Next
' contender lost
contender.State = CandidateAnalysisResultState.Shadowed
candidates(i + 1) = contender
i = i + 1
GoTo Next_i
End If
End If
Next_i:
Next
End If
End If
If lateBindingIsAllowed Then
' Are there all narrowing from object candidates?
Dim haveAllNarrowingFromObject As Boolean = HaveNarrowingOnlyFromObjectCandidates(candidates)
If haveAllNarrowingFromObject AndAlso Not appliedTieBreakingRules Then
' Apply shadowing rules, Dev10 compiler does that for narrowing candidates too.
applicableCandidates = ApplyTieBreakingRulesToEquallyApplicableCandidates(candidates, arguments, delegateReturnType, binder, useSiteInfo)
appliedTieBreakingRules = True
If applicableCandidates < 2 Then
Return applicableCandidates
End If
haveAllNarrowingFromObject = HaveNarrowingOnlyFromObjectCandidates(candidates)
End If
If haveAllNarrowingFromObject Then
' Get rid of candidates that require narrowing from something other than Object
applicableCandidates = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
If (current.RequiresNarrowingNotFromObject OrElse current.Candidate.IsExtensionMethod) Then
current.State = CandidateAnalysisResultState.ExtensionMethodVsLateBinding
candidates(i) = current
Else
applicableCandidates += 1
End If
End If
Next
Debug.Assert(applicableCandidates > 0)
If applicableCandidates > 1 Then
resolutionIsLateBound = True
End If
Return applicableCandidates
End If
End If
' Although all candidates narrow, there may be a best choice when factoring in narrowing of numeric constants.
' Note that EliminateLessApplicableToTheArguments applies shadowing rules, Dev10 compiler does that for narrowing candidates too.
applicableCandidates = EliminateLessApplicableToTheArguments(candidates, arguments, delegateReturnType, appliedTieBreakingRules, binder,
mostApplicableMustNarrowOnlyFromNumericConstants:=True, useSiteInfo:=useSiteInfo)
' If we ended up with 2 applicable candidates, make sure it is not the same method in
' ParamArray expanded and non-expanded form. The non-expanded form should win in this case.
If applicableCandidates = 2 Then
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim first As CandidateAnalysisResult = candidates(i)
If first.State = CandidateAnalysisResultState.Applicable Then
For j As Integer = i + 1 To candidates.Count - 1 Step 1
Dim second As CandidateAnalysisResult = candidates(j)
If second.State = CandidateAnalysisResultState.Applicable Then
If first.Candidate.UnderlyingSymbol.Equals(second.Candidate.UnderlyingSymbol) Then
Dim firstWins As Boolean = False
Dim secondWins As Boolean = False
If ShadowBasedOnParamArrayUsage(first, second, firstWins, secondWins) Then
If firstWins Then
second.State = CandidateAnalysisResultState.Shadowed
candidates(j) = second
applicableCandidates = 1
ElseIf secondWins Then
first.State = CandidateAnalysisResultState.Shadowed
candidates(i) = first
applicableCandidates = 1
End If
Debug.Assert(applicableCandidates = 1)
End If
End If
GoTo Done
End If
Next
Debug.Assert(False, "Should not reach this line.")
End If
Next
End If
Done:
Return applicableCandidates
End Function
Private Shared Function IsUnwrappingNullable(
conv As ConversionKind,
sourceType As TypeSymbol,
targetType As TypeSymbol
) As Boolean
Debug.Assert((conv And ConversionKind.UserDefined) = 0)
Return (conv And ConversionKind.Nullable) <> 0 AndAlso
sourceType IsNot Nothing AndAlso
sourceType.IsNullableType() AndAlso
Not targetType.IsNullableType()
End Function
Private Shared Function IsUnwrappingNullable(
sourceType As TypeSymbol,
targetType As TypeSymbol,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
Return sourceType IsNot Nothing AndAlso
IsUnwrappingNullable(Conversions.ClassifyPredefinedConversion(sourceType, targetType, useSiteInfo), sourceType, targetType)
End Function
Private Shared Function HaveNarrowingOnlyFromObjectCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult)
) As Boolean
Dim haveAllNarrowingFromObject As Boolean = False
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable AndAlso
Not current.RequiresNarrowingNotFromObject AndAlso
Not current.Candidate.IsExtensionMethod Then
haveAllNarrowingFromObject = True
Exit For
End If
Next
Return haveAllNarrowingFromObject
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 2. Next, eliminate all members from the set that are inaccessible or not applicable to the argument list.
'''
''' Note, similar to Dev10 compiler this process will eliminate candidates requiring narrowing conversions
''' if strict semantics is used, exception are candidates that require narrowing only from numeric constants.
'''
''' Returns amount of applicable candidates left.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Shared Function EliminateNotApplicableToArguments(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
<Out()> ByRef applicableNarrowingCandidates As Integer,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
callerInfoOpt As SyntaxNode,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Integer
Dim applicableCandidates As Integer = 0
Dim illegalInAttribute As Integer = 0
applicableNarrowingCandidates = 0
' Filter out inapplicable candidates
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
If Not current.ArgumentMatchingDone Then
MatchArguments(methodOrPropertyGroup, current, arguments, argumentNames, binder, asyncLambdaSubToFunctionMismatch, callerInfoOpt, forceExpandedForm, useSiteInfo)
current.SetArgumentMatchingDone()
candidates(i) = current
End If
If current.State = CandidateAnalysisResultState.Applicable Then
applicableCandidates += 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates += 1
End If
If current.IsIllegalInAttribute Then
illegalInAttribute += 1
End If
End If
Next
' Filter out candidates with IsIllegalInAttribute if there are other applicable candidates
If illegalInAttribute > 0 AndAlso applicableCandidates > illegalInAttribute Then
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable AndAlso current.IsIllegalInAttribute Then
applicableCandidates -= 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates -= 1
End If
current.State = CandidateAnalysisResultState.ArgumentMismatch
candidates(i) = current
End If
Next
Debug.Assert(applicableCandidates > 0)
End If
Return applicableCandidates
End Function
''' <summary>
''' Figure out corresponding arguments for parameters §11.8.2 Applicable Methods.
'''
''' Note, this function mutates the candidate structure.
'''
''' If non-Nothing ArrayBuilders are returned through parameterToArgumentMap and paramArrayItems
''' parameters, the caller is responsible fo returning them into the pool.
'''
''' Assumptions:
''' 1) This function is never called for a candidate that should be rejected due to parameter count.
''' 2) Omitted arguments [ Call Goo(a, , b) ] are represented by OmittedArgumentExpression node in the arguments array.
''' 3) Omitted argument never has name.
''' 4) argumentNames contains Nothing for all positional arguments.
'''
''' !!! Should keep this function in sync with Binder.PassArguments, which uses data this function populates. !!!
''' !!! Should keep this function in sync with Binder.ReportOverloadResolutionFailureForASingleCandidate. !!!
''' !!! Everything we flag as an error here, Binder.ReportOverloadResolutionFailureForASingleCandidate should detect as well. !!!
''' </summary>
Private Shared Sub BuildParameterToArgumentMap(
ByRef candidate As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
ByRef parameterToArgumentMap As ArrayBuilder(Of Integer),
ByRef paramArrayItems As ArrayBuilder(Of Integer)
)
Debug.Assert(Not arguments.IsDefault)
Debug.Assert(argumentNames.IsDefault OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length))
Debug.Assert(Not candidate.ArgumentMatchingDone)
Debug.Assert(candidate.State = CandidateAnalysisResultState.Applicable)
parameterToArgumentMap = ArrayBuilder(Of Integer).GetInstance(candidate.Candidate.ParameterCount, -1)
Dim argsToParams As ArrayBuilder(Of Integer) = Nothing
If Not argumentNames.IsDefault Then
argsToParams = ArrayBuilder(Of Integer).GetInstance(arguments.Length, -1)
End If
paramArrayItems = Nothing
If candidate.IsExpandedParamArrayForm Then
paramArrayItems = ArrayBuilder(Of Integer).GetInstance()
End If
'§11.8.2 Applicable Methods
'1. First, match each positional argument in order to the list of method parameters.
'If there are more positional arguments than parameters and the last parameter is not a paramarray, the method is not applicable.
'Otherwise, the paramarray parameter is expanded with parameters of the paramarray element type to match the number of positional arguments.
'If a positional argument is omitted, the method is not applicable.
' !!! Not sure about the last sentence: "If a positional argument is omitted, the method is not applicable."
' !!! Dev10 allows omitting positional argument as long as the corresponding parameter is optional.
Dim positionalArguments As Integer = 0
Dim paramIndex = 0
For i As Integer = 0 To arguments.Length - 1 Step 1
If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then
' A named argument
If Not candidate.Candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then
' ERRID_NamedParamNotFound1
' ERRID_NamedParamNotFound2
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
End If
If paramIndex <> i Then
' all remaining arguments must be named
Exit For
End If
If paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
candidate.Candidate.Parameters(paramIndex).IsParamArray Then
' ERRID_NamedParamArrayArgument
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
End If
Debug.Assert(parameterToArgumentMap(paramIndex) = -1)
End If
positionalArguments += 1
If argsToParams IsNot Nothing Then
argsToParams(i) = paramIndex
End If
If arguments(i).Kind = BoundKind.OmittedArgument Then
If paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
candidate.Candidate.Parameters(paramIndex).IsParamArray Then
' Omitted ParamArray argument at the call site
' ERRID_OmittedParamArrayArgument
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
Else
parameterToArgumentMap(paramIndex) = i
paramIndex += 1
End If
ElseIf (candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1) Then
paramArrayItems.Add(i)
Else
parameterToArgumentMap(paramIndex) = i
paramIndex += 1
End If
Next
'§11.8.2 Applicable Methods
'2. Next, match each named argument to a parameter with the given name.
'If one of the named arguments fails to match, matches a paramarray parameter,
'or matches an argument already matched with another positional or named argument,
'the method is not applicable.
For i As Integer = positionalArguments To arguments.Length - 1 Step 1
Debug.Assert(argumentNames(i) Is Nothing OrElse argumentNames(i).Length > 0)
If argumentNames(i) Is Nothing Then
' Unnamed argument follows named arguments, parser should have detected an error.
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
If Not candidate.Candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then
' ERRID_NamedParamNotFound1
' ERRID_NamedParamNotFound2
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
If argsToParams IsNot Nothing Then
argsToParams(i) = paramIndex
End If
If paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
candidate.Candidate.Parameters(paramIndex).IsParamArray Then
' ERRID_NamedParamArrayArgument
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
If parameterToArgumentMap(paramIndex) <> -1 Then
' ERRID_NamedArgUsedTwice1
' ERRID_NamedArgUsedTwice2
' ERRID_NamedArgUsedTwice3
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
' It is an error for a named argument to specify
' a value for an explicitly omitted positional argument.
If paramIndex < positionalArguments Then
'ERRID_NamedArgAlsoOmitted1
'ERRID_NamedArgAlsoOmitted2
'ERRID_NamedArgAlsoOmitted3
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
parameterToArgumentMap(paramIndex) = i
Next
If argsToParams IsNot Nothing Then
candidate.ArgsToParamsOpt = argsToParams.ToImmutableAndFree()
argsToParams = Nothing
End If
Bailout:
If argsToParams IsNot Nothing Then
argsToParams.Free()
argsToParams = Nothing
End If
End Sub
''' <summary>
''' Match candidate's parameters to arguments §11.8.2 Applicable Methods.
'''
''' Note, similar to Dev10 compiler this process will eliminate candidate requiring narrowing conversions
''' if strict semantics is used, exception are candidates that require narrowing only from numeric constants.
'''
''' Assumptions:
''' 1) This function is never called for a candidate that should be rejected due to parameter count.
''' 2) Omitted arguments [ Call Goo(a, , b) ] are represented by OmittedArgumentExpression node in the arguments array.
''' 3) Omitted argument never has name.
''' 4) argumentNames contains Nothing for all positional arguments.
'''
''' !!! Should keep this function in sync with Binder.PassArguments, which uses data this function populates. !!!
''' !!! Should keep this function in sync with Binder.ReportOverloadResolutionFailureForASingleCandidate. !!!
''' !!! Should keep this function in sync with InferenceGraph.PopulateGraph. !!!
''' !!! Everything we flag as an error here, Binder.ReportOverloadResolutionFailureForASingleCandidate should detect as well. !!!
''' </summary>
Private Shared Sub MatchArguments(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
ByRef candidate As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
callerInfoOpt As SyntaxNode,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(Not arguments.IsDefault)
Debug.Assert(argumentNames.IsDefault OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length))
Debug.Assert(Not candidate.ArgumentMatchingDone)
Debug.Assert(candidate.State = CandidateAnalysisResultState.Applicable)
Debug.Assert(Not candidate.Candidate.UnderlyingSymbol.IsReducedExtensionMethod() OrElse methodOrPropertyGroup.ReceiverOpt IsNot Nothing OrElse TypeOf methodOrPropertyGroup.SyntaxTree Is DummySyntaxTree)
Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Nothing
Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing
Dim conversionKinds As KeyValuePair(Of ConversionKind, MethodSymbol)() = Nothing
Dim conversionBackKinds As KeyValuePair(Of ConversionKind, MethodSymbol)() = Nothing
Dim optionalArguments As OptionalArgument() = Nothing
Dim defaultValueDiagnostics As BindingDiagnosticBag = Nothing
BuildParameterToArgumentMap(candidate, arguments, argumentNames, parameterToArgumentMap, paramArrayItems)
If candidate.State <> CandidateAnalysisResultState.Applicable Then
Debug.Assert(Not candidate.IgnoreExtensionMethods)
GoTo Bailout
End If
' At this point we will set IgnoreExtensionMethods to true and will
' clear it when appropriate because not every failure should allow
' us to consider extension methods.
If Not candidate.Candidate.IsExtensionMethod Then
candidate.IgnoreExtensionMethods = True
End If
'§11.8.2 Applicable Methods
'The type arguments, if any, must satisfy the constraints, if any, on the matching type parameters.
Dim candidateSymbol = candidate.Candidate.UnderlyingSymbol
If candidateSymbol.Kind = SymbolKind.Method Then
Dim method = DirectCast(candidateSymbol, MethodSymbol)
If method.IsGenericMethod Then
Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()
Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing
Dim satisfiedConstraints = method.CheckConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder, template:=useSiteInfo)
diagnosticsBuilder.Free()
If useSiteDiagnosticsBuilder IsNot Nothing AndAlso useSiteDiagnosticsBuilder.Count > 0 Then
For Each diag In useSiteDiagnosticsBuilder
useSiteInfo.Add(diag.UseSiteInfo)
Next
End If
If Not satisfiedConstraints Then
' Do not clear IgnoreExtensionMethods flag if constraints are violated.
candidate.State = CandidateAnalysisResultState.GenericConstraintsViolated
GoTo Bailout
End If
End If
End If
' Traverse the parameters, converting corresponding arguments
' as appropriate.
Dim argIndex As Integer
Dim candidateIsAProperty As Boolean = (candidate.Candidate.UnderlyingSymbol.Kind = SymbolKind.Property)
For paramIndex = 0 To candidate.Candidate.ParameterCount - 1 Step 1
If candidate.State <> CandidateAnalysisResultState.Applicable AndAlso
Not candidate.IgnoreExtensionMethods Then
' There is no reason to continue. We will not learn anything new.
GoTo Bailout
End If
Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex)
Dim isByRef As Boolean = param.IsByRef
Dim targetType As TypeSymbol = param.Type
If param.IsParamArray AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 Then
If targetType.Kind <> SymbolKind.ArrayType Then
' ERRID_ParamArrayWrongType
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
If Not candidate.IsExpandedParamArrayForm Then
argIndex = parameterToArgumentMap(paramIndex)
Dim paramArrayArgument = If(argIndex = -1, Nothing, arguments(argIndex))
Debug.Assert(paramArrayArgument Is Nothing OrElse paramArrayArgument.Kind <> BoundKind.OmittedArgument)
'§11.8.2 Applicable Methods
'If the conversion from the type of the argument expression to the paramarray type is narrowing,
'then the method is only applicable in its expanded form.
'!!! However, there is an exception to that rule - narrowing conversion from semantical Nothing literal is Ok. !!!
Dim arrayConversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
If Not (paramArrayArgument IsNot Nothing AndAlso
Not paramArrayArgument.HasErrors AndAlso CanPassToParamArray(paramArrayArgument, targetType, arrayConversion, binder, useSiteInfo)) Then
' It doesn't look like native compiler reports any errors in this case.
' Probably due to assumption that either errors were already reported for bad argument expression or
' we will report errors for expanded version of the same candidate.
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
ElseIf Conversions.IsNarrowingConversion(arrayConversion.Key) Then
' We can get here only for Object with constant value == Nothing.
Debug.Assert(paramArrayArgument.IsNothingLiteral())
' Unlike for other arguments, Dev10 doesn't make a note of this narrowing.
' However, should this narrowing cause a conversion error, the error must be noted.
If binder.OptionStrict = OptionStrict.On Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, this doesn't clear IgnoreExtensionMethods flag.
Continue For
End If
Else
Debug.Assert(Conversions.IsWideningConversion(arrayConversion.Key))
End If
' Since CanPassToParamArray succeeded, there is no need to check conversions for this argument again
If Not Conversions.IsIdentityConversion(arrayConversion.Key) Then
If conversionKinds Is Nothing Then
conversionKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionKinds.Length - 1
conversionKinds(i) = Conversions.Identity
Next
End If
conversionKinds(argIndex) = arrayConversion
End If
Else
Debug.Assert(candidate.IsExpandedParamArrayForm)
'§11.8.2 Applicable Methods
' If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form.
' Note, that explicitly converted NOTHING is treated the same way by Dev10.
' But, for the purpose of interpolated string lowering the method is applicable even if the argument expression
' is the literal Nothing. This is because for interpolated string lowering we want to always call methods
' in their expanded form. E.g. $"{Nothing}" should be lowered to String.Format("{0}", New Object() {Nothing}) not
' String.Format("{0}", CType(Nothing, Object())).
If paramArrayItems.Count = 1 AndAlso arguments(paramArrayItems(0)).IsNothingLiteral() AndAlso Not forceExpandedForm Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
' Otherwise, for a ParamArray parameter, all the matching arguments are passed
' ByVal as instances of the element type of the ParamArray.
' Perform the conversions to the element type of the ParamArray here.
Dim arrayType = DirectCast(targetType, ArrayTypeSymbol)
If Not arrayType.IsSZArray Then
' ERRID_ParamArrayWrongType
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
targetType = arrayType.ElementType
If targetType.Kind = SymbolKind.ErrorType Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, IgnoreExtensionMethods is not cleared.
Continue For
End If
For j As Integer = 0 To paramArrayItems.Count - 1 Step 1
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
If arguments(paramArrayItems(j)).HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011]
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
If Not MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, arguments(paramArrayItems(j)), targetType, binder, conv, asyncLambdaSubToFunctionMismatch, useSiteInfo) Then
' Note, IgnoreExtensionMethods is not cleared here, MatchArgumentToByValParameter makes required changes.
Continue For
End If
' typically all conversions in otherwise acceptable candidate are identity conversions
If Not Conversions.IsIdentityConversion(conv.Key) Then
If conversionKinds Is Nothing Then
conversionKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionKinds.Length - 1
conversionKinds(i) = Conversions.Identity
Next
End If
conversionKinds(paramArrayItems(j)) = conv
End If
Next
End If
Continue For
End If
argIndex = parameterToArgumentMap(paramIndex)
Dim argument = If(argIndex = -1, Nothing, arguments(argIndex))
Dim defaultArgument As BoundExpression = Nothing
If argument Is Nothing OrElse argument.Kind = BoundKind.OmittedArgument Then
' Deal with Optional arguments.
If defaultValueDiagnostics Is Nothing Then
defaultValueDiagnostics = BindingDiagnosticBag.GetInstance()
Else
defaultValueDiagnostics.Clear()
End If
Dim receiverOpt As BoundExpression = Nothing
If candidateSymbol.IsReducedExtensionMethod() Then
receiverOpt = methodOrPropertyGroup.ReceiverOpt
End If
defaultArgument = binder.GetArgumentForParameterDefaultValue(param, If(argument, methodOrPropertyGroup).Syntax, defaultValueDiagnostics, callerInfoOpt, parameterToArgumentMap, arguments, receiverOpt)
If defaultArgument IsNot Nothing AndAlso Not defaultValueDiagnostics.HasAnyErrors Then
Debug.Assert(Not defaultValueDiagnostics.DiagnosticBag.AsEnumerable().Any())
' Mark these as compiler generated so they are ignored by later phases. For example,
' these bound nodes will mess up the incremental binder cache, because they use the
' the same syntax node as the method identifier from the invocation / AddressOf if they
' are not marked.
defaultArgument.SetWasCompilerGenerated()
argument = defaultArgument
Else
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
'Note, IgnoreExtensionMethods flag should not be cleared due to a badness of default value.
candidate.IgnoreExtensionMethods = False
GoTo Bailout
End If
End If
If targetType.Kind = SymbolKind.ErrorType Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, IgnoreExtensionMethods is not cleared.
Continue For
End If
If argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011]
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
End If
Dim conversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
Dim conversionBack As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
Debug.Assert(Not isByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType())
' Arguments for properties are always passed with ByVal semantics. Even if
' parameter in metadata is defined ByRef, we always pass corresponding argument
' through a temp without copy-back.
' Non-string arguments for implicitly ByRef string parameters of Declare functions
' are passed through a temp without copy-back.
If isByRef AndAlso Not candidateIsAProperty AndAlso defaultArgument Is Nothing AndAlso
(param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then
MatchArgumentToByRefParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, conversion, conversionBack, asyncLambdaSubToFunctionMismatch, useSiteInfo)
Else
conversionBack = Conversions.Identity
MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, conversion, asyncLambdaSubToFunctionMismatch, useSiteInfo, defaultArgument IsNot Nothing)
End If
' typically all conversions in otherwise acceptable candidate are identity conversions
If Not Conversions.IsIdentityConversion(conversion.Key) Then
If conversionKinds Is Nothing Then
conversionKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionKinds.Length - 1
conversionKinds(i) = Conversions.Identity
Next
End If
' If this is not a default argument then store the conversion in the conversionKinds.
' For default arguments the conversion is stored below.
If defaultArgument Is Nothing Then
conversionKinds(argIndex) = conversion
End If
End If
' If this is a default argument then add it to the candidate result default arguments.
' Note these arguments are stored by parameter index. Default arguments are missing so they
' may not have an argument index.
If defaultArgument IsNot Nothing Then
If optionalArguments Is Nothing Then
optionalArguments = New OptionalArgument(candidate.Candidate.ParameterCount - 1) {}
End If
optionalArguments(paramIndex) = New OptionalArgument(defaultArgument, conversion, defaultValueDiagnostics.DependenciesBag.ToImmutableArray())
End If
If Not Conversions.IsIdentityConversion(conversionBack.Key) Then
If conversionBackKinds Is Nothing Then
' There should never be a copy back conversion with a default argument.
Debug.Assert(defaultArgument Is Nothing)
conversionBackKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionBackKinds.Length - 1
conversionBackKinds(i) = Conversions.Identity
Next
End If
conversionBackKinds(argIndex) = conversionBack
End If
Next
Bailout:
If defaultValueDiagnostics IsNot Nothing Then
defaultValueDiagnostics.Free()
End If
If paramArrayItems IsNot Nothing Then
paramArrayItems.Free()
End If
If conversionKinds IsNot Nothing Then
candidate.ConversionsOpt = conversionKinds.AsImmutableOrNull()
End If
If conversionBackKinds IsNot Nothing Then
candidate.ConversionsBackOpt = conversionBackKinds.AsImmutableOrNull()
End If
If optionalArguments IsNot Nothing Then
candidate.OptionalArguments = optionalArguments.AsImmutableOrNull()
End If
If parameterToArgumentMap IsNot Nothing Then
parameterToArgumentMap.Free()
End If
End Sub
''' <summary>
''' Should be in sync with Binder.ReportByRefConversionErrors.
''' </summary>
Private Shared Sub MatchArgumentToByRefParameter(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
ByRef candidate As CandidateAnalysisResult,
argument As BoundExpression,
targetType As TypeSymbol,
binder As Binder,
<Out()> ByRef outConversionKind As KeyValuePair(Of ConversionKind, MethodSymbol),
<Out()> ByRef outConversionBackKind As KeyValuePair(Of ConversionKind, MethodSymbol),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
If argument.IsSupportingAssignment() Then
If argument.IsLValue() AndAlso targetType.IsSameTypeIgnoringAll(argument.Type) Then
outConversionKind = Conversions.Identity
outConversionBackKind = Conversions.Identity
Else
outConversionBackKind = Conversions.Identity
If MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, outConversionKind, asyncLambdaSubToFunctionMismatch, useSiteInfo) Then
' Check copy back conversion
Dim copyBackType = argument.GetTypeOfAssignmentTarget()
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(targetType, copyBackType, useSiteInfo)
outConversionBackKind = conv
If Conversions.NoConversion(conv.Key) Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch ' Possible only with user-defined conversions, I think.
candidate.IgnoreExtensionMethods = False
Else
If Conversions.IsNarrowingConversion(conv.Key) Then
' Similar to Dev10 compiler, we will eliminate candidate requiring narrowing conversions
' if strict semantics is used, exception are candidates that require narrowing only from
' numeric(Constants.
candidate.SetRequiresNarrowingConversion()
Debug.Assert((conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0)
candidate.SetRequiresNarrowingNotFromNumericConstant()
If binder.OptionStrict = OptionStrict.On Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
Return
End If
If targetType.SpecialType <> SpecialType.System_Object Then
candidate.SetRequiresNarrowingNotFromObject()
End If
End If
candidate.RegisterDelegateRelaxationLevel(conv.Key)
End If
End If
End If
Else
' No copy back needed
' If we are inside a lambda in a constructor and are passing ByRef a non-LValue field, which
' would be an LValue field, if it were referred to in the constructor outside of a lambda,
' we need to report an error because the operation will result in a simulated pass by
' ref (through a temp, without a copy back), which might be not the intent.
If binder.Report_ERRID_ReadOnlyInClosure(argument) Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, we do not change IgnoreExtensionMethods flag here.
End If
outConversionBackKind = Conversions.Identity
MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, outConversionKind, asyncLambdaSubToFunctionMismatch, useSiteInfo)
End If
End Sub
''' <summary>
''' Should be in sync with Binder.ReportByValConversionErrors.
''' </summary>
Private Shared Function MatchArgumentToByValParameter(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
ByRef candidate As CandidateAnalysisResult,
argument As BoundExpression,
targetType As TypeSymbol,
binder As Binder,
<Out()> ByRef outConversionKind As KeyValuePair(Of ConversionKind, MethodSymbol),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional isDefaultValueArgument As Boolean = False
) As Boolean
outConversionKind = Nothing 'VBConversions.NoConversion
' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics,
' arrays, etc., detect types from unreferenced assemblies, ... ?
If targetType.IsErrorType() Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, IgnoreExtensionMethods is not cleared.
Return False
End If
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, binder, useSiteInfo)
outConversionKind = conv
If Conversions.NoConversion(conv.Key) Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
If (conv.Key And (ConversionKind.DelegateRelaxationLevelMask Or ConversionKind.Lambda)) = (ConversionKind.DelegateRelaxationLevelInvalid Or ConversionKind.Lambda) Then
' Dig through parenthesized
Dim underlying As BoundExpression = argument
While underlying.Kind = BoundKind.Parenthesized AndAlso underlying.Type Is Nothing
underlying = DirectCast(underlying, BoundParenthesized).Expression
End While
Dim unbound = If(underlying.Kind = BoundKind.UnboundLambda, DirectCast(underlying, UnboundLambda), Nothing)
If unbound IsNot Nothing AndAlso Not unbound.IsFunctionLambda AndAlso
(unbound.Flags And SourceMemberFlags.Async) <> 0 AndAlso
targetType.IsDelegateType Then
Dim delegateInvoke As MethodSymbol = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod
Debug.Assert(delegateInvoke IsNot Nothing)
If delegateInvoke IsNot Nothing Then
Dim bound As BoundLambda = unbound.GetBoundLambda(New UnboundLambda.TargetSignature(delegateInvoke))
Debug.Assert(bound IsNot Nothing)
If bound IsNot Nothing AndAlso (bound.MethodConversionKind And MethodConversionKind.AllErrorReasons) = MethodConversionKind.Error_SubToFunction AndAlso
(Not bound.Diagnostics.Diagnostics.HasAnyErrors) Then
If asyncLambdaSubToFunctionMismatch Is Nothing Then
asyncLambdaSubToFunctionMismatch = New HashSet(Of BoundExpression)(ReferenceEqualityComparer.Instance)
End If
asyncLambdaSubToFunctionMismatch.Add(unbound)
End If
End If
End If
End If
Return False
End If
' Characteristics of conversion applied to a default value for an optional parameter shouldn't be used to disambiguate
' between two candidates.
If Conversions.IsNarrowingConversion(conv.Key) Then
' Similar to Dev10 compiler, we will eliminate candidate requiring narrowing conversions
' if strict semantics is used, exception are candidates that require narrowing only from
' numeric constants.
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingConversion()
End If
If (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingNotFromNumericConstant()
End If
If binder.OptionStrict = OptionStrict.On Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
Return False
End If
End If
Dim argumentType = argument.Type
If argumentType Is Nothing OrElse
argumentType.SpecialType <> SpecialType.System_Object Then
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingNotFromObject()
End If
End If
ElseIf (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0 Then
' Dev10 overload resolution treats conversions that involve narrowing from numeric constant type
' as narrowing.
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingConversion()
candidate.SetRequiresNarrowingNotFromObject()
End If
End If
If Not isDefaultValueArgument Then
candidate.RegisterDelegateRelaxationLevel(conv.Key)
End If
' If we are in attribute context, keep track of candidates that will result in illegal arguments.
' They should be dismissed in favor of other applicable candidates.
If binder.BindingLocation = BindingLocation.Attribute AndAlso
Not candidate.IsIllegalInAttribute AndAlso
Not methodOrPropertyGroup.WasCompilerGenerated AndAlso
methodOrPropertyGroup.Kind = BoundKind.MethodGroup AndAlso
IsWithinAppliedAttributeName(methodOrPropertyGroup.Syntax) AndAlso
DirectCast(candidate.Candidate.UnderlyingSymbol, MethodSymbol).MethodKind = MethodKind.Constructor AndAlso
binder.Compilation.GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(candidate.Candidate.UnderlyingSymbol.ContainingType, useSiteInfo) Then
Debug.Assert(Not argument.HasErrors)
Dim passedExpression As BoundExpression = binder.PassArgumentByVal(argument, conv, targetType, BindingDiagnosticBag.Discarded)
If Not passedExpression.IsConstant Then ' Trying to match native compiler behavior in Semantics::IsValidAttributeConstant
Dim visitor As New Binder.AttributeExpressionVisitor(binder, passedExpression.HasErrors)
visitor.VisitExpression(passedExpression, BindingDiagnosticBag.Discarded)
If visitor.HasErrors Then
candidate.SetIllegalInAttribute()
End If
End If
End If
Return True
End Function
Private Shared Function IsWithinAppliedAttributeName(syntax As SyntaxNode) As Boolean
Dim parent As SyntaxNode = syntax.Parent
While parent IsNot Nothing
If parent.Kind = SyntaxKind.Attribute Then
Return DirectCast(parent, AttributeSyntax).Name.Span.Contains(syntax.Position)
ElseIf TypeOf parent Is ExpressionSyntax OrElse TypeOf parent Is StatementSyntax Then
Exit While
End If
parent = parent.Parent
End While
Return False
End Function
Public Shared Function CanPassToParamArray(
expression As BoundExpression,
targetType As TypeSymbol,
<Out()> ByRef outConvKind As KeyValuePair(Of ConversionKind, MethodSymbol),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
'§11.8.2 Applicable Methods
'If the conversion from the type of the argument expression to the paramarray type is narrowing,
'then the method is only applicable in its expanded form.
outConvKind = Conversions.ClassifyConversion(expression, targetType, binder, useSiteInfo)
' Note, user-defined conversions are acceptable here.
If Conversions.IsWideningConversion(outConvKind.Key) Then
Return True
End If
' Dev10 allows explicitly converted NOTHING as an argument for a ParamArray parameter,
' even if conversion to the array type is narrowing.
If IsNothingLiteral(expression) Then
Debug.Assert(Conversions.IsNarrowingConversion(outConvKind.Key))
Return True
End If
Return False
End Function
''' <summary>
''' Performs an initial pass through the group of candidates and does
''' the following in the process.
''' 1) Eliminates candidates based on the number of supplied arguments and number of supplied generic type arguments.
''' 2) Adds additional entries for expanded ParamArray forms when applicable.
''' 3) Infers method's generic type arguments if needed.
''' 4) Substitutes method's generic type arguments.
''' 5) Eliminates candidates based on shadowing by signature.
''' This partially takes care of §11.8.1 Overloaded Method Resolution, section 7.1.
''' If M is defined in a more derived type than N, eliminate N from the set.
''' 6) Eliminates candidates with identical virtual signatures by applying various shadowing and
''' tie-breaking rules from §11.8.1 Overloaded Method Resolution, section 7.0
''' • If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
''' 7) Takes care of unsupported overloading within the same type for instance methods/properties.
'''
''' Assumptions:
''' 1) Shadowing by name has been already applied.
''' 2) group can include extension methods.
''' 3) group contains original definitions, i.e. method type arguments have not been substituted yet.
''' Exception are extension methods with type parameters substituted based on receiver type rather
''' than based on type arguments supplied at the call site.
''' 4) group contains only accessible candidates.
''' 5) group doesn't contain members involved into unsupported overloading, i.e. differ by casing or custom modifiers only.
''' 6) group does not contain duplicates.
''' 7) All elements of arguments array are Not Nothing, omitted arguments are represented by OmittedArgumentExpression node.
''' </summary>
''' <remarks>
''' This method is destructive to content of the [group] parameter.
''' </remarks>
Private Shared Sub CollectOverloadedCandidates(
binder As Binder,
results As ArrayBuilder(Of CandidateAnalysisResult),
group As ArrayBuilder(Of Candidate),
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
includeEliminatedCandidates As Boolean,
isQueryOperatorInvocation As Boolean,
forceExpandedForm As Boolean,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(results IsNot Nothing)
Debug.Assert(argumentNames.IsDefault OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length))
Dim quickInfo = ArrayBuilder(Of QuickApplicabilityInfo).GetInstance()
Dim sourceModule As ModuleSymbol = binder.SourceModule
For i As Integer = 0 To group.Count - 1
If group(i) Is Nothing Then
Continue For
End If
Dim info As QuickApplicabilityInfo = DoQuickApplicabilityCheck(group(i), typeArguments, arguments, isQueryOperatorInvocation, forceExpandedForm, useSiteInfo)
If info.Candidate Is Nothing Then
Continue For
End If
If info.Candidate.UnderlyingSymbol.ContainingModule Is sourceModule OrElse
info.Candidate.IsExtensionMethod Then
CollectOverloadedCandidate(results, info, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
Continue For
End If
' Deal with VB-illegal overloading in imported types.
' We are trying to avoid doing signature comparison as much as possible and limit them to
' cases when at least one candidate is applicable based on the quick applicability check.
' Similar code exists in overriding checks in OverrideHidingHelper.RemoveMembersWithConflictingAccessibility.
Dim container As Symbol = info.Candidate.UnderlyingSymbol.ContainingSymbol
' If there are more candidates from this type, collect all of them in quickInfo array,
' but keep the applicable candidates at the beginning
quickInfo.Clear()
quickInfo.Add(info)
Dim applicableCount As Integer = If(info.State = CandidateAnalysisResultState.Applicable, 1, 0)
For j As Integer = i + 1 To group.Count - 1
If group(j) Is Nothing OrElse
group(j).IsExtensionMethod Then ' VS2013 ignores illegal overloading for extension methods
Continue For
End If
If container = group(j).UnderlyingSymbol.ContainingSymbol Then
info = DoQuickApplicabilityCheck(group(j), typeArguments, arguments, isQueryOperatorInvocation, forceExpandedForm, useSiteInfo)
group(j) = Nothing
If info.Candidate Is Nothing Then
Continue For
End If
' Keep applicable candidates at the beginning.
If info.State <> CandidateAnalysisResultState.Applicable Then
quickInfo.Add(info)
ElseIf applicableCount = quickInfo.Count Then
quickInfo.Add(info)
applicableCount += 1
Else
quickInfo.Add(quickInfo(applicableCount))
quickInfo(applicableCount) = info
applicableCount += 1
End If
End If
Next
' Now see if any candidates are ambiguous or lose against other candidates in the quickInfo array.
' This loop is destructive to the content of the quickInfo, some applicable candidates could be replaced with
' a "better" candidate, even though that candidate is not applicable, "losers" are deleted, etc.
For k As Integer = 0 To If(applicableCount > 0 OrElse Not includeEliminatedCandidates, applicableCount, quickInfo.Count) - 1
info = quickInfo(k)
If info.Candidate Is Nothing OrElse info.State = CandidateAnalysisResultState.Ambiguous Then
Continue For
End If
#If DEBUG Then
Dim isExtensionMethod As Boolean = info.Candidate.IsExtensionMethod
#End If
Dim firstSymbol As Symbol = info.Candidate.UnderlyingSymbol.OriginalDefinition
If firstSymbol.IsReducedExtensionMethod() Then
firstSymbol = DirectCast(firstSymbol, MethodSymbol).ReducedFrom
End If
For l As Integer = k + 1 To quickInfo.Count - 1
Dim info2 As QuickApplicabilityInfo = quickInfo(l)
If info2.Candidate Is Nothing OrElse info2.State = CandidateAnalysisResultState.Ambiguous Then
Continue For
End If
#If DEBUG Then
Debug.Assert(isExtensionMethod = info2.Candidate.IsExtensionMethod)
#End If
Dim secondSymbol As Symbol = info2.Candidate.UnderlyingSymbol.OriginalDefinition
If secondSymbol.IsReducedExtensionMethod() Then
secondSymbol = DirectCast(secondSymbol, MethodSymbol).ReducedFrom
End If
' The following check should be similar to the one performed by SourceNamedTypeSymbol.CheckForOverloadsErrors
' However, we explicitly ignore custom modifiers here, since this part is NYI for SourceNamedTypeSymbol.
Const significantDifferences As SymbolComparisonResults = SymbolComparisonResults.AllMismatches And
Not SymbolComparisonResults.MismatchesForConflictingMethods
Dim comparisonResults As SymbolComparisonResults = OverrideHidingHelper.DetailedSignatureCompare(
firstSymbol,
secondSymbol,
significantDifferences,
significantDifferences)
' Signature must be considered equal following VB rules.
If comparisonResults = 0 Then
Dim accessibilityCmp As Integer = LookupResult.CompareAccessibilityOfSymbolsConflictingInSameContainer(firstSymbol, secondSymbol)
If accessibilityCmp > 0 Then
' first wins
quickInfo(l) = Nothing
ElseIf accessibilityCmp < 0 Then
' second wins
quickInfo(k) = info2
quickInfo(l) = Nothing
firstSymbol = secondSymbol
info = info2
Else
Debug.Assert(accessibilityCmp = 0)
info = New QuickApplicabilityInfo(info.Candidate, CandidateAnalysisResultState.Ambiguous)
quickInfo(k) = info
quickInfo(l) = New QuickApplicabilityInfo(info2.Candidate, CandidateAnalysisResultState.Ambiguous)
End If
End If
Next
If info.State <> CandidateAnalysisResultState.Ambiguous Then
CollectOverloadedCandidate(results, info, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
ElseIf includeEliminatedCandidates Then
CollectOverloadedCandidate(results, info, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
For l As Integer = k + 1 To quickInfo.Count - 1
Dim info2 As QuickApplicabilityInfo = quickInfo(l)
If info2.Candidate IsNot Nothing AndAlso info2.State = CandidateAnalysisResultState.Ambiguous Then
quickInfo(l) = Nothing
CollectOverloadedCandidate(results, info2, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
End If
Next
End If
Next
Next
quickInfo.Free()
#If DEBUG Then
group.Clear()
#End If
End Sub
Private Structure QuickApplicabilityInfo
Public ReadOnly Candidate As Candidate
Public ReadOnly State As CandidateAnalysisResultState
Public ReadOnly AppliesToNormalForm As Boolean
Public ReadOnly AppliesToParamArrayForm As Boolean
Public Sub New(
candidate As Candidate,
state As CandidateAnalysisResultState,
Optional appliesToNormalForm As Boolean = True,
Optional appliesToParamArrayForm As Boolean = True
)
Debug.Assert(candidate IsNot Nothing)
Debug.Assert(appliesToNormalForm OrElse appliesToParamArrayForm)
Me.Candidate = candidate
Me.State = state
Me.AppliesToNormalForm = appliesToNormalForm
Me.AppliesToParamArrayForm = appliesToParamArrayForm
End Sub
End Structure
Private Shared Function DoQuickApplicabilityCheck(
candidate As Candidate,
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
isQueryOperatorInvocation As Boolean,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As QuickApplicabilityInfo
If isQueryOperatorInvocation AndAlso DirectCast(candidate.UnderlyingSymbol, MethodSymbol).IsSub Then
' Subs are never considered as candidates for Query Operators, but method group might have subs in it.
Return Nothing
End If
If candidate.UnderlyingSymbol.HasUnsupportedMetadata Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.HasUnsupportedMetadata)
End If
' If type arguments have been supplied, eliminate procedures that don't have an
' appropriate number of type parameters.
'§11.8.2 Applicable Methods
'Section 4.
' If type arguments have been specified, they are matched against the type parameter list.
' If the two lists do not have the same number of elements, the method is not applicable,
' unless the type argument list is empty.
If typeArguments.Length > 0 AndAlso candidate.Arity <> typeArguments.Length Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.BadGenericArity)
End If
' Eliminate procedures that cannot accept the number of supplied arguments.
Dim requiredCount As Integer
Dim maxCount As Integer
Dim hasParamArray As Boolean
candidate.GetAllParameterCounts(requiredCount, maxCount, hasParamArray)
'§11.8.2 Applicable Methods
'If there are more positional arguments than parameters and the last parameter is not a paramarray,
'the method is not applicable. Otherwise, the paramarray parameter is expanded with parameters of
'the paramarray element type to match the number of positional arguments. If a single argument expression
'matches a paramarray parameter and the type of the argument expression is convertible to both the type of
'the paramarray parameter and the paramarray element type, the method is applicable in both its expanded
'and unexpanded forms, with two exceptions. If the conversion from the type of the argument expression to
'the paramarray type is narrowing, then the method is only applicable in its expanded form. If the argument
'expression is the literal Nothing, then the method is only applicable in its unexpanded form.
If isQueryOperatorInvocation Then
' Query operators require exact match for argument count.
If arguments.Length <> maxCount Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.ArgumentCountMismatch, True, False)
End If
ElseIf arguments.Length < requiredCount OrElse
(Not hasParamArray AndAlso arguments.Length > maxCount) Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.ArgumentCountMismatch, Not hasParamArray, hasParamArray)
End If
Dim candidateUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = candidate.UnderlyingSymbol.GetUseSiteInfo()
useSiteInfo.Add(candidateUseSiteInfo)
If candidateUseSiteInfo.DiagnosticInfo IsNot Nothing Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.HasUseSiteError)
End If
' A method with a paramarray can be considered in two forms: in an
' expanded form or in an unexpanded form (i.e. as if the paramarray
' decoration was not specified). It can apply in both forms, as
' in the case of passing Object() to ParamArray x As Object() (because
' Object() converts to both Object() and Object).
' Does the method apply in its unexpanded form? This can only happen if
' either there is no paramarray or if the argument count matches exactly
' (if it's less, then the paramarray is expanded to nothing, if it's more,
' it's expanded to one or more parameters).
Dim applicableInNormalForm As Boolean = False
Dim applicableInParamArrayForm As Boolean = False
If Not hasParamArray OrElse (arguments.Length = maxCount AndAlso Not forceExpandedForm) Then
applicableInNormalForm = True
End If
' How about it's expanded form? It always applies if there's a paramarray.
If hasParamArray AndAlso Not isQueryOperatorInvocation Then
applicableInParamArrayForm = True
End If
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.Applicable, applicableInNormalForm, applicableInParamArrayForm)
End Function
Private Shared Sub CollectOverloadedCandidate(
results As ArrayBuilder(Of CandidateAnalysisResult),
candidate As QuickApplicabilityInfo,
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
includeEliminatedCandidates As Boolean,
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Select Case candidate.State
Case CandidateAnalysisResultState.HasUnsupportedMetadata
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.HasUnsupportedMetadata))
End If
Case CandidateAnalysisResultState.HasUseSiteError
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.HasUseSiteError))
End If
Case CandidateAnalysisResultState.BadGenericArity
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.BadGenericArity))
End If
Case CandidateAnalysisResultState.ArgumentCountMismatch
Debug.Assert(candidate.AppliesToNormalForm <> candidate.AppliesToParamArrayForm)
If includeEliminatedCandidates Then
Dim candidateAnalysis As New CandidateAnalysisResult(ConstructIfNeedTo(candidate.Candidate, typeArguments), CandidateAnalysisResultState.ArgumentCountMismatch)
If candidate.AppliesToParamArrayForm Then
candidateAnalysis.SetIsExpandedParamArrayForm()
End If
results.Add(candidateAnalysis)
End If
Case CandidateAnalysisResultState.Applicable
Dim candidateAnalysis As CandidateAnalysisResult
If typeArguments.Length > 0 Then
candidateAnalysis = New CandidateAnalysisResult(candidate.Candidate.Construct(typeArguments))
Else
candidateAnalysis = New CandidateAnalysisResult(candidate.Candidate)
End If
#If DEBUG Then
Dim triedToAddSomething As Boolean = False
#End If
If candidate.AppliesToNormalForm Then
#If DEBUG Then
triedToAddSomething = True
#End If
InferTypeArgumentsIfNeedToAndCombineWithExistingCandidates(results, candidateAnalysis, typeArguments,
arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
End If
' How about it's expanded form? It always applies if there's a paramarray.
If candidate.AppliesToParamArrayForm Then
#If DEBUG Then
triedToAddSomething = True
#End If
candidateAnalysis.SetIsExpandedParamArrayForm()
candidateAnalysis.ExpandedParamArrayArgumentsUsed = Math.Max(arguments.Length - candidate.Candidate.ParameterCount + 1, 0)
InferTypeArgumentsIfNeedToAndCombineWithExistingCandidates(results, candidateAnalysis, typeArguments,
arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
End If
#If DEBUG Then
Debug.Assert(triedToAddSomething)
#End If
Case CandidateAnalysisResultState.Ambiguous
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.Ambiguous))
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(candidate.State)
End Select
End Sub
Private Shared Sub InferTypeArgumentsIfNeedToAndCombineWithExistingCandidates(
results As ArrayBuilder(Of CandidateAnalysisResult),
newCandidate As CandidateAnalysisResult,
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
If typeArguments.Length = 0 AndAlso newCandidate.Candidate.Arity > 0 Then
'§11.8.2 Applicable Methods
'Section 4.
'If the type argument list is empty, type inferencing is used to try and infer the type argument list.
'If type inferencing fails, the method is not applicable. Otherwise, the type arguments are filled
'in the place of the type parameters in the signature.
If Not InferTypeArguments(newCandidate, arguments, argumentNames, delegateReturnType, delegateReturnTypeReferenceBoundNode,
asyncLambdaSubToFunctionMismatch, binder, useSiteInfo) Then
Debug.Assert(newCandidate.State <> CandidateAnalysisResultState.Applicable)
results.Add(newCandidate)
Return
End If
End If
CombineCandidates(results, newCandidate, arguments.Length, argumentNames, useSiteInfo)
End Sub
''' <summary>
''' Combine new candidate with the list of existing candidates, applying various shadowing and
''' tie-breaking rules. New candidate may or may not be added to the result, some
''' existing candidates may be removed from the result.
''' </summary>
Private Shared Sub CombineCandidates(
results As ArrayBuilder(Of CandidateAnalysisResult),
newCandidate As CandidateAnalysisResult,
argumentCount As Integer,
argumentNames As ImmutableArray(Of String),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(newCandidate.State = CandidateAnalysisResultState.Applicable)
Dim operatorResolution As Boolean = newCandidate.Candidate.IsOperator
Debug.Assert(newCandidate.Candidate.ParameterCount >= argumentCount OrElse newCandidate.IsExpandedParamArrayForm)
Debug.Assert(argumentNames.IsDefault OrElse argumentNames.Length > 0)
Debug.Assert(Not operatorResolution OrElse argumentNames.IsDefault)
Dim i As Integer = 0
While i < results.Count
Dim existingCandidate As CandidateAnalysisResult = results(i)
' Skip over some eliminated candidates, which we will be unable to match signature against.
If existingCandidate.State = CandidateAnalysisResultState.ArgumentCountMismatch OrElse
existingCandidate.State = CandidateAnalysisResultState.BadGenericArity OrElse
existingCandidate.State = CandidateAnalysisResultState.Ambiguous Then
GoTo ContinueCandidatesLoop
End If
' Candidate can't hide another form of itself
If existingCandidate.Candidate Is newCandidate.Candidate Then
Debug.Assert(Not operatorResolution)
GoTo ContinueCandidatesLoop
End If
Dim existingWins As Boolean = False
Dim newWins As Boolean = False
' An overriding method hides the methods it overrides.
' In particular, this rule takes care of bug VSWhidbey #385900. Where type argument inference fails
' for an overriding method due to named argument name mismatch, but succeeds for the overridden method
' from base (the overridden method uses parameter name matching the named argument name). At the end,
' however, the overriding method is called, even though it doesn't have parameter with matching name.
' Also helps with methods overridden by restricted types (TypedReference, etc.), ShadowBasedOnReceiverType
' doesn't do the job for them because it relies on Conversions.ClassifyDirectCastConversion, which
' disallows boxing conversion for restricted types.
If Not operatorResolution AndAlso ShadowBasedOnOverriding(existingCandidate, newCandidate, existingWins, newWins) Then
GoTo DeterminedTheWinner
End If
If existingCandidate.State = CandidateAnalysisResultState.TypeInferenceFailed OrElse existingCandidate.SomeInferenceFailed OrElse
existingCandidate.State = CandidateAnalysisResultState.HasUseSiteError OrElse
existingCandidate.State = CandidateAnalysisResultState.HasUnsupportedMetadata Then
' Won't be able to match signature.
GoTo ContinueCandidatesLoop
End If
' It looks like the following code is applying some tie-breaking rules from section 7 of
' §11.8.1 Overloaded Method Resolution, but not all of them and even skips ParamArrays tie-breaking
' rule in some scenarios. I couldn't find an explanation of this behavior in the spec and
' simply tried to keep this code close to Dev10.
' Spec says that the tie-breaking rules should be applied only for members equally applicable to the argument list.
' [§11.8.1.1 Applicability] defines equally applicable members as follows:
' A member M is considered equally applicable as N if
' 1) their signatures are the same or
' 2) if each parameter type in M is the same as the corresponding parameter type in N.
' We can always check if signature is the same, but we cannot check the second condition in presence
' of named arguments because for them we don't know yet which parameter in M corresponds to which
' parameter in N.
Debug.Assert(existingCandidate.Candidate.ParameterCount >= argumentCount OrElse existingCandidate.IsExpandedParamArrayForm)
If argumentNames.IsDefault Then
Dim existingParamIndex As Integer = 0
Dim newParamIndex As Integer = 0
'CONSIDER: Can we somehow merge this with the complete signature comparison?
For j As Integer = 0 To argumentCount - 1 Step 1
Dim existingType As TypeSymbol = GetParameterTypeFromVirtualSignature(existingCandidate, existingParamIndex)
Dim newType As TypeSymbol = GetParameterTypeFromVirtualSignature(newCandidate, newParamIndex)
If Not existingType.IsSameTypeIgnoringAll(newType) Then
' Signatures are different, shadowing rules do not apply
GoTo ContinueCandidatesLoop
End If
' Advance to the next parameter in the existing candidate,
' unless we are on the expanded ParamArray parameter.
AdvanceParameterInVirtualSignature(existingCandidate, existingParamIndex)
' Advance to the next parameter in the new candidate,
' unless we are on the expanded ParamArray parameter.
AdvanceParameterInVirtualSignature(newCandidate, newParamIndex)
Next
Else
Debug.Assert(Not operatorResolution)
End If
Dim signatureMatch As Boolean = True
' Compare complete signature, with no regard to arguments
If existingCandidate.Candidate.ParameterCount <> newCandidate.Candidate.ParameterCount Then
Debug.Assert(Not operatorResolution)
signatureMatch = False
ElseIf operatorResolution Then
Debug.Assert(argumentCount = existingCandidate.Candidate.ParameterCount)
Debug.Assert(signatureMatch)
' Not lifted operators are preferred over lifted.
If existingCandidate.Candidate.IsLifted Then
If Not newCandidate.Candidate.IsLifted Then
newWins = True
GoTo DeterminedTheWinner
End If
ElseIf newCandidate.Candidate.IsLifted Then
Debug.Assert(Not existingCandidate.Candidate.IsLifted)
existingWins = True
GoTo DeterminedTheWinner
End If
Else
For j As Integer = 0 To existingCandidate.Candidate.ParameterCount - 1 Step 1
Dim existingType As TypeSymbol = existingCandidate.Candidate.Parameters(j).Type
Dim newType As TypeSymbol = newCandidate.Candidate.Parameters(j).Type
If Not existingType.IsSameTypeIgnoringAll(newType) Then
signatureMatch = False
Exit For
End If
Next
End If
If Not argumentNames.IsDefault AndAlso Not signatureMatch Then
' Signatures are different, shadowing rules do not apply
GoTo ContinueCandidatesLoop
End If
If Not signatureMatch Then
Debug.Assert(argumentNames.IsDefault)
' If we have gotten to this point it means that the 2 procedures have equal specificity,
' but signatures that do not match exactly (after generic substitution). This
' implies that we are dealing with differences in shape due to param arrays
' or optional arguments.
' So we look and see if one procedure maps fewer arguments to the
' param array than the other. The one using more, is then shadowed by the one using less.
'• If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
If ShadowBasedOnParamArrayUsage(existingCandidate, newCandidate, existingWins, newWins) Then
GoTo DeterminedTheWinner
End If
Else
' The signatures of the two methods match (after generic parameter substitution).
' This means that param array shadowing doesn't come into play.
' !!! Why? Where is this mentioned in the spec?
End If
Debug.Assert(argumentNames.IsDefault OrElse signatureMatch)
' In presence of named arguments, the following shadowing rules
' cannot be applied if any candidate is extension method because
' full signature match doesn't guarantee equal applicability (in presence of named arguments)
' and instance methods hide by signature regardless applicability rules do not apply to extension methods.
If argumentNames.IsDefault OrElse
Not (existingCandidate.Candidate.IsExtensionMethod OrElse newCandidate.Candidate.IsExtensionMethod) Then
'7.1. If M is defined in a more derived type than N, eliminate N from the set.
' This rule also applies to the types that extension methods are defined on.
'7.2. If M and N are extension methods and the target type of M is a class or
' structure and the target type of N is an interface, eliminate N from the set.
If ShadowBasedOnReceiverType(existingCandidate, newCandidate, existingWins, newWins, useSiteInfo) Then
GoTo DeterminedTheWinner
End If
'7.3. If M and N are extension methods and the target type of M has fewer type
' parameters than the target type of N, eliminate N from the set.
' !!! Note that spec talks about "fewer type parameters", but it is not really about count.
' !!! It is about one refers to a type parameter and the other one doesn't.
If ShadowBasedOnExtensionMethodTargetTypeGenericity(existingCandidate, newCandidate, existingWins, newWins) Then
GoTo DeterminedTheWinner
End If
End If
DeterminedTheWinner:
Debug.Assert(Not existingWins OrElse Not newWins) ' Both cannot win!
If newWins Then
' Remove existing
results.RemoveAt(i)
' We should continue the loop because at least with
' extension methods in the picture, there could be other
' winners and losers in the results.
' Since we removed the element, we should bypass index increment.
Continue While
ElseIf existingWins Then
' New candidate lost, shouldn't add it.
Return
End If
ContinueCandidatesLoop:
i += 1
End While
results.Add(newCandidate)
End Sub
Private Shared Function ShadowBasedOnOverriding(
existingCandidate As CandidateAnalysisResult, newCandidate As CandidateAnalysisResult,
ByRef existingWins As Boolean, ByRef newWins As Boolean
) As Boolean
Dim existingSymbol As Symbol = existingCandidate.Candidate.UnderlyingSymbol
Dim newSymbol As Symbol = newCandidate.Candidate.UnderlyingSymbol
Dim existingType As NamedTypeSymbol = existingSymbol.ContainingType
Dim newType As NamedTypeSymbol = newSymbol.ContainingType
' Optimization: We will rely on ShadowBasedOnReceiverType to give us the
' same effect later on for cases when existingCandidate is
' applicable and neither candidate is from restricted type.
Dim existingIsApplicable As Boolean = (existingCandidate.State = CandidateAnalysisResultState.Applicable)
If existingIsApplicable AndAlso Not existingType.IsRestrictedType() AndAlso Not newType.IsRestrictedType() Then
Return False
End If
' Optimization: symbols from the same type can't override each other.
' ShadowBasedOnReceiverType
If existingType.OriginalDefinition IsNot newType.OriginalDefinition Then
If newCandidate.Candidate.IsOverriddenBy(existingSymbol) Then
existingWins = True
Return True
ElseIf existingIsApplicable AndAlso existingCandidate.Candidate.IsOverriddenBy(newSymbol) Then
newWins = True
Return True
End If
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.5. If M is not an extension method and N is, eliminate N from the set.
''' 7.6. If M and N are extension methods and M was found before N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnExtensionVsInstanceAndPrecedence(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
If left.Candidate.IsExtensionMethod Then
If Not right.Candidate.IsExtensionMethod Then
'7.5.
rightWins = True
Return True
Else
' Both are extensions
If left.Candidate.PrecedenceLevel < right.Candidate.PrecedenceLevel Then
'7.6.
leftWins = True
Return True
ElseIf left.Candidate.PrecedenceLevel > right.Candidate.PrecedenceLevel Then
'7.6.
rightWins = True
Return True
End If
End If
ElseIf right.Candidate.IsExtensionMethod Then
'7.5.
leftWins = True
Return True
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.4. If M is less generic than N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnGenericity(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As Boolean
' §11.8.1.2 Genericity
' A member M is determined to be less generic than a member N as follows:
'
' 1. If, for each pair of matching parameters Mj and Nj, Mj is less or equally generic than Nj
' with respect to type parameters on the method, and at least one Mj is less generic with
' respect to type parameters on the method.
' 2. Otherwise, if for each pair of matching parameters Mj and Nj, Mj is less or equally generic
' than Nj with respect to type parameters on the type, and at least one Mj is less generic with
' respect to type parameters on the type, then M is less generic than N.
'
' A parameter M is considered to be equally generic to a parameter N if their types Mt and Nt
' both refer to type parameters or both don't refer to type parameters. M is considered to be less
' generic than N if Mt does not refer to a type parameter and Nt does.
'
' Extension method type parameters that were fixed during currying are considered type parameters on the type,
' not type parameters on the method.
' At the beginning we will track both method and type type parameters.
Dim track As TypeParameterKind = TypeParameterKind.Both
If Not (left.Candidate.IsGeneric OrElse right.Candidate.IsGeneric) Then
track = track And (Not TypeParameterKind.Method)
End If
If Not ((left.Candidate.UnderlyingSymbol.ContainingType.IsOrInGenericType() OrElse
(left.Candidate.IsExtensionMethod AndAlso Not left.Candidate.FixedTypeParameters.IsNull)) OrElse
(right.Candidate.UnderlyingSymbol.ContainingType.IsOrInGenericType() OrElse
(right.Candidate.IsExtensionMethod AndAlso Not right.Candidate.FixedTypeParameters.IsNull))) Then
track = track And (Not TypeParameterKind.Type)
End If
If track = TypeParameterKind.None Then
Return False ' There is no winner.
End If
#If DEBUG Then
Dim saveTrack = track
#End If
Dim leftHasLeastGenericParameterAgainstMethod As Boolean = False
Dim leftHasLeastGenericParameterAgainstType As Boolean = False
Dim rightHasLeastGenericParameterAgainstMethod As Boolean = False
Dim rightHasLeastGenericParameterAgainstType As Boolean = False
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For i = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Dim leftParamTypeForGenericityCheck As TypeSymbol = Nothing
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex, leftParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(i), leftParamTypeForGenericityCheck)
End If
Dim rightParamType As TypeSymbol
Dim rightParamTypeForGenericityCheck As TypeSymbol = Nothing
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex, rightParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(i), rightParamTypeForGenericityCheck)
End If
' Parameters matching omitted arguments do not participate.
If arguments(i).Kind = BoundKind.OmittedArgument Then
Continue For
End If
If SignatureMismatchForThePurposeOfShadowingBasedOnGenericity(leftParamType, rightParamType, arguments(i), binder) Then
Return False
End If
Dim leftRefersTo As TypeParameterKind = DetectReferencesToGenericParameters(leftParamTypeForGenericityCheck, track, left.Candidate.FixedTypeParameters)
Dim rightRefersTo As TypeParameterKind = DetectReferencesToGenericParameters(rightParamTypeForGenericityCheck, track, right.Candidate.FixedTypeParameters)
' Still looking for less generic with respect to type parameters on the method.
If (track And TypeParameterKind.Method) <> 0 Then
If (leftRefersTo And TypeParameterKind.Method) = 0 Then
If (rightRefersTo And TypeParameterKind.Method) <> 0 Then
leftHasLeastGenericParameterAgainstMethod = True
End If
ElseIf (rightRefersTo And TypeParameterKind.Method) = 0 Then
rightHasLeastGenericParameterAgainstMethod = True
End If
' If both won at least once, neither candidate is less generic with respect to type parameters on the method.
' Stop checking for this.
If leftHasLeastGenericParameterAgainstMethod AndAlso rightHasLeastGenericParameterAgainstMethod Then
track = track And (Not TypeParameterKind.Method)
End If
End If
' Still looking for less generic with respect to type parameters on the type.
If (track And TypeParameterKind.Type) <> 0 Then
If (leftRefersTo And TypeParameterKind.Type) = 0 Then
If (rightRefersTo And TypeParameterKind.Type) <> 0 Then
leftHasLeastGenericParameterAgainstType = True
End If
ElseIf (rightRefersTo And TypeParameterKind.Type) = 0 Then
rightHasLeastGenericParameterAgainstType = True
End If
' If both won at least once, neither candidate is less generic with respect to type parameters on the type.
' Stop checking for this.
If leftHasLeastGenericParameterAgainstType AndAlso rightHasLeastGenericParameterAgainstType Then
track = track And (Not TypeParameterKind.Type)
End If
End If
' Are we still looking for a winner?
If track = TypeParameterKind.None Then
#If DEBUG Then
Debug.Assert((saveTrack And TypeParameterKind.Method) = 0 OrElse (leftHasLeastGenericParameterAgainstMethod AndAlso rightHasLeastGenericParameterAgainstMethod))
Debug.Assert((saveTrack And TypeParameterKind.Type) = 0 OrElse (leftHasLeastGenericParameterAgainstType AndAlso rightHasLeastGenericParameterAgainstType))
#End If
Return False ' There is no winner.
End If
Next
If leftHasLeastGenericParameterAgainstMethod Then
If Not rightHasLeastGenericParameterAgainstMethod Then
leftWins = True
Return True
End If
ElseIf rightHasLeastGenericParameterAgainstMethod Then
rightWins = True
Return True
End If
If leftHasLeastGenericParameterAgainstType Then
If Not rightHasLeastGenericParameterAgainstType Then
leftWins = True
Return True
End If
ElseIf rightHasLeastGenericParameterAgainstType Then
rightWins = True
Return True
End If
Return False
End Function
Private Shared Function SignatureMismatchForThePurposeOfShadowingBasedOnGenericity(
leftParamType As TypeSymbol,
rightParamType As TypeSymbol,
argument As BoundExpression,
binder As Binder
) As Boolean
Debug.Assert(argument.Kind <> BoundKind.OmittedArgument)
' See Semantics::CompareGenericityIsSignatureMismatch in native compiler.
If leftParamType.IsSameTypeIgnoringAll(rightParamType) Then
Return False
Else
' Note: Undocumented rule.
' Different types. We still consider them the same if they are delegates with
' equivalent signatures, after possibly unwrapping Expression(Of D).
Dim leftIsExpressionTree As Boolean, rightIsExpressionTree As Boolean
Dim leftDelegateType As NamedTypeSymbol = leftParamType.DelegateOrExpressionDelegate(binder, leftIsExpressionTree)
Dim rightDelegateType As NamedTypeSymbol = rightParamType.DelegateOrExpressionDelegate(binder, rightIsExpressionTree)
' Native compiler will only compare D1 and D2 for Expression(Of D1) and D2 if the argument is a lambda. It will compare
' Expression(Of D1) and Expression (Of D2) regardless of the argument.
If leftDelegateType IsNot Nothing AndAlso rightDelegateType IsNot Nothing AndAlso
((leftIsExpressionTree = rightIsExpressionTree) OrElse argument.IsAnyLambda()) Then
Dim leftInvoke = leftDelegateType.DelegateInvokeMethod
Dim rightInvoke = rightDelegateType.DelegateInvokeMethod
If leftInvoke IsNot Nothing AndAlso rightInvoke IsNot Nothing AndAlso
MethodSignatureComparer.ParametersAndReturnTypeSignatureComparer.Equals(leftInvoke, rightInvoke) Then
Return False
End If
End If
End If
Return True
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1.3 Depth of genericity
''' </summary>
Private Shared Function ShadowBasedOnDepthOfGenericity(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As Boolean
' §11.8.1.3 Depth of Genericity
' A member M is determined to have greater depth of genericity than a member N if, for each pair
' of matching parameters Mj and Nj, Mj has greater or equal depth of genericity than Nj, and at
' least one Mj has greater depth of genericity. Depth of genericity is defined as follows:
'
' 1. Anything other than a type parameter has greater depth of genericity than a type parameter;
' 2. Recursively, a constructed type has greater depth of genericity than another constructed type
' (with the same number of type arguments) if at least one type argument has greater depth
' of genericity and no type argument has less depth than the corresponding type argument in the other.
' 3. An array type has greater depth of genericity than another array type (with the same number
' of dimensions) if the element type of the first has greater depth of genericity than the
' element type of the second.
'
' For example:
'
' Module Test
' Sub f(Of T)(x As Task(Of T))
' End Sub
' Sub f(Of T)(x As T)
' End Sub
' Sub Main()
' Dim x As Task(Of Integer) = Nothing
' f(x) ' Calls the first overload
' End Sub
' End Module
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For i = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Dim leftParamTypeForGenericityCheck As TypeSymbol = Nothing
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex, leftParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(i), leftParamTypeForGenericityCheck)
End If
Dim rightParamType As TypeSymbol
Dim rightParamTypeForGenericityCheck As TypeSymbol = Nothing
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex, rightParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(i), rightParamTypeForGenericityCheck)
End If
' Parameters matching omitted arguments do not participate.
If arguments(i).Kind = BoundKind.OmittedArgument Then
Continue For
End If
If SignatureMismatchForThePurposeOfShadowingBasedOnGenericity(leftParamType, rightParamType, arguments(i), binder) Then
Return False ' no winner if the types of the parameter are different
End If
Dim leftParamWins As Boolean = False
Dim rightParamWins As Boolean = False
If CompareParameterTypeGenericDepth(leftParamTypeForGenericityCheck, rightParamTypeForGenericityCheck, leftParamWins, rightParamWins) Then
Debug.Assert(leftParamWins <> rightParamWins)
If leftParamWins Then
If rightWins Then
rightWins = False
Return False ' both won
Else
leftWins = True
End If
Else
If leftWins Then
leftWins = False
Return False ' both won
Else
rightWins = True
End If
End If
End If
Next
Debug.Assert(Not leftWins OrElse Not rightWins)
Return leftWins OrElse rightWins
End Function
''' <summary>
'''
''' </summary>
''' <returns>False if node of candidates wins</returns>
Private Shared Function CompareParameterTypeGenericDepth(leftType As TypeSymbol, rightType As TypeSymbol,
ByRef leftWins As Boolean, ByRef rightWins As Boolean) As Boolean
' Depth of genericity is defined as follows:
' 1. Anything other than a type parameter has greater depth of genericity than a type parameter;
' 2. Recursively, a constructed type has greater depth of genericity than another constructed
' type (with the same number of type arguments) if at least one type argument has greater
' depth of genericity and no type argument has less depth than the corresponding type
' argument in the other.
' 3. An array type has greater depth of genericity than another array type (with the same number
' of dimensions) if the element type of the first has greater depth of genericity than the
' element type of the second.
'
' For exact rules see Dev11 OverloadResolution.cpp: void Semantics::CompareParameterTypeGenericDepth(...)
If leftType Is rightType Then
Return False
End If
If leftType.IsTypeParameter Then
If rightType.IsTypeParameter Then
' Both type parameters => no winner
Return False
Else
' Left is a type parameter, but right is not
rightWins = True
Return True
End If
ElseIf rightType.IsTypeParameter Then
' Right is a type parameter, but left is not
leftWins = True
Return True
End If
' None of the two is a type parameter
If leftType.IsArrayType AndAlso rightType.IsArrayType Then
' Both are arrays
Dim leftArray = DirectCast(leftType, ArrayTypeSymbol)
Dim rightArray = DirectCast(rightType, ArrayTypeSymbol)
If leftArray.HasSameShapeAs(rightArray) Then
Return CompareParameterTypeGenericDepth(leftArray.ElementType, rightArray.ElementType, leftWins, rightWins)
End If
End If
' Both are generics
If leftType.Kind = SymbolKind.NamedType AndAlso rightType.Kind = SymbolKind.NamedType Then
Dim leftNamedType = DirectCast(leftType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol)
Dim rightNamedType = DirectCast(rightType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol)
' If their arities are equal
If leftNamedType.Arity = rightNamedType.Arity Then
Dim leftTypeArguments As ImmutableArray(Of TypeSymbol) = leftNamedType.TypeArgumentsNoUseSiteDiagnostics
Dim rightTypeArguments As ImmutableArray(Of TypeSymbol) = rightNamedType.TypeArgumentsNoUseSiteDiagnostics
For i = 0 To leftTypeArguments.Length - 1
Dim leftArgWins As Boolean = False
Dim rightArgWins As Boolean = False
If CompareParameterTypeGenericDepth(leftTypeArguments(i), rightTypeArguments(i), leftArgWins, rightArgWins) Then
Debug.Assert(leftArgWins <> rightArgWins)
If leftArgWins Then
If rightWins Then
rightWins = False
Return False
Else
leftWins = True
End If
Else
If leftWins Then
leftWins = False
Return False
Else
rightWins = True
End If
End If
End If
Next
Debug.Assert(Not leftWins OrElse Not rightWins)
Return leftWins OrElse rightWins
End If
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.3. If M and N are extension methods and the target type of M has fewer type
''' parameters than the target type of N, eliminate N from the set.
''' !!! Note that spec talks about "fewer type parameters", but it is not really about count.
''' !!! It is about one refers to a type parameter and the other one doesn't.
''' </summary>
Private Shared Function ShadowBasedOnExtensionMethodTargetTypeGenericity(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
If Not left.Candidate.IsExtensionMethod OrElse Not right.Candidate.IsExtensionMethod Then
Return False
End If
'!!! Note, the spec does not mention this explicitly, but this rule applies only if receiver type
'!!! is the same for both methods.
If Not left.Candidate.ReceiverType.IsSameTypeIgnoringAll(right.Candidate.ReceiverType) Then
Return False
End If
' Only interested in method type parameters.
Dim leftRefersToATypeParameter = DetectReferencesToGenericParameters(left.Candidate.ReceiverTypeDefinition,
TypeParameterKind.Method,
BitVector.Null)
' Only interested in method type parameters.
Dim rightRefersToATypeParameter = DetectReferencesToGenericParameters(right.Candidate.ReceiverTypeDefinition,
TypeParameterKind.Method,
BitVector.Null)
If (leftRefersToATypeParameter And TypeParameterKind.Method) <> 0 Then
If (rightRefersToATypeParameter And TypeParameterKind.Method) = 0 Then
rightWins = True
Return True
End If
ElseIf (rightRefersToATypeParameter And TypeParameterKind.Method) <> 0 Then
leftWins = True
Return True
End If
Return False
End Function
<Flags()>
Private Enum TypeParameterKind
None = 0
Method = 1 << 0
Type = 1 << 1
Both = Method Or Type
End Enum
Private Shared Function DetectReferencesToGenericParameters(
symbol As NamedTypeSymbol,
track As TypeParameterKind,
methodTypeParametersToTreatAsTypeTypeParameters As BitVector
) As TypeParameterKind
Dim result As TypeParameterKind = TypeParameterKind.None
Do
If symbol Is symbol.OriginalDefinition Then
If (track And TypeParameterKind.Type) = 0 Then
Return result
End If
If symbol.Arity > 0 Then
Return result Or TypeParameterKind.Type
End If
Else
For Each argument As TypeSymbol In symbol.TypeArgumentsNoUseSiteDiagnostics
result = result Or DetectReferencesToGenericParameters(argument, track,
methodTypeParametersToTreatAsTypeTypeParameters)
If (result And track) = track Then
Return result
End If
Next
End If
symbol = symbol.ContainingType
Loop While symbol IsNot Nothing
Return result
End Function
Private Shared Function DetectReferencesToGenericParameters(
symbol As TypeParameterSymbol,
track As TypeParameterKind,
methodTypeParametersToTreatAsTypeTypeParameters As BitVector
) As TypeParameterKind
If symbol.ContainingSymbol.Kind = SymbolKind.NamedType Then
If (track And TypeParameterKind.Type) <> 0 Then
Return TypeParameterKind.Type
End If
Else
If methodTypeParametersToTreatAsTypeTypeParameters.IsNull OrElse Not methodTypeParametersToTreatAsTypeTypeParameters(symbol.Ordinal) Then
If (track And TypeParameterKind.Method) <> 0 Then
Return TypeParameterKind.Method
End If
Else
If (track And TypeParameterKind.Type) <> 0 Then
Return TypeParameterKind.Type
End If
End If
End If
Return TypeParameterKind.None
End Function
Private Shared Function DetectReferencesToGenericParameters(
this As TypeSymbol,
track As TypeParameterKind,
methodTypeParametersToTreatAsTypeTypeParameters As BitVector
) As TypeParameterKind
Select Case this.Kind
Case SymbolKind.TypeParameter
Return DetectReferencesToGenericParameters(DirectCast(this, TypeParameterSymbol), track,
methodTypeParametersToTreatAsTypeTypeParameters)
Case SymbolKind.ArrayType
Return DetectReferencesToGenericParameters(DirectCast(this, ArrayTypeSymbol).ElementType, track,
methodTypeParametersToTreatAsTypeTypeParameters)
Case SymbolKind.NamedType, SymbolKind.ErrorType
Return DetectReferencesToGenericParameters(DirectCast(this, NamedTypeSymbol), track,
methodTypeParametersToTreatAsTypeTypeParameters)
Case Else
Throw ExceptionUtilities.UnexpectedValue(this.Kind)
End Select
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.1. If M is defined in a more derived type than N, eliminate N from the set.
''' This rule also applies to the types that extension methods are defined on.
''' 7.2. If M and N are extension methods and the target type of M is a class or
''' structure and the target type of N is an interface, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnReceiverType(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
Dim leftType = left.Candidate.ReceiverType
Dim rightType = right.Candidate.ReceiverType
If Not leftType.IsSameTypeIgnoringAll(rightType) Then
If DoesReceiverMatchInstance(leftType, rightType, useSiteInfo) Then
leftWins = True
Return True
ElseIf DoesReceiverMatchInstance(rightType, leftType, useSiteInfo) Then
rightWins = True
Return True
End If
End If
Return False
End Function
''' <summary>
''' For a receiver to match an instance, more or less, the type of that instance has to be convertible
''' to the type of the receiver with the same bit-representation (i.e. identity on value-types
''' and reference-convertibility on reference types).
''' Actually, we don't include the reference-convertibilities that seem nonsensical, e.g. enum() to underlyingtype()
''' We do include inheritance, implements and variance conversions amongst others.
''' </summary>
Public Shared Function DoesReceiverMatchInstance(instanceType As TypeSymbol, receiverType As TypeSymbol, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean
Return Conversions.HasWideningDirectCastConversionButNotEnumTypeConversion(instanceType, receiverType, useSiteInfo)
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' • If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnParamArrayUsage(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
If left.IsExpandedParamArrayForm Then
If right.IsExpandedParamArrayForm Then
If left.ExpandedParamArrayArgumentsUsed > right.ExpandedParamArrayArgumentsUsed Then
rightWins = True
Return True
ElseIf left.ExpandedParamArrayArgumentsUsed < right.ExpandedParamArrayArgumentsUsed Then
leftWins = True
Return True
End If
Else
rightWins = True
Return True
End If
ElseIf right.IsExpandedParamArrayForm Then
leftWins = True
Return True
End If
Return False
End Function
Friend Shared Function GetParameterTypeFromVirtualSignature(
ByRef candidate As CandidateAnalysisResult,
paramIndex As Integer
) As TypeSymbol
Dim paramType As TypeSymbol = candidate.Candidate.Parameters(paramIndex).Type
If candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
paramType.Kind = SymbolKind.ArrayType Then
paramType = DirectCast(paramType, ArrayTypeSymbol).ElementType
End If
Return paramType
End Function
Private Shared Function GetParameterTypeFromVirtualSignature(
ByRef candidate As CandidateAnalysisResult,
paramIndex As Integer,
ByRef typeForGenericityCheck As TypeSymbol
) As TypeSymbol
Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex)
Dim paramForGenericityCheck = param.OriginalDefinition
If paramForGenericityCheck.ContainingSymbol.Kind = SymbolKind.Method Then
Dim method = DirectCast(paramForGenericityCheck.ContainingSymbol, MethodSymbol)
If method.IsReducedExtensionMethod Then
paramForGenericityCheck = method.ReducedFrom.Parameters(paramIndex + 1)
End If
End If
Dim paramType As TypeSymbol = param.Type
typeForGenericityCheck = paramForGenericityCheck.Type
If candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
paramType.Kind = SymbolKind.ArrayType Then
paramType = DirectCast(paramType, ArrayTypeSymbol).ElementType
typeForGenericityCheck = DirectCast(typeForGenericityCheck, ArrayTypeSymbol).ElementType
End If
Return paramType
End Function
Friend Shared Sub AdvanceParameterInVirtualSignature(
ByRef candidate As CandidateAnalysisResult,
ByRef paramIndex As Integer
)
If Not (candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1) Then
paramIndex += 1
End If
End Sub
Private Shared Function InferTypeArguments(
ByRef candidate As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Nothing
Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing
BuildParameterToArgumentMap(candidate, arguments, argumentNames, parameterToArgumentMap, paramArrayItems)
If candidate.State = CandidateAnalysisResultState.Applicable Then
Dim typeArguments As ImmutableArray(Of TypeSymbol) = Nothing
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = TypeArgumentInference.InferenceLevel.None
Dim allFailedInferenceIsDueToObject As Boolean = False
Dim someInferenceFailed As Boolean = False
Dim inferenceErrorReasons As InferenceErrorReasons = InferenceErrorReasons.Other
Dim inferredTypeByAssumption As BitVector = Nothing
Dim typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken) = Nothing
If TypeArgumentInference.Infer(DirectCast(candidate.Candidate.UnderlyingSymbol, MethodSymbol),
arguments, parameterToArgumentMap, paramArrayItems,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
typeArguments:=typeArguments,
inferenceLevel:=inferenceLevel,
someInferenceFailed:=someInferenceFailed,
allFailedInferenceIsDueToObject:=allFailedInferenceIsDueToObject,
inferenceErrorReasons:=inferenceErrorReasons,
inferredTypeByAssumption:=inferredTypeByAssumption,
typeArgumentsLocation:=typeArgumentsLocation,
asyncLambdaSubToFunctionMismatch:=asyncLambdaSubToFunctionMismatch,
useSiteInfo:=useSiteInfo,
diagnostic:=candidate.TypeArgumentInferenceDiagnosticsOpt) Then
candidate.SetInferenceLevel(inferenceLevel)
candidate.Candidate = candidate.Candidate.Construct(typeArguments)
' Need check for Option Strict and warn if parameter type is an assumed inferred type.
If binder.OptionStrict = OptionStrict.On AndAlso Not inferredTypeByAssumption.IsNull Then
For i As Integer = 0 To typeArguments.Length - 1 Step 1
If inferredTypeByAssumption(i) Then
Dim diagnostics = candidate.TypeArgumentInferenceDiagnosticsOpt
If diagnostics Is Nothing Then
diagnostics = BindingDiagnosticBag.Create(withDiagnostics:=True, useSiteInfo.AccumulatesDependencies)
candidate.TypeArgumentInferenceDiagnosticsOpt = diagnostics
End If
Binder.ReportDiagnostic(diagnostics,
typeArgumentsLocation(i),
ERRID.WRN_TypeInferenceAssumed3,
candidate.Candidate.TypeParameters(i),
DirectCast(candidate.Candidate.UnderlyingSymbol, MethodSymbol).OriginalDefinition,
typeArguments(i))
End If
Next
End If
Else
candidate.State = CandidateAnalysisResultState.TypeInferenceFailed
If someInferenceFailed Then
candidate.SetSomeInferenceFailed()
End If
If allFailedInferenceIsDueToObject Then
candidate.SetAllFailedInferenceIsDueToObject()
If Not candidate.Candidate.IsExtensionMethod Then
candidate.IgnoreExtensionMethods = True
End If
End If
candidate.SetInferenceErrorReasons(inferenceErrorReasons)
candidate.NotInferredTypeArguments = BitVector.Create(typeArguments.Length)
For i As Integer = 0 To typeArguments.Length - 1 Step 1
If typeArguments(i) Is Nothing Then
candidate.NotInferredTypeArguments(i) = True
End If
Next
End If
Else
candidate.SetSomeInferenceFailed()
End If
If paramArrayItems IsNot Nothing Then
paramArrayItems.Free()
End If
If parameterToArgumentMap IsNot Nothing Then
parameterToArgumentMap.Free()
End If
Return (candidate.State = CandidateAnalysisResultState.Applicable)
End Function
Private Shared Function ConstructIfNeedTo(candidate As Candidate, typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
If typeArguments.Length > 0 Then
Return candidate.Construct(typeArguments)
End If
Return candidate
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.Diagnostics
Imports System.Linq
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend NotInheritable Class OverloadResolution
Private Sub New()
Throw ExceptionUtilities.Unreachable
End Sub
''' <summary>
''' Information about a candidate from a group.
''' Will have different implementation for methods, extension methods and properties.
''' </summary>
''' <remarks></remarks>
Public MustInherit Class Candidate
Public MustOverride ReadOnly Property UnderlyingSymbol As Symbol
Friend MustOverride Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
''' <summary>
''' Whether the method is used as extension method vs. called as a static method.
''' </summary>
Public Overridable ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Whether the method is used as an operator.
''' </summary>
Public Overridable ReadOnly Property IsOperator As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Whether the method is used in a lifted to nullable form.
''' </summary>
Public Overridable ReadOnly Property IsLifted As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Precedence level for an extension method.
''' </summary>
Public Overridable ReadOnly Property PrecedenceLevel As Integer
Get
Return 0
End Get
End Property
''' <summary>
''' Extension method type parameters that were fixed during currying, if any.
''' If none were fixed, BitArray.Null should be returned.
''' </summary>
Public Overridable ReadOnly Property FixedTypeParameters As BitVector
Get
Return BitVector.Null
End Get
End Property
Public MustOverride ReadOnly Property IsGeneric As Boolean
Public MustOverride ReadOnly Property ParameterCount As Integer
Public MustOverride Function Parameters(index As Integer) As ParameterSymbol
Public MustOverride ReadOnly Property ReturnType As TypeSymbol
Public MustOverride ReadOnly Property Arity As Integer
Public MustOverride ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Friend Sub GetAllParameterCounts(
ByRef requiredCount As Integer,
ByRef maxCount As Integer,
ByRef hasParamArray As Boolean
)
maxCount = Me.ParameterCount
hasParamArray = False
requiredCount = -1
Dim last = maxCount - 1
For i As Integer = 0 To last Step 1
Dim param As ParameterSymbol = Me.Parameters(i)
If i = last AndAlso param.IsParamArray Then
hasParamArray = True
ElseIf Not param.IsOptional Then
requiredCount = i
End If
Next
requiredCount += 1
End Sub
Friend Function TryGetNamedParamIndex(name As String, ByRef index As Integer) As Boolean
For i As Integer = 0 To Me.ParameterCount - 1 Step 1
Dim param As ParameterSymbol = Me.Parameters(i)
If IdentifierComparison.Equals(name, param.Name) Then
index = i
Return True
End If
Next
index = -1
Return False
End Function
''' <summary>
''' Receiver type for extension method. Otherwise, containing type.
''' </summary>
Public MustOverride ReadOnly Property ReceiverType As TypeSymbol
''' <summary>
''' For extension methods, the type of the fist parameter in method's definition (i.e. before type parameters are substituted).
''' Otherwise, same as the ReceiverType.
''' </summary>
Public MustOverride ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Friend MustOverride Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
End Class
''' <summary>
''' Implementation for an ordinary method (based on usage).
''' </summary>
Public Class MethodCandidate
Inherits Candidate
Protected ReadOnly m_Method As MethodSymbol
Public Sub New(method As MethodSymbol)
Debug.Assert(method IsNot Nothing)
Debug.Assert(method.ReducedFrom Is Nothing OrElse Me.IsExtensionMethod)
m_Method = method
End Sub
Friend Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
Return New MethodCandidate(m_Method.Construct(typeArguments))
End Function
Public Overrides ReadOnly Property IsGeneric As Boolean
Get
Return m_Method.IsGenericMethod
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return m_Method.ParameterCount
End Get
End Property
Public Overrides Function Parameters(index As Integer) As ParameterSymbol
Return m_Method.Parameters(index)
End Function
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return m_Method.ReturnType
End Get
End Property
Public Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return m_Method.ContainingType
End Get
End Property
Public Overrides ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Get
Return m_Method.ContainingType
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return m_Method.Arity
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return m_Method.TypeParameters
End Get
End Property
Public Overrides ReadOnly Property UnderlyingSymbol As Symbol
Get
Return m_Method
End Get
End Property
Friend Overrides Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
Dim definition As MethodSymbol = m_Method.OriginalDefinition
If definition.IsOverridable OrElse definition.IsOverrides OrElse definition.IsMustOverride Then
Dim otherMethod As MethodSymbol = DirectCast(otherSymbol, MethodSymbol).OverriddenMethod
While otherMethod IsNot Nothing
If otherMethod.OriginalDefinition.Equals(definition) Then
Return True
End If
otherMethod = otherMethod.OverriddenMethod
End While
End If
Return False
End Function
End Class
''' <summary>
''' Implementation for an extension method, i.e. it is used as an extension method.
''' </summary>
Public NotInheritable Class ExtensionMethodCandidate
Inherits MethodCandidate
Private _fixedTypeParameters As BitVector
Public Sub New(method As MethodSymbol)
Me.New(method, GetFixedTypeParameters(method))
End Sub
' TODO: Consider building this bitmap lazily, on demand.
Private Shared Function GetFixedTypeParameters(method As MethodSymbol) As BitVector
If method.FixedTypeParameters.Length > 0 Then
Dim fixedTypeParameters = BitVector.Create(method.ReducedFrom.Arity)
For Each fixed As KeyValuePair(Of TypeParameterSymbol, TypeSymbol) In method.FixedTypeParameters
fixedTypeParameters(fixed.Key.Ordinal) = True
Next
Return fixedTypeParameters
End If
Return Nothing
End Function
Private Sub New(method As MethodSymbol, fixedTypeParameters As BitVector)
MyBase.New(method)
Debug.Assert(method.ReducedFrom IsNot Nothing)
_fixedTypeParameters = fixedTypeParameters
End Sub
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property PrecedenceLevel As Integer
Get
Return m_Method.Proximity
End Get
End Property
Public Overrides ReadOnly Property FixedTypeParameters As BitVector
Get
Return _fixedTypeParameters
End Get
End Property
Friend Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
Return New ExtensionMethodCandidate(m_Method.Construct(typeArguments), _fixedTypeParameters)
End Function
Public Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return m_Method.ReceiverType
End Get
End Property
Public Overrides ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Get
Return m_Method.ReducedFrom.Parameters(0).Type
End Get
End Property
Friend Overrides Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
Return False ' Extension methods never override/overridden
End Function
End Class
''' <summary>
''' Implementation for an operator
''' </summary>
Public Class OperatorCandidate
Inherits MethodCandidate
Public Sub New(method As MethodSymbol)
MyBase.New(method)
End Sub
Public NotOverridable Overrides ReadOnly Property IsOperator As Boolean
Get
Return True
End Get
End Property
End Class
''' <summary>
''' Implementation for a lifted operator.
''' </summary>
Public Class LiftedOperatorCandidate
Inherits OperatorCandidate
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
Private ReadOnly _returnType As TypeSymbol
Public Sub New(method As MethodSymbol, parameters As ImmutableArray(Of ParameterSymbol), returnType As TypeSymbol)
MyBase.New(method)
Debug.Assert(parameters.Length = method.ParameterCount)
_parameters = parameters
_returnType = returnType
End Sub
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return _parameters.Length
End Get
End Property
Public Overrides Function Parameters(index As Integer) As ParameterSymbol
Return _parameters(index)
End Function
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property IsLifted As Boolean
Get
Return True
End Get
End Property
End Class
''' <summary>
''' Implementation for a property.
''' </summary>
Public NotInheritable Class PropertyCandidate
Inherits Candidate
Private ReadOnly _property As PropertySymbol
Public Sub New([property] As PropertySymbol)
Debug.Assert([property] IsNot Nothing)
_property = [property]
End Sub
Friend Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides ReadOnly Property IsGeneric As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return _property.Parameters.Length
End Get
End Property
Public Overrides Function Parameters(index As Integer) As ParameterSymbol
Return _property.Parameters(index)
End Function
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _property.Type
End Get
End Property
Public Overrides ReadOnly Property ReceiverType As TypeSymbol
Get
Return _property.ContainingType
End Get
End Property
Public Overrides ReadOnly Property ReceiverTypeDefinition As TypeSymbol
Get
Return _property.ContainingType
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property UnderlyingSymbol As Symbol
Get
Return _property
End Get
End Property
Friend Overrides Function IsOverriddenBy(otherSymbol As Symbol) As Boolean
Dim definition As PropertySymbol = _property.OriginalDefinition
If definition.IsOverridable OrElse definition.IsOverrides OrElse definition.IsMustOverride Then
Dim otherProperty As PropertySymbol = DirectCast(otherSymbol, PropertySymbol).OverriddenProperty
While otherProperty IsNot Nothing
If otherProperty.OriginalDefinition.Equals(definition) Then
Return True
End If
otherProperty = otherProperty.OverriddenProperty
End While
End If
Return False
End Function
End Class
Private Const s_stateSize = 8 ' bit size of the following enum
Public Enum CandidateAnalysisResultState As Byte
Applicable
' All following states are to indicate inapplicability
HasUnsupportedMetadata
HasUseSiteError
Ambiguous
BadGenericArity
ArgumentCountMismatch
TypeInferenceFailed
ArgumentMismatch
GenericConstraintsViolated
RequiresNarrowing
RequiresNarrowingNotFromObject
ExtensionMethodVsInstanceMethod
Shadowed
LessApplicable
ExtensionMethodVsLateBinding
Count
End Enum
<Flags()>
Private Enum SmallFieldMask As Integer
State = (1 << s_stateSize) - 1
IsExpandedParamArrayForm = 1 << (s_stateSize + 0)
InferenceLevelShift = (s_stateSize + 1)
InferenceLevelMask = 3 << InferenceLevelShift ' 2 bits are used
ArgumentMatchingDone = 1 << (s_stateSize + 3)
RequiresNarrowingConversion = 1 << (s_stateSize + 4)
RequiresNarrowingNotFromObject = 1 << (s_stateSize + 5)
RequiresNarrowingNotFromNumericConstant = 1 << (s_stateSize + 6)
' Must be equal to ConversionKind.DelegateRelaxationLevelMask
' Compile time "asserts" below enforce it by reporting a compilation error in case of a violation.
' I am not using the form of
' DelegateRelaxationLevelMask = ConversionKind.DelegateRelaxationLevelMask
' to make it easier to reason about bits used relative to other values in this enum.
DelegateRelaxationLevelMask = 7 << (s_stateSize + 7) ' 3 bits used!
SomeInferenceFailed = 1 << (s_stateSize + 10)
AllFailedInferenceIsDueToObject = 1 << (s_stateSize + 11)
InferenceErrorReasonsShift = (s_stateSize + 12)
InferenceErrorReasonsMask = 3 << InferenceErrorReasonsShift
IgnoreExtensionMethods = 1 << (s_stateSize + 14)
IllegalInAttribute = 1 << (s_stateSize + 15)
End Enum
#If DEBUG Then
' Compile time asserts.
Private Const s_delegateRelaxationLevelMask_AssertZero = SmallFieldMask.DelegateRelaxationLevelMask - ConversionKind.DelegateRelaxationLevelMask
Private ReadOnly _delegateRelaxationLevelMask_Assert1(s_delegateRelaxationLevelMask_AssertZero) As Boolean
Private ReadOnly _delegateRelaxationLevelMask_Assert2(-s_delegateRelaxationLevelMask_AssertZero) As Boolean
Private Const s_inferenceLevelMask_AssertZero = CByte((SmallFieldMask.InferenceLevelMask >> SmallFieldMask.InferenceLevelShift) <> ((TypeArgumentInference.InferenceLevel.Invalid << 1) - 1))
Private ReadOnly _inferenceLevelMask_Assert1(s_inferenceLevelMask_AssertZero) As Boolean
Private ReadOnly _inferenceLevelMask_Assert2(-s_inferenceLevelMask_AssertZero) As Boolean
#End If
Public Structure OptionalArgument
Public ReadOnly DefaultValue As BoundExpression
Public ReadOnly Conversion As KeyValuePair(Of ConversionKind, MethodSymbol)
Public ReadOnly Dependencies As ImmutableArray(Of AssemblySymbol)
Public Sub New(value As BoundExpression, conversion As KeyValuePair(Of ConversionKind, MethodSymbol), dependencies As ImmutableArray(Of AssemblySymbol))
Me.DefaultValue = value
Me.Conversion = conversion
Me.Dependencies = dependencies.NullToEmpty()
End Sub
End Structure
Public Structure CandidateAnalysisResult
Public ReadOnly Property IsExpandedParamArrayForm As Boolean
Get
Return (_smallFields And SmallFieldMask.IsExpandedParamArrayForm) <> 0
End Get
End Property
Public Sub SetIsExpandedParamArrayForm()
_smallFields = _smallFields Or SmallFieldMask.IsExpandedParamArrayForm
End Sub
Public ReadOnly Property InferenceLevel As TypeArgumentInference.InferenceLevel
Get
Return CType((_smallFields And SmallFieldMask.InferenceLevelMask) >> SmallFieldMask.InferenceLevelShift, TypeArgumentInference.InferenceLevel)
End Get
End Property
Public Sub SetInferenceLevel(level As TypeArgumentInference.InferenceLevel)
Dim value As Integer = CInt(level) << SmallFieldMask.InferenceLevelShift
Debug.Assert((value And SmallFieldMask.InferenceLevelMask) = value)
_smallFields = (_smallFields And (Not SmallFieldMask.InferenceLevelMask)) Or (value And SmallFieldMask.InferenceLevelMask)
End Sub
Public ReadOnly Property ArgumentMatchingDone As Boolean
Get
Return (_smallFields And SmallFieldMask.ArgumentMatchingDone) <> 0
End Get
End Property
Public Sub SetArgumentMatchingDone()
_smallFields = _smallFields Or SmallFieldMask.ArgumentMatchingDone
End Sub
Public ReadOnly Property RequiresNarrowingConversion As Boolean
Get
Return (_smallFields And SmallFieldMask.RequiresNarrowingConversion) <> 0
End Get
End Property
Public Sub SetRequiresNarrowingConversion()
_smallFields = _smallFields Or SmallFieldMask.RequiresNarrowingConversion
End Sub
Public ReadOnly Property RequiresNarrowingNotFromObject As Boolean
Get
Return (_smallFields And SmallFieldMask.RequiresNarrowingNotFromObject) <> 0
End Get
End Property
Public Sub SetRequiresNarrowingNotFromObject()
_smallFields = _smallFields Or SmallFieldMask.RequiresNarrowingNotFromObject
End Sub
Public ReadOnly Property RequiresNarrowingNotFromNumericConstant As Boolean
Get
Return (_smallFields And SmallFieldMask.RequiresNarrowingNotFromNumericConstant) <> 0
End Get
End Property
Public Sub SetRequiresNarrowingNotFromNumericConstant()
Debug.Assert(RequiresNarrowingConversion)
IgnoreExtensionMethods = False
_smallFields = _smallFields Or SmallFieldMask.RequiresNarrowingNotFromNumericConstant
End Sub
''' <summary>
''' Only bits specific to delegate relaxation level are returned.
''' </summary>
Public ReadOnly Property MaxDelegateRelaxationLevel As ConversionKind
Get
Return CType(_smallFields And SmallFieldMask.DelegateRelaxationLevelMask, ConversionKind)
End Get
End Property
Public Sub RegisterDelegateRelaxationLevel(conversionKind As ConversionKind)
Dim relaxationLevel As Integer = (conversionKind And SmallFieldMask.DelegateRelaxationLevelMask)
If relaxationLevel > (_smallFields And SmallFieldMask.DelegateRelaxationLevelMask) Then
Debug.Assert(relaxationLevel <= ConversionKind.DelegateRelaxationLevelNarrowing)
If relaxationLevel = ConversionKind.DelegateRelaxationLevelNarrowing Then
IgnoreExtensionMethods = False
End If
_smallFields = (_smallFields And (Not SmallFieldMask.DelegateRelaxationLevelMask)) Or relaxationLevel
End If
End Sub
Public Sub SetSomeInferenceFailed()
_smallFields = _smallFields Or SmallFieldMask.SomeInferenceFailed
End Sub
Public ReadOnly Property SomeInferenceFailed As Boolean
Get
Return (_smallFields And SmallFieldMask.SomeInferenceFailed) <> 0
End Get
End Property
Public Sub SetIllegalInAttribute()
_smallFields = _smallFields Or SmallFieldMask.IllegalInAttribute
End Sub
Public ReadOnly Property IsIllegalInAttribute As Boolean
Get
Return (_smallFields And SmallFieldMask.IllegalInAttribute) <> 0
End Get
End Property
Public Sub SetAllFailedInferenceIsDueToObject()
_smallFields = _smallFields Or SmallFieldMask.AllFailedInferenceIsDueToObject
End Sub
Public ReadOnly Property AllFailedInferenceIsDueToObject As Boolean
Get
Return (_smallFields And SmallFieldMask.AllFailedInferenceIsDueToObject) <> 0
End Get
End Property
Public Sub SetInferenceErrorReasons(reasons As InferenceErrorReasons)
Dim value As Integer = CInt(reasons) << SmallFieldMask.InferenceErrorReasonsShift
Debug.Assert((value And SmallFieldMask.InferenceErrorReasonsMask) = value)
_smallFields = (_smallFields And (Not SmallFieldMask.InferenceErrorReasonsMask)) Or (value And SmallFieldMask.InferenceErrorReasonsMask)
End Sub
Public ReadOnly Property InferenceErrorReasons As InferenceErrorReasons
Get
Return CType((_smallFields And SmallFieldMask.InferenceErrorReasonsMask) >> SmallFieldMask.InferenceErrorReasonsShift, InferenceErrorReasons)
End Get
End Property
Public Property State As CandidateAnalysisResultState
Get
Return CType(_smallFields And SmallFieldMask.State, CandidateAnalysisResultState)
End Get
Set(value As CandidateAnalysisResultState)
Debug.Assert((value And (Not SmallFieldMask.State)) = 0)
Dim newFields = _smallFields And (Not SmallFieldMask.State)
newFields = newFields Or value
_smallFields = newFields
End Set
End Property
Public Property IgnoreExtensionMethods As Boolean
Get
Return (_smallFields And SmallFieldMask.IgnoreExtensionMethods) <> 0
End Get
Set(value As Boolean)
If value Then
_smallFields = _smallFields Or SmallFieldMask.IgnoreExtensionMethods
Else
_smallFields = _smallFields And (Not SmallFieldMask.IgnoreExtensionMethods)
End If
End Set
End Property
Private _smallFields As Integer
Public Candidate As Candidate
Public ExpandedParamArrayArgumentsUsed As Integer
Public EquallyApplicableCandidatesBucket As Integer
' When this is null, it means that arguments map to parameters sequentially
Public ArgsToParamsOpt As ImmutableArray(Of Integer)
' When these are null, it means that all conversions are identity conversions
Public ConversionsOpt As ImmutableArray(Of KeyValuePair(Of ConversionKind, MethodSymbol))
Public ConversionsBackOpt As ImmutableArray(Of KeyValuePair(Of ConversionKind, MethodSymbol))
' When this is null, it means that there aren't any optional arguments
' This array is indexed by parameter index, not the argument index.
Public OptionalArguments As ImmutableArray(Of OptionalArgument)
Public ReadOnly Property UsedOptionalParameterDefaultValue As Boolean
Get
Return Not OptionalArguments.IsDefault
End Get
End Property
Public NotInferredTypeArguments As BitVector
Public TypeArgumentInferenceDiagnosticsOpt As BindingDiagnosticBag
Public Sub New(candidate As Candidate, state As CandidateAnalysisResultState)
Me.Candidate = candidate
Me.State = state
End Sub
Public Sub New(candidate As Candidate)
Me.Candidate = candidate
Me.State = CandidateAnalysisResultState.Applicable
End Sub
End Structure
' Represents a simple overload resolution result
Friend Structure OverloadResolutionResult
Private ReadOnly _bestResult As CandidateAnalysisResult?
Private ReadOnly _allResults As ImmutableArray(Of CandidateAnalysisResult)
Private ReadOnly _resolutionIsLateBound As Boolean
Private ReadOnly _remainingCandidatesRequireNarrowingConversion As Boolean
Public ReadOnly AsyncLambdaSubToFunctionMismatch As ImmutableArray(Of BoundExpression)
' Create an overload resolution result from a full set of results.
Public Sub New(allResults As ImmutableArray(Of CandidateAnalysisResult), resolutionIsLateBound As Boolean,
remainingCandidatesRequireNarrowingConversion As Boolean,
asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression))
Me._allResults = allResults
Me._resolutionIsLateBound = resolutionIsLateBound
Me._remainingCandidatesRequireNarrowingConversion = remainingCandidatesRequireNarrowingConversion
Me.AsyncLambdaSubToFunctionMismatch = If(asyncLambdaSubToFunctionMismatch Is Nothing,
ImmutableArray(Of BoundExpression).Empty,
asyncLambdaSubToFunctionMismatch.ToArray().AsImmutableOrNull())
If Not resolutionIsLateBound Then
Me._bestResult = GetBestResult(allResults)
End If
End Sub
Public ReadOnly Property Candidates As ImmutableArray(Of CandidateAnalysisResult)
Get
Return _allResults
End Get
End Property
' Returns the best method. Note that if overload resolution succeeded, the set of conversion kinds will NOT be returned.
Public ReadOnly Property BestResult As CandidateAnalysisResult?
Get
Return _bestResult
End Get
End Property
Public ReadOnly Property ResolutionIsLateBound As Boolean
Get
Return _resolutionIsLateBound
End Get
End Property
''' <summary>
''' This might simplify error reporting. If not, consider getting rid of this property.
''' </summary>
Public ReadOnly Property RemainingCandidatesRequireNarrowingConversion As Boolean
Get
Return _remainingCandidatesRequireNarrowingConversion
End Get
End Property
Private Shared Function GetBestResult(allResults As ImmutableArray(Of CandidateAnalysisResult)) As CandidateAnalysisResult?
Dim best As CandidateAnalysisResult? = Nothing
Dim i As Integer = 0
While i < allResults.Length
Dim current = allResults(i)
If current.State = CandidateAnalysisResultState.Applicable Then
If best IsNot Nothing Then
Return Nothing
End If
best = current
End If
i = i + 1
End While
Return best
End Function
End Structure
''' <summary>
''' Perform overload resolution on the given method or property group, with the given arguments and names.
''' The names can be null if no names were supplied to any arguments.
''' </summary>
Public Shared Function MethodOrPropertyInvocationOverloadResolution(
group As BoundMethodOrPropertyGroup,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
callerInfoOpt As SyntaxNode,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional includeEliminatedCandidates As Boolean = False,
Optional forceExpandedForm As Boolean = False
) As OverloadResolutionResult
If group.Kind = BoundKind.MethodGroup Then
Dim methodGroup = DirectCast(group, BoundMethodGroup)
Return MethodInvocationOverloadResolution(
methodGroup,
arguments,
argumentNames,
binder,
callerInfoOpt,
useSiteInfo,
includeEliminatedCandidates,
forceExpandedForm:=forceExpandedForm)
Else
Dim propertyGroup = DirectCast(group, BoundPropertyGroup)
Return PropertyInvocationOverloadResolution(
propertyGroup,
arguments,
argumentNames,
binder,
callerInfoOpt,
useSiteInfo,
includeEliminatedCandidates)
End If
End Function
''' <summary>
''' Perform overload resolution on the given method group, with the given arguments.
''' </summary>
Public Shared Function QueryOperatorInvocationOverloadResolution(
methodGroup As BoundMethodGroup,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional includeEliminatedCandidates As Boolean = False
) As OverloadResolutionResult
Return MethodInvocationOverloadResolution(
methodGroup,
arguments,
Nothing,
binder,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo,
includeEliminatedCandidates:=includeEliminatedCandidates,
lateBindingIsAllowed:=False,
isQueryOperatorInvocation:=True)
End Function
''' <summary>
''' Perform overload resolution on the given method group, with the given arguments and names.
''' The names can be null if no names were supplied to any arguments.
''' </summary>
Public Shared Function MethodInvocationOverloadResolution(
methodGroup As BoundMethodGroup,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
callerInfoOpt As SyntaxNode,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional includeEliminatedCandidates As Boolean = False,
Optional delegateReturnType As TypeSymbol = Nothing,
Optional delegateReturnTypeReferenceBoundNode As BoundNode = Nothing,
Optional lateBindingIsAllowed As Boolean = True,
Optional isQueryOperatorInvocation As Boolean = False,
Optional forceExpandedForm As Boolean = False
) As OverloadResolutionResult
Debug.Assert(methodGroup.ResultKind = LookupResultKind.Good OrElse methodGroup.ResultKind = LookupResultKind.Inaccessible)
Dim typeArguments = If(methodGroup.TypeArgumentsOpt IsNot Nothing, methodGroup.TypeArgumentsOpt.Arguments, ImmutableArray(Of TypeSymbol).Empty)
' To simplify code later
If typeArguments.IsDefault Then
typeArguments = ImmutableArray(Of TypeSymbol).Empty
End If
If arguments.IsDefault Then
arguments = ImmutableArray(Of BoundExpression).Empty
End If
Dim candidates = ArrayBuilder(Of CandidateAnalysisResult).GetInstance()
Dim instanceCandidates As ArrayBuilder(Of Candidate) = ArrayBuilder(Of Candidate).GetInstance()
Dim curriedCandidates As ArrayBuilder(Of Candidate) = ArrayBuilder(Of Candidate).GetInstance()
Dim methods As ImmutableArray(Of MethodSymbol) = methodGroup.Methods
If Not methods.IsDefault Then
' Create MethodCandidates for ordinary methods and ExtensionMethodCandidates
' for curried methods, separating them.
For Each method As MethodSymbol In methods
If method.ReducedFrom Is Nothing Then
instanceCandidates.Add(New MethodCandidate(method))
Else
curriedCandidates.Add(New ExtensionMethodCandidate(method))
End If
Next
End If
Dim asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) = Nothing
Dim applicableNarrowingCandidateCount As Integer = 0
Dim applicableInstanceCandidateCount As Integer = 0
' First collect instance methods.
If instanceCandidates.Count > 0 Then
CollectOverloadedCandidates(
binder, candidates, instanceCandidates, typeArguments,
arguments, argumentNames, delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, isQueryOperatorInvocation, forceExpandedForm, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
applicableInstanceCandidateCount = EliminateNotApplicableToArguments(methodGroup, candidates, arguments, argumentNames, binder,
applicableNarrowingCandidateCount, asyncLambdaSubToFunctionMismatch,
callerInfoOpt,
forceExpandedForm,
useSiteInfo)
End If
instanceCandidates.Free()
instanceCandidates = Nothing
' Now add extension methods if they should be considered.
Dim addedExtensionMethods As Boolean = False
If ShouldConsiderExtensionMethods(candidates) Then
' Request additional extension methods, if any available.
If methodGroup.ResultKind = LookupResultKind.Good Then
methods = methodGroup.AdditionalExtensionMethods(useSiteInfo)
For Each method As MethodSymbol In methods
curriedCandidates.Add(New ExtensionMethodCandidate(method))
Next
End If
If curriedCandidates.Count > 0 Then
addedExtensionMethods = True
CollectOverloadedCandidates(
binder, candidates, curriedCandidates, typeArguments,
arguments, argumentNames, delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, isQueryOperatorInvocation, forceExpandedForm, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
End If
End If
curriedCandidates.Free()
Dim result As OverloadResolutionResult
If applicableInstanceCandidateCount = 0 AndAlso Not addedExtensionMethods Then
result = ReportOverloadResolutionFailedOrLateBound(candidates, applicableInstanceCandidateCount, lateBindingIsAllowed AndAlso binder.OptionStrict <> OptionStrict.On, asyncLambdaSubToFunctionMismatch)
Else
result = ResolveOverloading(methodGroup, candidates, arguments, argumentNames, delegateReturnType, lateBindingIsAllowed, binder, asyncLambdaSubToFunctionMismatch, callerInfoOpt, forceExpandedForm,
useSiteInfo)
End If
candidates.Free()
Return result
End Function
Private Shared Function ReportOverloadResolutionFailedOrLateBound(candidates As ArrayBuilder(Of CandidateAnalysisResult),
applicableNarrowingCandidateCount As Integer,
lateBindingIsAllowed As Boolean,
asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression)) As OverloadResolutionResult
Dim isLateBound As Boolean = False
If lateBindingIsAllowed Then
For Each candidate In candidates
If candidate.State = CandidateAnalysisResultState.TypeInferenceFailed Then
If candidate.AllFailedInferenceIsDueToObject AndAlso Not candidate.Candidate.IsExtensionMethod Then
isLateBound = True
Exit For
End If
End If
Next
End If
Return New OverloadResolutionResult(candidates.ToImmutable, isLateBound, applicableNarrowingCandidateCount > 0, asyncLambdaSubToFunctionMismatch)
End Function
''' <summary>
''' Perform overload resolution on the given array of property symbols.
''' </summary>
Public Shared Function PropertyInvocationOverloadResolution(
propertyGroup As BoundPropertyGroup,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
callerInfoOpt As SyntaxNode,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional includeEliminatedCandidates As Boolean = False
) As OverloadResolutionResult
Debug.Assert(propertyGroup.ResultKind = LookupResultKind.Good OrElse propertyGroup.ResultKind = LookupResultKind.Inaccessible)
Dim properties As ImmutableArray(Of PropertySymbol) = propertyGroup.Properties
' To simplify code later
If arguments.IsDefault Then
arguments = ImmutableArray(Of BoundExpression).Empty
End If
Dim results = ArrayBuilder(Of CandidateAnalysisResult).GetInstance()
Dim candidates = ArrayBuilder(Of Candidate).GetInstance(properties.Length - 1)
For i As Integer = 0 To properties.Length - 1 Step 1
candidates.Add(New PropertyCandidate(properties(i)))
Next
Dim asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) = Nothing
CollectOverloadedCandidates(binder, results, candidates, ImmutableArray(Of TypeSymbol).Empty,
arguments, argumentNames, Nothing, Nothing, includeEliminatedCandidates,
isQueryOperatorInvocation:=False, forceExpandedForm:=False, asyncLambdaSubToFunctionMismatch:=asyncLambdaSubToFunctionMismatch,
useSiteInfo:=useSiteInfo)
Debug.Assert(asyncLambdaSubToFunctionMismatch Is Nothing)
candidates.Free()
Dim result = ResolveOverloading(propertyGroup, results, arguments, argumentNames, delegateReturnType:=Nothing, lateBindingIsAllowed:=True, binder:=binder,
asyncLambdaSubToFunctionMismatch:=asyncLambdaSubToFunctionMismatch, callerInfoOpt:=callerInfoOpt, forceExpandedForm:=False,
useSiteInfo:=useSiteInfo)
results.Free()
Return result
End Function
''' <summary>
''' Given instance method candidates gone through applicability analysis,
''' figure out if we should consider extension methods, if any.
''' </summary>
Private Shared Function ShouldConsiderExtensionMethods(
candidates As ArrayBuilder(Of CandidateAnalysisResult)
) As Boolean
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim candidate = candidates(i)
Debug.Assert(Not candidate.Candidate.IsExtensionMethod)
If candidate.IgnoreExtensionMethods Then
Return False
End If
Next
Return True
End Function
Private Shared Function ResolveOverloading(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
lateBindingIsAllowed As Boolean,
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
callerInfoOpt As SyntaxNode,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As OverloadResolutionResult
Debug.Assert(argumentNames.IsDefault OrElse argumentNames.Length = arguments.Length)
Dim applicableCandidates As Integer
Dim resolutionIsLateBound As Boolean = False
Dim narrowingCandidatesRemainInTheSet As Boolean = False
Dim applicableNarrowingCandidates As Integer = 0
'TODO: Where does this fit?
'Semantics::ResolveOverloading
'// See if type inference failed for all candidates and it failed from
'// Object. For this scenario, in non-strict mode, treat the call
'// as latebound.
'§11.8.1 Overloaded Method Resolution
'2. Next, eliminate all members from the set that are inaccessible or not applicable to the argument list.
' Note, similar to Dev10 compiler this process will eliminate candidates requiring narrowing conversions
' if strict semantics is used, exception are candidates that require narrowing only from numeric constants.
applicableCandidates = EliminateNotApplicableToArguments(methodOrPropertyGroup, candidates, arguments, argumentNames, binder,
applicableNarrowingCandidates, asyncLambdaSubToFunctionMismatch,
callerInfoOpt,
forceExpandedForm,
useSiteInfo)
If applicableCandidates < 2 Then
narrowingCandidatesRemainInTheSet = (applicableNarrowingCandidates > 0)
GoTo ResolutionComplete
End If
' §11.8.1 Overloaded Method Resolution.
' 7.8. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
' delegate types in M match exactly, but not all do in N, eliminate N from the set.
' 7.9. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
' delegate types in M are widening conversions, but not all are in N, eliminate N from the set.
'
' The spec implies that this rule is applied to the set of most applicable candidate as one of the tie breaking rules.
' However, doing it there wouldn't have any effect because all candidates in the set of most applicable candidates
' are equally applicable, therefore, have the same types for corresponding parameters. Thus all the candidates
' have exactly the same delegate relaxation level and none would be eliminated.
' Dev10 applies this rule much earlier, even before eliminating narrowing candidates, and it does it across the board.
' I am going to do the same.
applicableCandidates = ShadowBasedOnDelegateRelaxation(candidates, applicableNarrowingCandidates)
If applicableCandidates < 2 Then
narrowingCandidatesRemainInTheSet = (applicableNarrowingCandidates > 0)
GoTo ResolutionComplete
End If
' §11.8.1 Overloaded Method Resolution.
'7.7. If M and N both required type inference to produce type arguments, and M did not
' require determining the dominant type for any of its type arguments (i.e. each the
' type arguments inferred to a single type), but N did, eliminate N from the set.
' Despite what the spec says, this rule is applied after shadowing based on delegate relaxation
' level, however it needs other tie breaking rules applied to equally applicable candidates prior
' to figuring out the minimal inference level to use as the filter.
ShadowBasedOnInferenceLevel(candidates, arguments, Not argumentNames.IsDefault, delegateReturnType, binder,
applicableCandidates, applicableNarrowingCandidates, useSiteInfo)
If applicableCandidates < 2 Then
narrowingCandidatesRemainInTheSet = (applicableNarrowingCandidates > 0)
GoTo ResolutionComplete
End If
'3. Next, eliminate all members from the set that require narrowing conversions
' to be applicable to the argument list, except for the case where the argument
' expression type is Object.
'4. Next, eliminate all remaining members from the set that require narrowing coercions
' to be applicable to the argument list. If the set is empty, the type containing the
' method group is not an interface, and strict semantics are not being used, the
' invocation target expression is reclassified as a late-bound method access.
' Otherwise, the normal rules apply.
If applicableCandidates = applicableNarrowingCandidates Then
' All remaining candidates are narrowing, deal with them.
narrowingCandidatesRemainInTheSet = True
applicableCandidates = AnalyzeNarrowingCandidates(candidates, arguments, delegateReturnType,
lateBindingIsAllowed AndAlso binder.OptionStrict <> OptionStrict.On, binder,
resolutionIsLateBound,
useSiteInfo)
Else
If applicableNarrowingCandidates > 0 Then
Debug.Assert(applicableNarrowingCandidates < applicableCandidates)
applicableCandidates = EliminateNarrowingCandidates(candidates)
Debug.Assert(applicableCandidates > 0)
If applicableCandidates < 2 Then
GoTo ResolutionComplete
End If
End If
'5. Next, if any instance methods remain in the set,
' eliminate all extension methods from the set.
' !!! I don't think we need to do this explicitly. ResolveMethodOverloading doesn't add
' !!! extension methods in the list if we need to remove them here.
'applicableCandidates = EliminateExtensionMethodsInPresenceOfInstanceMethods(candidates)
'If applicableCandidates < 2 Then
' GoTo ResolutionComplete
'End If
'6. Next, if, given any two members of the set, M and N, M is more applicable than N
' to the argument list, eliminate N from the set. If more than one member remains
' in the set and the remaining members are not equally applicable to the argument
' list, a compile-time error results.
'7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
applicableCandidates = EliminateLessApplicableToTheArguments(candidates, arguments, delegateReturnType,
False, ' appliedTieBreakingRules
binder, useSiteInfo)
End If
ResolutionComplete:
If Not resolutionIsLateBound AndAlso applicableCandidates = 0 Then
Return ReportOverloadResolutionFailedOrLateBound(candidates, applicableCandidates, lateBindingIsAllowed AndAlso binder.OptionStrict <> OptionStrict.On, asyncLambdaSubToFunctionMismatch)
End If
Return New OverloadResolutionResult(candidates.ToImmutable(), resolutionIsLateBound, narrowingCandidatesRemainInTheSet, asyncLambdaSubToFunctionMismatch)
End Function
Private Shared Function EliminateNarrowingCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult)
) As Integer
Dim applicableCandidates As Integer = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
If current.RequiresNarrowingConversion Then
current.State = CandidateAnalysisResultState.RequiresNarrowing
candidates(i) = current
Else
applicableCandidates += 1
End If
End If
Next
Return applicableCandidates
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 6. Next, if, given any two members of the set, M and N, M is more applicable than N
''' to the argument list, eliminate N from the set. If more than one member remains
''' in the set and the remaining members are not equally applicable to the argument
''' list, a compile-time error results.
''' 7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
'''
''' Returns amount of applicable candidates left.
'''
''' Note that less applicable candidates are going to be eliminated if and only if there are most applicable
''' candidates.
''' </summary>
Private Shared Function EliminateLessApplicableToTheArguments(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
appliedTieBreakingRules As Boolean,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional mostApplicableMustNarrowOnlyFromNumericConstants As Boolean = False
) As Integer
Dim applicableCandidates As Integer
Dim indexesOfEqualMostApplicableCandidates As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance()
If FastFindMostApplicableCandidates(candidates, arguments, indexesOfEqualMostApplicableCandidates, binder, useSiteInfo) AndAlso
(mostApplicableMustNarrowOnlyFromNumericConstants = False OrElse
candidates(indexesOfEqualMostApplicableCandidates(0)).RequiresNarrowingNotFromNumericConstant = False OrElse
indexesOfEqualMostApplicableCandidates.Count = CountApplicableCandidates(candidates)) Then
' We have most applicable candidates.
' Mark those that lost applicability comparison.
' Applicable candidates with indexes before the first value in indexesOfEqualMostApplicableCandidates,
' after the last value in indexesOfEqualMostApplicableCandidates and in between consecutive values in
' indexesOfEqualMostApplicableCandidates are less applicable.
Debug.Assert(indexesOfEqualMostApplicableCandidates.Count > 0)
Dim nextMostApplicable As Integer = 0 ' and index into indexesOfEqualMostApplicableCandidates
Dim indexOfNextMostApplicable As Integer = indexesOfEqualMostApplicableCandidates(nextMostApplicable)
For i As Integer = 0 To candidates.Count - 1 Step 1
If i = indexOfNextMostApplicable Then
nextMostApplicable += 1
If nextMostApplicable < indexesOfEqualMostApplicableCandidates.Count Then
indexOfNextMostApplicable = indexesOfEqualMostApplicableCandidates(nextMostApplicable)
Else
indexOfNextMostApplicable = candidates.Count
End If
Continue For
End If
Dim contender As CandidateAnalysisResult = candidates(i)
If contender.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
contender.State = CandidateAnalysisResultState.LessApplicable
candidates(i) = contender
Next
' Apply tie-breaking rules
If Not appliedTieBreakingRules Then
applicableCandidates = ApplyTieBreakingRules(candidates, indexesOfEqualMostApplicableCandidates, arguments, delegateReturnType, binder, useSiteInfo)
Else
applicableCandidates = indexesOfEqualMostApplicableCandidates.Count
End If
ElseIf Not appliedTieBreakingRules Then
' Overload resolution failed, we couldn't find most applicable candidates.
' We still need to apply shadowing rules to the sets of equally applicable candidates,
' this will provide better error reporting experience. As we are doing this, we will redo
' applicability comparisons that we've done earlier in FastFindMostApplicableCandidates, but we are willing to
' pay the price for erroneous code.
applicableCandidates = ApplyTieBreakingRulesToEquallyApplicableCandidates(candidates, arguments, delegateReturnType, binder, useSiteInfo)
Else
applicableCandidates = CountApplicableCandidates(candidates)
End If
indexesOfEqualMostApplicableCandidates.Free()
Return applicableCandidates
End Function
Private Shared Function CountApplicableCandidates(candidates As ArrayBuilder(Of CandidateAnalysisResult)) As Integer
Dim applicableCandidates As Integer = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
If candidates(i).State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
applicableCandidates += 1
Next
Return applicableCandidates
End Function
''' <summary>
''' Returns amount of applicable candidates left.
''' </summary>
Private Shared Function ApplyTieBreakingRulesToEquallyApplicableCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Integer
' First, let's break all remaining candidates into buckets of equally applicable candidates
Dim buckets = GroupEquallyApplicableCandidates(candidates, arguments, binder)
Debug.Assert(buckets.Count > 0)
Dim applicableCandidates As Integer = 0
' Apply tie-breaking rules
For i As Integer = 0 To buckets.Count - 1 Step 1
applicableCandidates += ApplyTieBreakingRules(candidates, buckets(i), arguments, delegateReturnType, binder, useSiteInfo)
Next
' Release memory we no longer need.
For i As Integer = 0 To buckets.Count - 1 Step 1
buckets(i).Free()
Next
buckets.Free()
Return applicableCandidates
End Function
''' <summary>
''' Returns True if there are most applicable candidates.
'''
''' indexesOfMostApplicableCandidates will contain indexes of equally applicable candidates, which are most applicable
''' by comparison to the other (non-equal) candidates. The indexes will be in ascending order.
''' </summary>
Private Shared Function FastFindMostApplicableCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
indexesOfMostApplicableCandidates As ArrayBuilder(Of Integer),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
Dim mightBeTheMostApplicableIndex As Integer = -1
Dim mightBeTheMostApplicable As CandidateAnalysisResult = Nothing
indexesOfMostApplicableCandidates.Clear()
' Use linear complexity algorithm to find the first most applicable candidate.
' We are saying "the first" because there could be a number of candidates equally applicable
' by comparison to the one we find, their indexes are collected in indexesOfMostApplicableCandidates.
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim contender As CandidateAnalysisResult = candidates(i)
If contender.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
If mightBeTheMostApplicableIndex = -1 Then
mightBeTheMostApplicableIndex = i
mightBeTheMostApplicable = contender
indexesOfMostApplicableCandidates.Add(i)
Else
Dim cmp As ApplicabilityComparisonResult = CompareApplicabilityToTheArguments(mightBeTheMostApplicable, contender, arguments, binder, useSiteInfo)
If cmp = ApplicabilityComparisonResult.RightIsMoreApplicable Then
mightBeTheMostApplicableIndex = i
mightBeTheMostApplicable = contender
indexesOfMostApplicableCandidates.Clear()
indexesOfMostApplicableCandidates.Add(i)
ElseIf cmp = ApplicabilityComparisonResult.Undefined Then
mightBeTheMostApplicableIndex = -1
indexesOfMostApplicableCandidates.Clear()
ElseIf cmp = ApplicabilityComparisonResult.EquallyApplicable Then
indexesOfMostApplicableCandidates.Add(i)
Else
Debug.Assert(cmp = ApplicabilityComparisonResult.LeftIsMoreApplicable)
End If
End If
Next
For i As Integer = 0 To mightBeTheMostApplicableIndex - 1 Step 1
Dim contender As CandidateAnalysisResult = candidates(i)
If contender.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
Dim cmp As ApplicabilityComparisonResult = CompareApplicabilityToTheArguments(mightBeTheMostApplicable, contender, arguments, binder, useSiteInfo)
If cmp = ApplicabilityComparisonResult.RightIsMoreApplicable OrElse
cmp = ApplicabilityComparisonResult.Undefined OrElse
cmp = ApplicabilityComparisonResult.EquallyApplicable Then
' We do this for equal applicability too because this contender was dropped during the first loop, so,
' if we continue, the mightBeTheMostApplicable candidate will be definitely dropped too.
mightBeTheMostApplicableIndex = -1
Exit For
Else
Debug.Assert(cmp = ApplicabilityComparisonResult.LeftIsMoreApplicable)
End If
Next
Return (mightBeTheMostApplicableIndex > -1)
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
''' </summary>
Private Shared Function ApplyTieBreakingRules(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
bucket As ArrayBuilder(Of Integer),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Integer
Dim leftWins As Boolean
Dim rightWins As Boolean
Dim applicableCandidates As Integer = bucket.Count
For i = 0 To bucket.Count - 1 Step 1
Dim left = candidates(bucket(i))
If left.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
For j = i + 1 To bucket.Count - 1 Step 1
Dim right = candidates(bucket(j))
If right.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
If ShadowBasedOnTieBreakingRules(left, right, arguments, delegateReturnType, leftWins, rightWins, binder, useSiteInfo) Then
Debug.Assert(Not (leftWins AndAlso rightWins))
If leftWins Then
right.State = CandidateAnalysisResultState.Shadowed
candidates(bucket(j)) = right
applicableCandidates -= 1
Else
Debug.Assert(rightWins)
left.State = CandidateAnalysisResultState.Shadowed
candidates(bucket(i)) = left
applicableCandidates -= 1
Exit For
End If
End If
Next
Next
Debug.Assert(applicableCandidates >= 0)
Return applicableCandidates
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 7. Otherwise, given any two members of the set, M and N, apply the following tie-breaking rules, in order.
''' </summary>
Private Shared Function ShadowBasedOnTieBreakingRules(
left As CandidateAnalysisResult,
right As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
ByRef leftWins As Boolean,
ByRef rightWins As Boolean,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
' Let's apply various shadowing and tie-breaking rules
' from section 7 of §11.8.1 Overloaded Method Resolution.
leftWins = False
rightWins = False
'• If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
If ShadowBasedOnParamArrayUsage(left, right, leftWins, rightWins) Then
Return True
End If
'7.1. If M is defined in a more derived type than N, eliminate N from the set.
' This rule also applies to the types that extension methods are defined on.
'7.2. If M and N are extension methods and the target type of M is a class or
' structure and the target type of N is an interface, eliminate N from the set.
If ShadowBasedOnReceiverType(left, right, leftWins, rightWins, useSiteInfo) Then
Return True ' I believe we can get here only in presence of named arguments and optional parameters. Otherwise, CombineCandidates takes care of this shadowing.
End If
'7.3. If M and N are extension methods and the target type of M has fewer type
' parameters than the target type of N, eliminate N from the set.
' !!! Note that spec talks about "fewer type parameters", but it is not really about count.
' !!! It is about one refers to a type parameter and the other one doesn't.
If ShadowBasedOnExtensionMethodTargetTypeGenericity(left, right, leftWins, rightWins) Then
Return True ' I believe we can get here only in presence of named arguments and optional parameters. Otherwise, CombineCandidates takes care of this shadowing.
End If
'7.4. If M is less generic than N, eliminate N from the set.
If ShadowBasedOnGenericity(left, right, leftWins, rightWins, arguments, binder) Then
Return True
End If
'7.5. If M is not an extension method and N is, eliminate N from the set.
'7.6. If M and N are extension methods and M was found before N, eliminate N from the set.
If ShadowBasedOnExtensionVsInstanceAndPrecedence(left, right, leftWins, rightWins) Then
Return True
End If
'7.7. If M and N both required type inference to produce type arguments, and M did not
' require determining the dominant type for any of its type arguments (i.e. each the
' type arguments inferred to a single type), but N did, eliminate N from the set.
' The spec is incorrect, this shadowing doesn't belong here, it is applied across the board
' after these tie breaking rules. For more information, see comment in ResolveOverloading.
'7.8. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding delegate types in M match exactly, but not all do in N, eliminate N from the set.
'7.9. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding delegate types in M are widening conversions, but not all are in N, eliminate N from the set.
' The spec is incorrect, this shadowing doesn't belong here, it is applied much earlier.
' For more information, see comment in ResolveOverloading.
' 7.9. If M did not use any optional parameter defaults in place of explicit
' arguments, but N did, then eliminate N from the set.
'
' !!!WARNING!!! The index (7.9) is based on "VB11 spec [draft 3]" version of documentation rather
' than Dev10 documentation.
If ShadowBasedOnOptionalParametersDefaultsUsed(left, right, leftWins, rightWins) Then
Return True
End If
'7.10. If the overload resolution is being done to resolve the target of a delegate-creation expression from an AddressOf expression and M is a function, while N is a subroutine, eliminate N from the set.
If ShadowBasedOnSubOrFunction(left, right, delegateReturnType, leftWins, rightWins) Then
Return True
End If
' 7.10. Before type arguments have been substituted, if M has greater depth of
' genericity (Section 11.8.1.3) than N, then eliminate N from the set.
'
' !!!WARNING!!! The index (7.10) is based on "VB11 spec [draft 3]" version of documentation
' rather than Dev10 documentation.
'
' NOTE: Dev11 puts this analysis in a second phase with the first phase
' performing analysis of { $11.8.1:6 + 7.9/7.10/7.11/7.8 }, see comments in
' OverloadResolution.cpp: bool Semantics::AreProceduresEquallySpecific(...)
'
' Placing this analysis here seems to be more natural than
' matching Dev11 implementation
If ShadowBasedOnDepthOfGenericity(left, right, leftWins, rightWins, arguments, binder) Then
Return True
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.10. If the overload resolution is being done to resolve the target of a
''' delegate-creation expression from an AddressOf expression and M is a
''' function, while N is a subroutine, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnSubOrFunction(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
delegateReturnType As TypeSymbol,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
' !!! Actually, the spec isn't accurate here. If the target delegate is a Sub, we prefer a Sub. !!!
' !!! If the target delegate is a Function, we prefer a Function. !!!
If delegateReturnType Is Nothing Then
Return False
End If
Dim leftReturnsVoid As Boolean = left.Candidate.ReturnType.IsVoidType()
Dim rightReturnsVoid As Boolean = right.Candidate.ReturnType.IsVoidType()
If leftReturnsVoid = rightReturnsVoid Then
Return False
End If
If delegateReturnType.IsVoidType() = leftReturnsVoid Then
leftWins = True
Return True
End If
Debug.Assert(delegateReturnType.IsVoidType() = rightReturnsVoid)
rightWins = True
Return True
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.8. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
''' delegate types in M match exactly, but not all do in N, eliminate N from the set.
''' 7.9. If one or more arguments are AddressOf or lambda expressions, and all of the corresponding
''' delegate types in M are widening conversions, but not all are in N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnDelegateRelaxation(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
ByRef applicableNarrowingCandidates As Integer
) As Integer
' Find the minimal MaxDelegateRelaxationLevel
Dim minMaxRelaxation As ConversionKind = ConversionKind.DelegateRelaxationLevelInvalid
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
Dim relaxation As ConversionKind = current.MaxDelegateRelaxationLevel
If relaxation < minMaxRelaxation Then
minMaxRelaxation = relaxation
End If
End If
Next
' Now eliminate all candidates with relaxation level bigger than the minimal.
Dim applicableCandidates As Integer = 0
applicableNarrowingCandidates = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
Dim relaxation As ConversionKind = current.MaxDelegateRelaxationLevel
If relaxation > minMaxRelaxation Then
current.State = CandidateAnalysisResultState.Shadowed
candidates(i) = current
Else
applicableCandidates += 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates += 1
End If
End If
Next
Return applicableCandidates
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.9. If M did not use any optional parameter defaults in place of explicit
''' arguments, but N did, then eliminate N from the set.
'''
''' !!!WARNING!!! The index (7.9) is based on "VB11 spec [draft 3]" version of documentation rather
''' than Dev10 documentation.
''' TODO: Update indexes of other overload method resolution rules
''' </summary>
Private Shared Function ShadowBasedOnOptionalParametersDefaultsUsed(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
Dim leftUsesOptionalParameterDefaults As Boolean = left.UsedOptionalParameterDefaultValue
If leftUsesOptionalParameterDefaults = right.UsedOptionalParameterDefaultValue Then
Return False ' No winner
End If
If Not leftUsesOptionalParameterDefaults Then
leftWins = True
Else
rightWins = True
End If
Return True
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.7. If M and N both required type inference to produce type arguments, and M did not
''' require determining the dominant type for any of its type arguments (i.e. each the
''' type arguments inferred to a single type), but N did, eliminate N from the set.
''' </summary>
Private Shared Sub ShadowBasedOnInferenceLevel(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
haveNamedArguments As Boolean,
delegateReturnType As TypeSymbol,
binder As Binder,
ByRef applicableCandidates As Integer,
ByRef applicableNarrowingCandidates As Integer,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(Not haveNamedArguments OrElse Not candidates(0).Candidate.IsOperator)
' See if there are candidates with different InferenceLevel
Dim haveDifferentInferenceLevel As Boolean = False
Dim theOnlyInferenceLevel As TypeArgumentInference.InferenceLevel = CType(Byte.MaxValue, TypeArgumentInference.InferenceLevel)
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = current.InferenceLevel
If theOnlyInferenceLevel = Byte.MaxValue Then
theOnlyInferenceLevel = inferenceLevel
ElseIf inferenceLevel <> theOnlyInferenceLevel Then
haveDifferentInferenceLevel = True
Exit For
End If
End If
Next
If Not haveDifferentInferenceLevel Then
' Nothing to do.
Return
End If
' Native compiler used to have a bug where CombineCandidates was applying shadowing in presence of named arguments
' before figuring out whether candidates are applicable. We fixed that. However, in cases when candidates were applicable
' after all, that shadowing had impact on the shadowing based on the inference level by affecting minimal inference level.
' To compensate, we will perform the CombineCandidates-style shadowing here. Note that we cannot simply call
' ApplyTieBreakingRulesToEquallyApplicableCandidates to do this because shadowing performed by CombineCandidates is more
' constrained.
If haveNamedArguments Then
Debug.Assert(Not candidates(0).Candidate.IsOperator)
Dim indexesOfApplicableCandidates = ArrayBuilder(Of Integer).GetInstance(applicableCandidates)
For i As Integer = 0 To candidates.Count - 1 Step 1
If candidates(i).State = CandidateAnalysisResultState.Applicable Then
indexesOfApplicableCandidates.Add(i)
End If
Next
Debug.Assert(indexesOfApplicableCandidates.Count = applicableCandidates)
' Sort indexes by inference level
indexesOfApplicableCandidates.Sort(New InferenceLevelComparer(candidates))
#If DEBUG Then
Dim level As TypeArgumentInference.InferenceLevel = TypeArgumentInference.InferenceLevel.None
For Each index As Integer In indexesOfApplicableCandidates
Debug.Assert(level <= candidates(index).InferenceLevel)
level = candidates(index).InferenceLevel
Next
#End If
' In order of sorted indexes, apply constrained shadowing rules looking for the first one survived.
' This will be sufficient to calculate "correct" minimal inference level. We don't have to apply
' shadowing to each pair of candidates.
For i As Integer = 0 To indexesOfApplicableCandidates.Count - 2
Dim left As CandidateAnalysisResult = candidates(indexesOfApplicableCandidates(i))
If left.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
For j As Integer = i + 1 To indexesOfApplicableCandidates.Count - 1
Dim right As CandidateAnalysisResult = candidates(indexesOfApplicableCandidates(j))
If right.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
' Shadowing is applied only to candidates that have the same types for corresponding parameters
' in virtual signatures
Dim equallyApplicable As Boolean = True
For k = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(k))
Dim rightParamType As TypeSymbol = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(k))
If Not leftParamType.IsSameTypeIgnoringAll(rightParamType) Then
' Signatures are different, shadowing rules do not apply
equallyApplicable = False
Exit For
End If
Next
If Not equallyApplicable Then
Continue For
End If
Dim signatureMatch As Boolean = True
' Compare complete signature, with no regard to arguments
If left.Candidate.ParameterCount <> right.Candidate.ParameterCount Then
signatureMatch = False
Else
For k As Integer = 0 To left.Candidate.ParameterCount - 1 Step 1
Dim leftType As TypeSymbol = left.Candidate.Parameters(k).Type
Dim rightType As TypeSymbol = right.Candidate.Parameters(k).Type
If Not leftType.IsSameTypeIgnoringAll(rightType) Then
signatureMatch = False
Exit For
End If
Next
End If
Dim leftWins As Boolean = False
Dim rightWins As Boolean = False
If (Not signatureMatch AndAlso ShadowBasedOnParamArrayUsage(left, right, leftWins, rightWins)) OrElse
ShadowBasedOnReceiverType(left, right, leftWins, rightWins, useSiteInfo) OrElse
ShadowBasedOnExtensionMethodTargetTypeGenericity(left, right, leftWins, rightWins) Then
Debug.Assert(leftWins Xor rightWins)
If leftWins Then
right.State = CandidateAnalysisResultState.Shadowed
candidates(indexesOfApplicableCandidates(j)) = right
ElseIf rightWins Then
left.State = CandidateAnalysisResultState.Shadowed
candidates(indexesOfApplicableCandidates(i)) = left
Exit For ' advance to the next left
End If
End If
Next
If left.State = CandidateAnalysisResultState.Applicable Then
' left has survived
Exit For
End If
Next
End If
' Find the minimal InferenceLevel
Dim minInferenceLevel = TypeArgumentInference.InferenceLevel.Invalid
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = current.InferenceLevel
If inferenceLevel < minInferenceLevel Then
minInferenceLevel = inferenceLevel
End If
End If
Next
' Now eliminate all candidates with inference level bigger than the minimal.
applicableCandidates = 0
applicableNarrowingCandidates = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = current.InferenceLevel
If inferenceLevel > minInferenceLevel Then
current.State = CandidateAnalysisResultState.Shadowed
candidates(i) = current
Else
applicableCandidates += 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates += 1
End If
End If
Next
' Done.
End Sub
Private Class InferenceLevelComparer
Implements IComparer(Of Integer)
Private ReadOnly _candidates As ArrayBuilder(Of CandidateAnalysisResult)
Public Sub New(candidates As ArrayBuilder(Of CandidateAnalysisResult))
_candidates = candidates
End Sub
Public Function Compare(indexX As Integer, indexY As Integer) As Integer Implements IComparer(Of Integer).Compare
Return CInt(_candidates(indexX).InferenceLevel).CompareTo(_candidates(indexY).InferenceLevel)
End Function
End Class
''' <summary>
''' §11.8.1.1 Applicability
''' </summary>
Private Shared Function CompareApplicabilityToTheArguments(
ByRef left As CandidateAnalysisResult,
ByRef right As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As ApplicabilityComparisonResult
' §11.8.1.1 Applicability
'A member M is considered more applicable than N if their signatures are different and at least one
'parameter type in M is more applicable than a parameter type in N, and no parameter type in N is more
'applicable than a parameter type in M.
Dim equallyApplicable As Boolean = True
Dim leftHasMoreApplicableParameterType As Boolean = False
Dim rightHasMoreApplicableParameterType As Boolean = False
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For i = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(i))
End If
Dim rightParamType As TypeSymbol
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(i))
End If
' Parameters matching omitted arguments do not participate.
If arguments(i).Kind = BoundKind.OmittedArgument Then
Continue For
End If
Dim cmp = CompareParameterTypeApplicability(leftParamType, rightParamType, arguments(i), binder, useSiteInfo)
If cmp = ApplicabilityComparisonResult.LeftIsMoreApplicable Then
leftHasMoreApplicableParameterType = True
If rightHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.Undefined ' Neither is more applicable
End If
equallyApplicable = False
ElseIf cmp = ApplicabilityComparisonResult.RightIsMoreApplicable Then
rightHasMoreApplicableParameterType = True
If leftHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.Undefined ' Neither is more applicable
End If
equallyApplicable = False
ElseIf cmp = ApplicabilityComparisonResult.Undefined Then
equallyApplicable = False
Else
Debug.Assert(cmp = ApplicabilityComparisonResult.EquallyApplicable)
End If
Next
Debug.Assert(Not (leftHasMoreApplicableParameterType AndAlso rightHasMoreApplicableParameterType))
If leftHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If rightHasMoreApplicableParameterType Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
Return If(equallyApplicable, ApplicabilityComparisonResult.EquallyApplicable, ApplicabilityComparisonResult.Undefined)
End Function
Private Enum ApplicabilityComparisonResult
Undefined
EquallyApplicable
LeftIsMoreApplicable
RightIsMoreApplicable
End Enum
''' <summary>
''' §11.8.1.1 Applicability
''' </summary>
Private Shared Function CompareParameterTypeApplicability(
left As TypeSymbol,
right As TypeSymbol,
argument As BoundExpression,
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As ApplicabilityComparisonResult
Debug.Assert(argument Is Nothing OrElse argument.Kind <> BoundKind.OmittedArgument)
' §11.8.1.1 Applicability
'Given a pair of parameters Mj and Nj that matches an argument Aj,
'the type of Mj is considered more applicable than the type of Nj if one of the following conditions is true:
Dim leftToRightConversion = Conversions.ClassifyConversion(left, right, useSiteInfo)
'1. Mj and Nj have identical types, or
' !!! Does this rule make sense? Not implementing it for now.
If Conversions.IsIdentityConversion(leftToRightConversion.Key) Then
Return ApplicabilityComparisonResult.EquallyApplicable
End If
'2. There exists a widening conversion from the type of Mj to the type Nj, or
If Conversions.IsWideningConversion(leftToRightConversion.Key) Then
' !!! For user defined conversions that widen in both directions there is a tie-breaking rule
' !!! not mentioned in the spec. The type that matches argument's type is more applicable.
' !!! Otherwise neither is more applicable.
If Conversions.IsWideningConversion(Conversions.ClassifyConversion(right, left, useSiteInfo).Key) Then
GoTo BreakTheTie
End If
' !!! Spec makes it look like rule #3 is a separate rule applied after the second, but this isn't the case
' !!! because enumerated type widens to its underlying type, however, if argument is a zero literal,
' !!! underlying type should win.
' !!! Also, based on Dev10 implementation, Mj doesn't have to be a numeric type, it is enough if it is not
' !!! an enumerated type.
'3. Aj is the literal 0, Mj is a numeric type and Nj is an enumerated type, or
If argument IsNot Nothing AndAlso argument.IsIntegerZeroLiteral AndAlso
left.TypeKind = TypeKind.Enum AndAlso right.TypeKind <> TypeKind.Enum Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If Conversions.IsWideningConversion(Conversions.ClassifyConversion(right, left, useSiteInfo).Key) Then
' !!! Spec makes it look like rule #3 is a separate rule applied after the second, but this isn't the case
' !!! because enumerated type widens to its underlying type, however, if argument is a zero literal,
' !!! underlying type should win.
' !!! Also, based on Dev10 implementation, Mj doesn't have to be a numeric type, it is enough if it is not
' !!! an enumerated type.
'3. Aj is the literal 0, Mj is a numeric type and Nj is an enumerated type, or
If argument IsNot Nothing AndAlso argument.IsIntegerZeroLiteral AndAlso
right.TypeKind = TypeKind.Enum AndAlso left.TypeKind <> TypeKind.Enum Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
''3. Aj is the literal 0, Mj is a numeric type and Nj is an enumerated type, or
'If argument IsNot Nothing AndAlso argument.IsIntegerZeroLiteral Then
' If left.IsNumericType() Then
' If right.TypeKind = TypeKind.Enum Then
' leftIsMoreApplicable = True
' Return
' End If
' ElseIf right.IsNumericType() Then
' If left.TypeKind = TypeKind.Enum Then
' rightIsMoreApplicable = True
' Return
' End If
' End If
'End If
'4. Mj is Byte and Nj is SByte, or
'5. Mj is Short and Nj is UShort, or
'6. Mj is Integer and Nj is UInteger, or
'7. Mj is Long and Nj is ULong.
'!!! Plus rules not mentioned in the spec
If left.IsNumericType() AndAlso right.IsNumericType() Then
Dim leftSpecialType = left.SpecialType
Dim rightSpecialType = right.SpecialType
If leftSpecialType = SpecialType.System_Byte AndAlso rightSpecialType = SpecialType.System_SByte Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If leftSpecialType = SpecialType.System_SByte AndAlso rightSpecialType = SpecialType.System_Byte Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
' This comparison depends on the ordering of the SpecialType enum. There is a unit-test that verifies the ordering.
If leftSpecialType < rightSpecialType Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
Else
Debug.Assert(rightSpecialType < leftSpecialType)
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
End If
'8. Mj and Nj are delegate function types and the return type of Mj is more specific than the return type of Nj.
' If Aj is classified as a lambda method, and Mj or Nj is System.Linq.Expressions.Expression(Of T), then the
' type argument of the type (assuming it is a delegate type) is substituted for the type being compared.
If argument IsNot Nothing Then
Dim leftIsExpressionTree As Boolean, rightIsExpressionTree As Boolean
Dim leftDelegateType As NamedTypeSymbol = left.DelegateOrExpressionDelegate(binder, leftIsExpressionTree)
Dim rightDelegateType As NamedTypeSymbol = right.DelegateOrExpressionDelegate(binder, rightIsExpressionTree)
' Native compiler will only compare D1 and D2 for Expression(Of D1) and D2 if the argument is a lambda. It will compare
' Expression(Of D1) and Expression (Of D2) regardless of the argument.
If leftDelegateType IsNot Nothing AndAlso rightDelegateType IsNot Nothing AndAlso
((leftIsExpressionTree = rightIsExpressionTree) OrElse argument.IsAnyLambda()) Then
Dim leftInvoke As MethodSymbol = leftDelegateType.DelegateInvokeMethod
Dim rightInvoke As MethodSymbol = rightDelegateType.DelegateInvokeMethod
If leftInvoke IsNot Nothing AndAlso Not leftInvoke.IsSub AndAlso rightInvoke IsNot Nothing AndAlso Not rightInvoke.IsSub Then
Dim newArgument As BoundExpression = Nothing
' TODO: Should probably handle GroupTypeInferenceLambda too.
If argument.Kind = BoundKind.QueryLambda Then
newArgument = DirectCast(argument, BoundQueryLambda).Expression
End If
Return CompareParameterTypeApplicability(leftInvoke.ReturnType, rightInvoke.ReturnType, newArgument, binder, useSiteInfo)
End If
End If
End If
BreakTheTie:
' !!! There is a tie-breaking rule not mentioned in the spec. The type that matches argument's type is more applicable.
' !!! Otherwise neither is more applicable.
If argument IsNot Nothing Then
Dim argType As TypeSymbol = If(argument.Kind <> BoundKind.ArrayLiteral, argument.Type, DirectCast(argument, BoundArrayLiteral).InferredType)
If argType IsNot Nothing Then
If left.IsSameTypeIgnoringAll(argType) Then
Return ApplicabilityComparisonResult.LeftIsMoreApplicable
End If
If right.IsSameTypeIgnoringAll(argType) Then
Return ApplicabilityComparisonResult.RightIsMoreApplicable
End If
End If
End If
' Neither is more applicable
Return ApplicabilityComparisonResult.Undefined
End Function
''' <summary>
''' This method groups equally applicable (§11.8.1.1 Applicability) candidates into buckets.
'''
''' Returns an ArrayBuilder of buckets. Each bucket is represented by an ArrayBuilder(Of Integer),
''' which contains indexes of equally applicable candidates from input parameter 'candidates'.
''' </summary>
Private Shared Function GroupEquallyApplicableCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As ArrayBuilder(Of ArrayBuilder(Of Integer))
Dim buckets = ArrayBuilder(Of ArrayBuilder(Of Integer)).GetInstance()
Dim i As Integer
Dim j As Integer
' §11.8.1.1 Applicability
' A member M is considered equally applicable as N if their signatures are the same or
' if each parameter type in M is the same as the corresponding parameter type in N.
For i = 0 To candidates.Count - 1 Step 1
Dim left As CandidateAnalysisResult = candidates(i)
If left.State <> CandidateAnalysisResultState.Applicable OrElse
left.EquallyApplicableCandidatesBucket > 0 Then
Continue For
End If
left.EquallyApplicableCandidatesBucket = buckets.Count + 1
candidates(i) = left
Dim b = ArrayBuilder(Of Integer).GetInstance()
b.Add(i)
buckets.Add(b)
For j = i + 1 To candidates.Count - 1 Step 1
Dim right As CandidateAnalysisResult = candidates(j)
If right.State <> CandidateAnalysisResultState.Applicable OrElse
right.EquallyApplicableCandidatesBucket > 0 OrElse
right.Candidate Is left.Candidate Then
Continue For
End If
If CandidatesAreEquallyApplicableToArguments(left, right, arguments, binder) Then
right.EquallyApplicableCandidatesBucket = left.EquallyApplicableCandidatesBucket
candidates(j) = right
b.Add(j)
End If
Next
Next
Return buckets
End Function
Private Shared Function CandidatesAreEquallyApplicableToArguments(
ByRef left As CandidateAnalysisResult,
ByRef right As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As Boolean
' §11.8.1.1 Applicability
' A member M is considered equally applicable as N if their signatures are the same or
' if each parameter type in M is the same as the corresponding parameter type in N.
' Compare types of corresponding parameters
Dim k As Integer
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For k = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(k))
End If
Dim rightParamType As TypeSymbol
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(k))
End If
' Parameters matching omitted arguments do not participate.
If arguments(k).Kind <> BoundKind.OmittedArgument AndAlso
Not ParametersAreEquallyApplicableToArgument(leftParamType, rightParamType, arguments(k), binder) Then
' Signatures are different
Exit For
End If
Next
Return k >= arguments.Length
End Function
Private Shared Function ParametersAreEquallyApplicableToArgument(
leftParamType As TypeSymbol,
rightParamType As TypeSymbol,
argument As BoundExpression,
binder As Binder
) As Boolean
Debug.Assert(argument Is Nothing OrElse argument.Kind <> BoundKind.OmittedArgument)
If Not leftParamType.IsSameTypeIgnoringAll(rightParamType) Then
If argument IsNot Nothing Then
Dim leftIsExpressionTree As Boolean, rightIsExpressionTree As Boolean
Dim leftDelegateType As NamedTypeSymbol = leftParamType.DelegateOrExpressionDelegate(binder, leftIsExpressionTree)
Dim rightDelegateType As NamedTypeSymbol = rightParamType.DelegateOrExpressionDelegate(binder, rightIsExpressionTree)
' Native compiler will only compare D1 and D2 for Expression(Of D1) and D2 if the argument is a lambda. It will compare
' Expression(Of D1) and Expression (Of D2) regardless of the argument.
If leftDelegateType IsNot Nothing AndAlso rightDelegateType IsNot Nothing AndAlso
((leftIsExpressionTree = rightIsExpressionTree) OrElse argument.IsAnyLambda()) Then
Dim leftInvoke As MethodSymbol = leftDelegateType.DelegateInvokeMethod
Dim rightInvoke As MethodSymbol = rightDelegateType.DelegateInvokeMethod
If leftInvoke IsNot Nothing AndAlso Not leftInvoke.IsSub AndAlso rightInvoke IsNot Nothing AndAlso Not rightInvoke.IsSub Then
Dim newArgument As BoundExpression = Nothing
' TODO: Should probably handle GroupTypeInferenceLambda too.
If argument.Kind = BoundKind.QueryLambda Then
newArgument = DirectCast(argument, BoundQueryLambda).Expression
End If
Return ParametersAreEquallyApplicableToArgument(leftInvoke.ReturnType, rightInvoke.ReturnType, newArgument, binder)
End If
End If
End If
' Signatures are different
Return False
End If
Return True
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 3. Next, eliminate all members from the set that require narrowing conversions
''' to be applicable to the argument list, except for the case where the argument
''' expression type is Object.
''' 4. Next, eliminate all remaining members from the set that require narrowing coercions
''' to be applicable to the argument list. If the set is empty, the type containing the
''' method group is not an interface, and strict semantics are not being used, the
''' invocation target expression is reclassified as a late-bound method access.
''' Otherwise, the normal rules apply.
'''
''' Returns amount of applicable candidates left.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Shared Function AnalyzeNarrowingCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
delegateReturnType As TypeSymbol,
lateBindingIsAllowed As Boolean,
binder As Binder,
ByRef resolutionIsLateBound As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Integer
Dim applicableCandidates As Integer = 0
Dim appliedTieBreakingRules As Boolean = False
' Look through the candidate set for lifted operators that require narrowing conversions whose
' source operators also require narrowing conversions. In that case, we only want to keep one method in
' the set. If the source operator requires nullables to be unwrapped, then we discard it and keep the lifted operator.
' If it does not, then we discard the lifted operator and keep the source operator. This will prevent the presence of
' lifted operators from causing overload resolution conflicts where there otherwise wouldn't be one. However,
' if the source operator only requires narrowing conversions from numeric literals, then we keep both in the set,
' because the conversion in that case is not really narrowing.
If candidates(0).Candidate.IsOperator Then
' As an optimization, we can rely on the fact that lifted operator, if added, immediately
' follows source operator.
Dim i As Integer
For i = 0 To candidates.Count - 2 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
Debug.Assert(current.Candidate.IsOperator)
If current.State = CandidateAnalysisResultState.Applicable AndAlso
Not current.Candidate.IsLifted AndAlso
current.RequiresNarrowingNotFromNumericConstant Then
Dim contender As CandidateAnalysisResult = candidates(i + 1)
Debug.Assert(contender.Candidate.IsOperator)
If contender.State = CandidateAnalysisResultState.Applicable AndAlso
contender.Candidate.IsLifted AndAlso
current.Candidate.UnderlyingSymbol Is contender.Candidate.UnderlyingSymbol Then
Exit For
End If
End If
Next
If i < candidates.Count - 1 Then
' [i] is the index of the first "interesting" pair of source/lifted operators.
If Not appliedTieBreakingRules Then
' Apply shadowing rules, Dev10 compiler does that for narrowing candidates too.
applicableCandidates = ApplyTieBreakingRulesToEquallyApplicableCandidates(candidates, arguments, delegateReturnType, binder, useSiteInfo)
appliedTieBreakingRules = True
Debug.Assert(applicableCandidates > 1) ' source and lifted operators are not equally applicable.
End If
' Let's do the elimination pass now.
For i = i To candidates.Count - 2 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
Debug.Assert(current.Candidate.IsOperator)
If current.State = CandidateAnalysisResultState.Applicable AndAlso
Not current.Candidate.IsLifted AndAlso
current.RequiresNarrowingNotFromNumericConstant Then
Dim contender As CandidateAnalysisResult = candidates(i + 1)
Debug.Assert(contender.Candidate.IsOperator)
If contender.State = CandidateAnalysisResultState.Applicable AndAlso
contender.Candidate.IsLifted AndAlso
current.Candidate.UnderlyingSymbol Is contender.Candidate.UnderlyingSymbol Then
For j As Integer = 0 To arguments.Length - 1
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = current.ConversionsOpt(j)
If Conversions.IsNarrowingConversion(conv.Key) Then
Dim lost As Boolean = False
If (conv.Key And ConversionKind.UserDefined) = 0 Then
If IsUnwrappingNullable(conv.Key, arguments(j).Type, current.Candidate.Parameters(j).Type) Then
lost = True
End If
Else
' Lifted user-defined conversions don't unwrap nullables, they are marked with Nullable bit.
If (conv.Key And ConversionKind.Nullable) = 0 Then
If IsUnwrappingNullable(arguments(j).Type, conv.Value.Parameters(0).Type, useSiteInfo) Then
lost = True
ElseIf IsUnwrappingNullable(conv.Value.ReturnType, current.Candidate.Parameters(j).Type, useSiteInfo) Then
lost = True
End If
End If
End If
If lost Then
' unwrapping nullable, current lost
current.State = CandidateAnalysisResultState.Shadowed
candidates(i) = current
i = i + 1
GoTo Next_i
End If
End If
Next
' contender lost
contender.State = CandidateAnalysisResultState.Shadowed
candidates(i + 1) = contender
i = i + 1
GoTo Next_i
End If
End If
Next_i:
Next
End If
End If
If lateBindingIsAllowed Then
' Are there all narrowing from object candidates?
Dim haveAllNarrowingFromObject As Boolean = HaveNarrowingOnlyFromObjectCandidates(candidates)
If haveAllNarrowingFromObject AndAlso Not appliedTieBreakingRules Then
' Apply shadowing rules, Dev10 compiler does that for narrowing candidates too.
applicableCandidates = ApplyTieBreakingRulesToEquallyApplicableCandidates(candidates, arguments, delegateReturnType, binder, useSiteInfo)
appliedTieBreakingRules = True
If applicableCandidates < 2 Then
Return applicableCandidates
End If
haveAllNarrowingFromObject = HaveNarrowingOnlyFromObjectCandidates(candidates)
End If
If haveAllNarrowingFromObject Then
' Get rid of candidates that require narrowing from something other than Object
applicableCandidates = 0
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable Then
If (current.RequiresNarrowingNotFromObject OrElse current.Candidate.IsExtensionMethod) Then
current.State = CandidateAnalysisResultState.ExtensionMethodVsLateBinding
candidates(i) = current
Else
applicableCandidates += 1
End If
End If
Next
Debug.Assert(applicableCandidates > 0)
If applicableCandidates > 1 Then
resolutionIsLateBound = True
End If
Return applicableCandidates
End If
End If
' Although all candidates narrow, there may be a best choice when factoring in narrowing of numeric constants.
' Note that EliminateLessApplicableToTheArguments applies shadowing rules, Dev10 compiler does that for narrowing candidates too.
applicableCandidates = EliminateLessApplicableToTheArguments(candidates, arguments, delegateReturnType, appliedTieBreakingRules, binder,
mostApplicableMustNarrowOnlyFromNumericConstants:=True, useSiteInfo:=useSiteInfo)
' If we ended up with 2 applicable candidates, make sure it is not the same method in
' ParamArray expanded and non-expanded form. The non-expanded form should win in this case.
If applicableCandidates = 2 Then
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim first As CandidateAnalysisResult = candidates(i)
If first.State = CandidateAnalysisResultState.Applicable Then
For j As Integer = i + 1 To candidates.Count - 1 Step 1
Dim second As CandidateAnalysisResult = candidates(j)
If second.State = CandidateAnalysisResultState.Applicable Then
If first.Candidate.UnderlyingSymbol.Equals(second.Candidate.UnderlyingSymbol) Then
Dim firstWins As Boolean = False
Dim secondWins As Boolean = False
If ShadowBasedOnParamArrayUsage(first, second, firstWins, secondWins) Then
If firstWins Then
second.State = CandidateAnalysisResultState.Shadowed
candidates(j) = second
applicableCandidates = 1
ElseIf secondWins Then
first.State = CandidateAnalysisResultState.Shadowed
candidates(i) = first
applicableCandidates = 1
End If
Debug.Assert(applicableCandidates = 1)
End If
End If
GoTo Done
End If
Next
Debug.Assert(False, "Should not reach this line.")
End If
Next
End If
Done:
Return applicableCandidates
End Function
Private Shared Function IsUnwrappingNullable(
conv As ConversionKind,
sourceType As TypeSymbol,
targetType As TypeSymbol
) As Boolean
Debug.Assert((conv And ConversionKind.UserDefined) = 0)
Return (conv And ConversionKind.Nullable) <> 0 AndAlso
sourceType IsNot Nothing AndAlso
sourceType.IsNullableType() AndAlso
Not targetType.IsNullableType()
End Function
Private Shared Function IsUnwrappingNullable(
sourceType As TypeSymbol,
targetType As TypeSymbol,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
Return sourceType IsNot Nothing AndAlso
IsUnwrappingNullable(Conversions.ClassifyPredefinedConversion(sourceType, targetType, useSiteInfo), sourceType, targetType)
End Function
Private Shared Function HaveNarrowingOnlyFromObjectCandidates(
candidates As ArrayBuilder(Of CandidateAnalysisResult)
) As Boolean
Dim haveAllNarrowingFromObject As Boolean = False
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable AndAlso
Not current.RequiresNarrowingNotFromObject AndAlso
Not current.Candidate.IsExtensionMethod Then
haveAllNarrowingFromObject = True
Exit For
End If
Next
Return haveAllNarrowingFromObject
End Function
''' <summary>
''' §11.8.1 Overloaded Method Resolution
''' 2. Next, eliminate all members from the set that are inaccessible or not applicable to the argument list.
'''
''' Note, similar to Dev10 compiler this process will eliminate candidates requiring narrowing conversions
''' if strict semantics is used, exception are candidates that require narrowing only from numeric constants.
'''
''' Returns amount of applicable candidates left.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Shared Function EliminateNotApplicableToArguments(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
candidates As ArrayBuilder(Of CandidateAnalysisResult),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
<Out()> ByRef applicableNarrowingCandidates As Integer,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
callerInfoOpt As SyntaxNode,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Integer
Dim applicableCandidates As Integer = 0
Dim illegalInAttribute As Integer = 0
applicableNarrowingCandidates = 0
' Filter out inapplicable candidates
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State <> CandidateAnalysisResultState.Applicable Then
Continue For
End If
If Not current.ArgumentMatchingDone Then
MatchArguments(methodOrPropertyGroup, current, arguments, argumentNames, binder, asyncLambdaSubToFunctionMismatch, callerInfoOpt, forceExpandedForm, useSiteInfo)
current.SetArgumentMatchingDone()
candidates(i) = current
End If
If current.State = CandidateAnalysisResultState.Applicable Then
applicableCandidates += 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates += 1
End If
If current.IsIllegalInAttribute Then
illegalInAttribute += 1
End If
End If
Next
' Filter out candidates with IsIllegalInAttribute if there are other applicable candidates
If illegalInAttribute > 0 AndAlso applicableCandidates > illegalInAttribute Then
For i As Integer = 0 To candidates.Count - 1 Step 1
Dim current As CandidateAnalysisResult = candidates(i)
If current.State = CandidateAnalysisResultState.Applicable AndAlso current.IsIllegalInAttribute Then
applicableCandidates -= 1
If current.RequiresNarrowingConversion Then
applicableNarrowingCandidates -= 1
End If
current.State = CandidateAnalysisResultState.ArgumentMismatch
candidates(i) = current
End If
Next
Debug.Assert(applicableCandidates > 0)
End If
Return applicableCandidates
End Function
''' <summary>
''' Figure out corresponding arguments for parameters §11.8.2 Applicable Methods.
'''
''' Note, this function mutates the candidate structure.
'''
''' If non-Nothing ArrayBuilders are returned through parameterToArgumentMap and paramArrayItems
''' parameters, the caller is responsible fo returning them into the pool.
'''
''' Assumptions:
''' 1) This function is never called for a candidate that should be rejected due to parameter count.
''' 2) Omitted arguments [ Call Goo(a, , b) ] are represented by OmittedArgumentExpression node in the arguments array.
''' 3) Omitted argument never has name.
''' 4) argumentNames contains Nothing for all positional arguments.
'''
''' !!! Should keep this function in sync with Binder.PassArguments, which uses data this function populates. !!!
''' !!! Should keep this function in sync with Binder.ReportOverloadResolutionFailureForASingleCandidate. !!!
''' !!! Everything we flag as an error here, Binder.ReportOverloadResolutionFailureForASingleCandidate should detect as well. !!!
''' </summary>
Private Shared Sub BuildParameterToArgumentMap(
ByRef candidate As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
ByRef parameterToArgumentMap As ArrayBuilder(Of Integer),
ByRef paramArrayItems As ArrayBuilder(Of Integer)
)
Debug.Assert(Not arguments.IsDefault)
Debug.Assert(argumentNames.IsDefault OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length))
Debug.Assert(Not candidate.ArgumentMatchingDone)
Debug.Assert(candidate.State = CandidateAnalysisResultState.Applicable)
parameterToArgumentMap = ArrayBuilder(Of Integer).GetInstance(candidate.Candidate.ParameterCount, -1)
Dim argsToParams As ArrayBuilder(Of Integer) = Nothing
If Not argumentNames.IsDefault Then
argsToParams = ArrayBuilder(Of Integer).GetInstance(arguments.Length, -1)
End If
paramArrayItems = Nothing
If candidate.IsExpandedParamArrayForm Then
paramArrayItems = ArrayBuilder(Of Integer).GetInstance()
End If
'§11.8.2 Applicable Methods
'1. First, match each positional argument in order to the list of method parameters.
'If there are more positional arguments than parameters and the last parameter is not a paramarray, the method is not applicable.
'Otherwise, the paramarray parameter is expanded with parameters of the paramarray element type to match the number of positional arguments.
'If a positional argument is omitted, the method is not applicable.
' !!! Not sure about the last sentence: "If a positional argument is omitted, the method is not applicable."
' !!! Dev10 allows omitting positional argument as long as the corresponding parameter is optional.
Dim positionalArguments As Integer = 0
Dim paramIndex = 0
For i As Integer = 0 To arguments.Length - 1 Step 1
If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then
' A named argument
If Not candidate.Candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then
' ERRID_NamedParamNotFound1
' ERRID_NamedParamNotFound2
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
End If
If paramIndex <> i Then
' all remaining arguments must be named
Exit For
End If
If paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
candidate.Candidate.Parameters(paramIndex).IsParamArray Then
' ERRID_NamedParamArrayArgument
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
End If
Debug.Assert(parameterToArgumentMap(paramIndex) = -1)
End If
positionalArguments += 1
If argsToParams IsNot Nothing Then
argsToParams(i) = paramIndex
End If
If arguments(i).Kind = BoundKind.OmittedArgument Then
If paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
candidate.Candidate.Parameters(paramIndex).IsParamArray Then
' Omitted ParamArray argument at the call site
' ERRID_OmittedParamArrayArgument
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
Else
parameterToArgumentMap(paramIndex) = i
paramIndex += 1
End If
ElseIf (candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1) Then
paramArrayItems.Add(i)
Else
parameterToArgumentMap(paramIndex) = i
paramIndex += 1
End If
Next
'§11.8.2 Applicable Methods
'2. Next, match each named argument to a parameter with the given name.
'If one of the named arguments fails to match, matches a paramarray parameter,
'or matches an argument already matched with another positional or named argument,
'the method is not applicable.
For i As Integer = positionalArguments To arguments.Length - 1 Step 1
Debug.Assert(argumentNames(i) Is Nothing OrElse argumentNames(i).Length > 0)
If argumentNames(i) Is Nothing Then
' Unnamed argument follows named arguments, parser should have detected an error.
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
If Not candidate.Candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then
' ERRID_NamedParamNotFound1
' ERRID_NamedParamNotFound2
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
If argsToParams IsNot Nothing Then
argsToParams(i) = paramIndex
End If
If paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
candidate.Candidate.Parameters(paramIndex).IsParamArray Then
' ERRID_NamedParamArrayArgument
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
If parameterToArgumentMap(paramIndex) <> -1 Then
' ERRID_NamedArgUsedTwice1
' ERRID_NamedArgUsedTwice2
' ERRID_NamedArgUsedTwice3
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
' It is an error for a named argument to specify
' a value for an explicitly omitted positional argument.
If paramIndex < positionalArguments Then
'ERRID_NamedArgAlsoOmitted1
'ERRID_NamedArgAlsoOmitted2
'ERRID_NamedArgAlsoOmitted3
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
GoTo Bailout
'Continue For
End If
parameterToArgumentMap(paramIndex) = i
Next
If argsToParams IsNot Nothing Then
candidate.ArgsToParamsOpt = argsToParams.ToImmutableAndFree()
argsToParams = Nothing
End If
Bailout:
If argsToParams IsNot Nothing Then
argsToParams.Free()
argsToParams = Nothing
End If
End Sub
''' <summary>
''' Match candidate's parameters to arguments §11.8.2 Applicable Methods.
'''
''' Note, similar to Dev10 compiler this process will eliminate candidate requiring narrowing conversions
''' if strict semantics is used, exception are candidates that require narrowing only from numeric constants.
'''
''' Assumptions:
''' 1) This function is never called for a candidate that should be rejected due to parameter count.
''' 2) Omitted arguments [ Call Goo(a, , b) ] are represented by OmittedArgumentExpression node in the arguments array.
''' 3) Omitted argument never has name.
''' 4) argumentNames contains Nothing for all positional arguments.
'''
''' !!! Should keep this function in sync with Binder.PassArguments, which uses data this function populates. !!!
''' !!! Should keep this function in sync with Binder.ReportOverloadResolutionFailureForASingleCandidate. !!!
''' !!! Should keep this function in sync with InferenceGraph.PopulateGraph. !!!
''' !!! Everything we flag as an error here, Binder.ReportOverloadResolutionFailureForASingleCandidate should detect as well. !!!
''' </summary>
Private Shared Sub MatchArguments(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
ByRef candidate As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
callerInfoOpt As SyntaxNode,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(Not arguments.IsDefault)
Debug.Assert(argumentNames.IsDefault OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length))
Debug.Assert(Not candidate.ArgumentMatchingDone)
Debug.Assert(candidate.State = CandidateAnalysisResultState.Applicable)
Debug.Assert(Not candidate.Candidate.UnderlyingSymbol.IsReducedExtensionMethod() OrElse methodOrPropertyGroup.ReceiverOpt IsNot Nothing OrElse TypeOf methodOrPropertyGroup.SyntaxTree Is DummySyntaxTree)
Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Nothing
Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing
Dim conversionKinds As KeyValuePair(Of ConversionKind, MethodSymbol)() = Nothing
Dim conversionBackKinds As KeyValuePair(Of ConversionKind, MethodSymbol)() = Nothing
Dim optionalArguments As OptionalArgument() = Nothing
Dim defaultValueDiagnostics As BindingDiagnosticBag = Nothing
BuildParameterToArgumentMap(candidate, arguments, argumentNames, parameterToArgumentMap, paramArrayItems)
If candidate.State <> CandidateAnalysisResultState.Applicable Then
Debug.Assert(Not candidate.IgnoreExtensionMethods)
GoTo Bailout
End If
' At this point we will set IgnoreExtensionMethods to true and will
' clear it when appropriate because not every failure should allow
' us to consider extension methods.
If Not candidate.Candidate.IsExtensionMethod Then
candidate.IgnoreExtensionMethods = True
End If
'§11.8.2 Applicable Methods
'The type arguments, if any, must satisfy the constraints, if any, on the matching type parameters.
Dim candidateSymbol = candidate.Candidate.UnderlyingSymbol
If candidateSymbol.Kind = SymbolKind.Method Then
Dim method = DirectCast(candidateSymbol, MethodSymbol)
If method.IsGenericMethod Then
Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance()
Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing
Dim satisfiedConstraints = method.CheckConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder, template:=useSiteInfo)
diagnosticsBuilder.Free()
If useSiteDiagnosticsBuilder IsNot Nothing AndAlso useSiteDiagnosticsBuilder.Count > 0 Then
For Each diag In useSiteDiagnosticsBuilder
useSiteInfo.Add(diag.UseSiteInfo)
Next
End If
If Not satisfiedConstraints Then
' Do not clear IgnoreExtensionMethods flag if constraints are violated.
candidate.State = CandidateAnalysisResultState.GenericConstraintsViolated
GoTo Bailout
End If
End If
End If
' Traverse the parameters, converting corresponding arguments
' as appropriate.
Dim argIndex As Integer
Dim candidateIsAProperty As Boolean = (candidate.Candidate.UnderlyingSymbol.Kind = SymbolKind.Property)
For paramIndex = 0 To candidate.Candidate.ParameterCount - 1 Step 1
If candidate.State <> CandidateAnalysisResultState.Applicable AndAlso
Not candidate.IgnoreExtensionMethods Then
' There is no reason to continue. We will not learn anything new.
GoTo Bailout
End If
Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex)
Dim isByRef As Boolean = param.IsByRef
Dim targetType As TypeSymbol = param.Type
If param.IsParamArray AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 Then
If targetType.Kind <> SymbolKind.ArrayType Then
' ERRID_ParamArrayWrongType
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
If Not candidate.IsExpandedParamArrayForm Then
argIndex = parameterToArgumentMap(paramIndex)
Dim paramArrayArgument = If(argIndex = -1, Nothing, arguments(argIndex))
Debug.Assert(paramArrayArgument Is Nothing OrElse paramArrayArgument.Kind <> BoundKind.OmittedArgument)
'§11.8.2 Applicable Methods
'If the conversion from the type of the argument expression to the paramarray type is narrowing,
'then the method is only applicable in its expanded form.
'!!! However, there is an exception to that rule - narrowing conversion from semantical Nothing literal is Ok. !!!
Dim arrayConversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
If Not (paramArrayArgument IsNot Nothing AndAlso
Not paramArrayArgument.HasErrors AndAlso CanPassToParamArray(paramArrayArgument, targetType, arrayConversion, binder, useSiteInfo)) Then
' It doesn't look like native compiler reports any errors in this case.
' Probably due to assumption that either errors were already reported for bad argument expression or
' we will report errors for expanded version of the same candidate.
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
ElseIf Conversions.IsNarrowingConversion(arrayConversion.Key) Then
' We can get here only for Object with constant value == Nothing.
Debug.Assert(paramArrayArgument.IsNothingLiteral())
' Unlike for other arguments, Dev10 doesn't make a note of this narrowing.
' However, should this narrowing cause a conversion error, the error must be noted.
If binder.OptionStrict = OptionStrict.On Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, this doesn't clear IgnoreExtensionMethods flag.
Continue For
End If
Else
Debug.Assert(Conversions.IsWideningConversion(arrayConversion.Key))
End If
' Since CanPassToParamArray succeeded, there is no need to check conversions for this argument again
If Not Conversions.IsIdentityConversion(arrayConversion.Key) Then
If conversionKinds Is Nothing Then
conversionKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionKinds.Length - 1
conversionKinds(i) = Conversions.Identity
Next
End If
conversionKinds(argIndex) = arrayConversion
End If
Else
Debug.Assert(candidate.IsExpandedParamArrayForm)
'§11.8.2 Applicable Methods
' If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form.
' Note, that explicitly converted NOTHING is treated the same way by Dev10.
' But, for the purpose of interpolated string lowering the method is applicable even if the argument expression
' is the literal Nothing. This is because for interpolated string lowering we want to always call methods
' in their expanded form. E.g. $"{Nothing}" should be lowered to String.Format("{0}", New Object() {Nothing}) not
' String.Format("{0}", CType(Nothing, Object())).
If paramArrayItems.Count = 1 AndAlso arguments(paramArrayItems(0)).IsNothingLiteral() AndAlso Not forceExpandedForm Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
' Otherwise, for a ParamArray parameter, all the matching arguments are passed
' ByVal as instances of the element type of the ParamArray.
' Perform the conversions to the element type of the ParamArray here.
Dim arrayType = DirectCast(targetType, ArrayTypeSymbol)
If Not arrayType.IsSZArray Then
' ERRID_ParamArrayWrongType
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
targetType = arrayType.ElementType
If targetType.Kind = SymbolKind.ErrorType Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, IgnoreExtensionMethods is not cleared.
Continue For
End If
For j As Integer = 0 To paramArrayItems.Count - 1 Step 1
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
If arguments(paramArrayItems(j)).HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011]
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
'Continue For
End If
If Not MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, arguments(paramArrayItems(j)), targetType, binder, conv, asyncLambdaSubToFunctionMismatch, useSiteInfo) Then
' Note, IgnoreExtensionMethods is not cleared here, MatchArgumentToByValParameter makes required changes.
Continue For
End If
' typically all conversions in otherwise acceptable candidate are identity conversions
If Not Conversions.IsIdentityConversion(conv.Key) Then
If conversionKinds Is Nothing Then
conversionKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionKinds.Length - 1
conversionKinds(i) = Conversions.Identity
Next
End If
conversionKinds(paramArrayItems(j)) = conv
End If
Next
End If
Continue For
End If
argIndex = parameterToArgumentMap(paramIndex)
Dim argument = If(argIndex = -1, Nothing, arguments(argIndex))
Dim defaultArgument As BoundExpression = Nothing
If argument Is Nothing OrElse argument.Kind = BoundKind.OmittedArgument Then
' Deal with Optional arguments.
If defaultValueDiagnostics Is Nothing Then
defaultValueDiagnostics = BindingDiagnosticBag.GetInstance()
Else
defaultValueDiagnostics.Clear()
End If
Dim receiverOpt As BoundExpression = Nothing
If candidateSymbol.IsReducedExtensionMethod() Then
receiverOpt = methodOrPropertyGroup.ReceiverOpt
End If
defaultArgument = binder.GetArgumentForParameterDefaultValue(param, If(argument, methodOrPropertyGroup).Syntax, defaultValueDiagnostics, callerInfoOpt, parameterToArgumentMap, arguments, receiverOpt)
If defaultArgument IsNot Nothing AndAlso Not defaultValueDiagnostics.HasAnyErrors Then
Debug.Assert(Not defaultValueDiagnostics.DiagnosticBag.AsEnumerable().Any())
' Mark these as compiler generated so they are ignored by later phases. For example,
' these bound nodes will mess up the incremental binder cache, because they use the
' the same syntax node as the method identifier from the invocation / AddressOf if they
' are not marked.
defaultArgument.SetWasCompilerGenerated()
argument = defaultArgument
Else
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
'Note, IgnoreExtensionMethods flag should not be cleared due to a badness of default value.
candidate.IgnoreExtensionMethods = False
GoTo Bailout
End If
End If
If targetType.Kind = SymbolKind.ErrorType Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, IgnoreExtensionMethods is not cleared.
Continue For
End If
If argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011]
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
GoTo Bailout
End If
Dim conversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
Dim conversionBack As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing
Debug.Assert(Not isByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType())
' Arguments for properties are always passed with ByVal semantics. Even if
' parameter in metadata is defined ByRef, we always pass corresponding argument
' through a temp without copy-back.
' Non-string arguments for implicitly ByRef string parameters of Declare functions
' are passed through a temp without copy-back.
If isByRef AndAlso Not candidateIsAProperty AndAlso defaultArgument Is Nothing AndAlso
(param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then
MatchArgumentToByRefParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, conversion, conversionBack, asyncLambdaSubToFunctionMismatch, useSiteInfo)
Else
conversionBack = Conversions.Identity
MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, conversion, asyncLambdaSubToFunctionMismatch, useSiteInfo, defaultArgument IsNot Nothing)
End If
' typically all conversions in otherwise acceptable candidate are identity conversions
If Not Conversions.IsIdentityConversion(conversion.Key) Then
If conversionKinds Is Nothing Then
conversionKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionKinds.Length - 1
conversionKinds(i) = Conversions.Identity
Next
End If
' If this is not a default argument then store the conversion in the conversionKinds.
' For default arguments the conversion is stored below.
If defaultArgument Is Nothing Then
conversionKinds(argIndex) = conversion
End If
End If
' If this is a default argument then add it to the candidate result default arguments.
' Note these arguments are stored by parameter index. Default arguments are missing so they
' may not have an argument index.
If defaultArgument IsNot Nothing Then
If optionalArguments Is Nothing Then
optionalArguments = New OptionalArgument(candidate.Candidate.ParameterCount - 1) {}
End If
optionalArguments(paramIndex) = New OptionalArgument(defaultArgument, conversion, defaultValueDiagnostics.DependenciesBag.ToImmutableArray())
End If
If Not Conversions.IsIdentityConversion(conversionBack.Key) Then
If conversionBackKinds Is Nothing Then
' There should never be a copy back conversion with a default argument.
Debug.Assert(defaultArgument Is Nothing)
conversionBackKinds = New KeyValuePair(Of ConversionKind, MethodSymbol)(arguments.Length - 1) {}
For i As Integer = 0 To conversionBackKinds.Length - 1
conversionBackKinds(i) = Conversions.Identity
Next
End If
conversionBackKinds(argIndex) = conversionBack
End If
Next
Bailout:
If defaultValueDiagnostics IsNot Nothing Then
defaultValueDiagnostics.Free()
End If
If paramArrayItems IsNot Nothing Then
paramArrayItems.Free()
End If
If conversionKinds IsNot Nothing Then
candidate.ConversionsOpt = conversionKinds.AsImmutableOrNull()
End If
If conversionBackKinds IsNot Nothing Then
candidate.ConversionsBackOpt = conversionBackKinds.AsImmutableOrNull()
End If
If optionalArguments IsNot Nothing Then
candidate.OptionalArguments = optionalArguments.AsImmutableOrNull()
End If
If parameterToArgumentMap IsNot Nothing Then
parameterToArgumentMap.Free()
End If
End Sub
''' <summary>
''' Should be in sync with Binder.ReportByRefConversionErrors.
''' </summary>
Private Shared Sub MatchArgumentToByRefParameter(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
ByRef candidate As CandidateAnalysisResult,
argument As BoundExpression,
targetType As TypeSymbol,
binder As Binder,
<Out()> ByRef outConversionKind As KeyValuePair(Of ConversionKind, MethodSymbol),
<Out()> ByRef outConversionBackKind As KeyValuePair(Of ConversionKind, MethodSymbol),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
If argument.IsSupportingAssignment() Then
If argument.IsLValue() AndAlso targetType.IsSameTypeIgnoringAll(argument.Type) Then
outConversionKind = Conversions.Identity
outConversionBackKind = Conversions.Identity
Else
outConversionBackKind = Conversions.Identity
If MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, outConversionKind, asyncLambdaSubToFunctionMismatch, useSiteInfo) Then
' Check copy back conversion
Dim copyBackType = argument.GetTypeOfAssignmentTarget()
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(targetType, copyBackType, useSiteInfo)
outConversionBackKind = conv
If Conversions.NoConversion(conv.Key) Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch ' Possible only with user-defined conversions, I think.
candidate.IgnoreExtensionMethods = False
Else
If Conversions.IsNarrowingConversion(conv.Key) Then
' Similar to Dev10 compiler, we will eliminate candidate requiring narrowing conversions
' if strict semantics is used, exception are candidates that require narrowing only from
' numeric(Constants.
candidate.SetRequiresNarrowingConversion()
Debug.Assert((conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0)
candidate.SetRequiresNarrowingNotFromNumericConstant()
If binder.OptionStrict = OptionStrict.On Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
Return
End If
If targetType.SpecialType <> SpecialType.System_Object Then
candidate.SetRequiresNarrowingNotFromObject()
End If
End If
candidate.RegisterDelegateRelaxationLevel(conv.Key)
End If
End If
End If
Else
' No copy back needed
' If we are inside a lambda in a constructor and are passing ByRef a non-LValue field, which
' would be an LValue field, if it were referred to in the constructor outside of a lambda,
' we need to report an error because the operation will result in a simulated pass by
' ref (through a temp, without a copy back), which might be not the intent.
If binder.Report_ERRID_ReadOnlyInClosure(argument) Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, we do not change IgnoreExtensionMethods flag here.
End If
outConversionBackKind = Conversions.Identity
MatchArgumentToByValParameter(methodOrPropertyGroup, candidate, argument, targetType, binder, outConversionKind, asyncLambdaSubToFunctionMismatch, useSiteInfo)
End If
End Sub
''' <summary>
''' Should be in sync with Binder.ReportByValConversionErrors.
''' </summary>
Private Shared Function MatchArgumentToByValParameter(
methodOrPropertyGroup As BoundMethodOrPropertyGroup,
ByRef candidate As CandidateAnalysisResult,
argument As BoundExpression,
targetType As TypeSymbol,
binder As Binder,
<Out()> ByRef outConversionKind As KeyValuePair(Of ConversionKind, MethodSymbol),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
Optional isDefaultValueArgument As Boolean = False
) As Boolean
outConversionKind = Nothing 'VBConversions.NoConversion
' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics,
' arrays, etc., detect types from unreferenced assemblies, ... ?
If targetType.IsErrorType() Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
' Note, IgnoreExtensionMethods is not cleared.
Return False
End If
Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, binder, useSiteInfo)
outConversionKind = conv
If Conversions.NoConversion(conv.Key) Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
candidate.IgnoreExtensionMethods = False
If (conv.Key And (ConversionKind.DelegateRelaxationLevelMask Or ConversionKind.Lambda)) = (ConversionKind.DelegateRelaxationLevelInvalid Or ConversionKind.Lambda) Then
' Dig through parenthesized
Dim underlying As BoundExpression = argument
While underlying.Kind = BoundKind.Parenthesized AndAlso underlying.Type Is Nothing
underlying = DirectCast(underlying, BoundParenthesized).Expression
End While
Dim unbound = If(underlying.Kind = BoundKind.UnboundLambda, DirectCast(underlying, UnboundLambda), Nothing)
If unbound IsNot Nothing AndAlso Not unbound.IsFunctionLambda AndAlso
(unbound.Flags And SourceMemberFlags.Async) <> 0 AndAlso
targetType.IsDelegateType Then
Dim delegateInvoke As MethodSymbol = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod
Debug.Assert(delegateInvoke IsNot Nothing)
If delegateInvoke IsNot Nothing Then
Dim bound As BoundLambda = unbound.GetBoundLambda(New UnboundLambda.TargetSignature(delegateInvoke))
Debug.Assert(bound IsNot Nothing)
If bound IsNot Nothing AndAlso (bound.MethodConversionKind And MethodConversionKind.AllErrorReasons) = MethodConversionKind.Error_SubToFunction AndAlso
(Not bound.Diagnostics.Diagnostics.HasAnyErrors) Then
If asyncLambdaSubToFunctionMismatch Is Nothing Then
asyncLambdaSubToFunctionMismatch = New HashSet(Of BoundExpression)(ReferenceEqualityComparer.Instance)
End If
asyncLambdaSubToFunctionMismatch.Add(unbound)
End If
End If
End If
End If
Return False
End If
' Characteristics of conversion applied to a default value for an optional parameter shouldn't be used to disambiguate
' between two candidates.
If Conversions.IsNarrowingConversion(conv.Key) Then
' Similar to Dev10 compiler, we will eliminate candidate requiring narrowing conversions
' if strict semantics is used, exception are candidates that require narrowing only from
' numeric constants.
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingConversion()
End If
If (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingNotFromNumericConstant()
End If
If binder.OptionStrict = OptionStrict.On Then
candidate.State = CandidateAnalysisResultState.ArgumentMismatch
Return False
End If
End If
Dim argumentType = argument.Type
If argumentType Is Nothing OrElse
argumentType.SpecialType <> SpecialType.System_Object Then
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingNotFromObject()
End If
End If
ElseIf (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0 Then
' Dev10 overload resolution treats conversions that involve narrowing from numeric constant type
' as narrowing.
If Not isDefaultValueArgument Then
candidate.SetRequiresNarrowingConversion()
candidate.SetRequiresNarrowingNotFromObject()
End If
End If
If Not isDefaultValueArgument Then
candidate.RegisterDelegateRelaxationLevel(conv.Key)
End If
' If we are in attribute context, keep track of candidates that will result in illegal arguments.
' They should be dismissed in favor of other applicable candidates.
If binder.BindingLocation = BindingLocation.Attribute AndAlso
Not candidate.IsIllegalInAttribute AndAlso
Not methodOrPropertyGroup.WasCompilerGenerated AndAlso
methodOrPropertyGroup.Kind = BoundKind.MethodGroup AndAlso
IsWithinAppliedAttributeName(methodOrPropertyGroup.Syntax) AndAlso
DirectCast(candidate.Candidate.UnderlyingSymbol, MethodSymbol).MethodKind = MethodKind.Constructor AndAlso
binder.Compilation.GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(candidate.Candidate.UnderlyingSymbol.ContainingType, useSiteInfo) Then
Debug.Assert(Not argument.HasErrors)
Dim passedExpression As BoundExpression = binder.PassArgumentByVal(argument, conv, targetType, BindingDiagnosticBag.Discarded)
If Not passedExpression.IsConstant Then ' Trying to match native compiler behavior in Semantics::IsValidAttributeConstant
Dim visitor As New Binder.AttributeExpressionVisitor(binder, passedExpression.HasErrors)
visitor.VisitExpression(passedExpression, BindingDiagnosticBag.Discarded)
If visitor.HasErrors Then
candidate.SetIllegalInAttribute()
End If
End If
End If
Return True
End Function
Private Shared Function IsWithinAppliedAttributeName(syntax As SyntaxNode) As Boolean
Dim parent As SyntaxNode = syntax.Parent
While parent IsNot Nothing
If parent.Kind = SyntaxKind.Attribute Then
Return DirectCast(parent, AttributeSyntax).Name.Span.Contains(syntax.Position)
ElseIf TypeOf parent Is ExpressionSyntax OrElse TypeOf parent Is StatementSyntax Then
Exit While
End If
parent = parent.Parent
End While
Return False
End Function
Public Shared Function CanPassToParamArray(
expression As BoundExpression,
targetType As TypeSymbol,
<Out()> ByRef outConvKind As KeyValuePair(Of ConversionKind, MethodSymbol),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
'§11.8.2 Applicable Methods
'If the conversion from the type of the argument expression to the paramarray type is narrowing,
'then the method is only applicable in its expanded form.
outConvKind = Conversions.ClassifyConversion(expression, targetType, binder, useSiteInfo)
' Note, user-defined conversions are acceptable here.
If Conversions.IsWideningConversion(outConvKind.Key) Then
Return True
End If
' Dev10 allows explicitly converted NOTHING as an argument for a ParamArray parameter,
' even if conversion to the array type is narrowing.
If IsNothingLiteral(expression) Then
Debug.Assert(Conversions.IsNarrowingConversion(outConvKind.Key))
Return True
End If
Return False
End Function
''' <summary>
''' Performs an initial pass through the group of candidates and does
''' the following in the process.
''' 1) Eliminates candidates based on the number of supplied arguments and number of supplied generic type arguments.
''' 2) Adds additional entries for expanded ParamArray forms when applicable.
''' 3) Infers method's generic type arguments if needed.
''' 4) Substitutes method's generic type arguments.
''' 5) Eliminates candidates based on shadowing by signature.
''' This partially takes care of §11.8.1 Overloaded Method Resolution, section 7.1.
''' If M is defined in a more derived type than N, eliminate N from the set.
''' 6) Eliminates candidates with identical virtual signatures by applying various shadowing and
''' tie-breaking rules from §11.8.1 Overloaded Method Resolution, section 7.0
''' • If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
''' 7) Takes care of unsupported overloading within the same type for instance methods/properties.
'''
''' Assumptions:
''' 1) Shadowing by name has been already applied.
''' 2) group can include extension methods.
''' 3) group contains original definitions, i.e. method type arguments have not been substituted yet.
''' Exception are extension methods with type parameters substituted based on receiver type rather
''' than based on type arguments supplied at the call site.
''' 4) group contains only accessible candidates.
''' 5) group doesn't contain members involved into unsupported overloading, i.e. differ by casing or custom modifiers only.
''' 6) group does not contain duplicates.
''' 7) All elements of arguments array are Not Nothing, omitted arguments are represented by OmittedArgumentExpression node.
''' </summary>
''' <remarks>
''' This method is destructive to content of the [group] parameter.
''' </remarks>
Private Shared Sub CollectOverloadedCandidates(
binder As Binder,
results As ArrayBuilder(Of CandidateAnalysisResult),
group As ArrayBuilder(Of Candidate),
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
includeEliminatedCandidates As Boolean,
isQueryOperatorInvocation As Boolean,
forceExpandedForm As Boolean,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(results IsNot Nothing)
Debug.Assert(argumentNames.IsDefault OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length))
Dim quickInfo = ArrayBuilder(Of QuickApplicabilityInfo).GetInstance()
Dim sourceModule As ModuleSymbol = binder.SourceModule
For i As Integer = 0 To group.Count - 1
If group(i) Is Nothing Then
Continue For
End If
Dim info As QuickApplicabilityInfo = DoQuickApplicabilityCheck(group(i), typeArguments, arguments, isQueryOperatorInvocation, forceExpandedForm, useSiteInfo)
If info.Candidate Is Nothing Then
Continue For
End If
If info.Candidate.UnderlyingSymbol.ContainingModule Is sourceModule OrElse
info.Candidate.IsExtensionMethod Then
CollectOverloadedCandidate(results, info, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
Continue For
End If
' Deal with VB-illegal overloading in imported types.
' We are trying to avoid doing signature comparison as much as possible and limit them to
' cases when at least one candidate is applicable based on the quick applicability check.
' Similar code exists in overriding checks in OverrideHidingHelper.RemoveMembersWithConflictingAccessibility.
Dim container As Symbol = info.Candidate.UnderlyingSymbol.ContainingSymbol
' If there are more candidates from this type, collect all of them in quickInfo array,
' but keep the applicable candidates at the beginning
quickInfo.Clear()
quickInfo.Add(info)
Dim applicableCount As Integer = If(info.State = CandidateAnalysisResultState.Applicable, 1, 0)
For j As Integer = i + 1 To group.Count - 1
If group(j) Is Nothing OrElse
group(j).IsExtensionMethod Then ' VS2013 ignores illegal overloading for extension methods
Continue For
End If
If container = group(j).UnderlyingSymbol.ContainingSymbol Then
info = DoQuickApplicabilityCheck(group(j), typeArguments, arguments, isQueryOperatorInvocation, forceExpandedForm, useSiteInfo)
group(j) = Nothing
If info.Candidate Is Nothing Then
Continue For
End If
' Keep applicable candidates at the beginning.
If info.State <> CandidateAnalysisResultState.Applicable Then
quickInfo.Add(info)
ElseIf applicableCount = quickInfo.Count Then
quickInfo.Add(info)
applicableCount += 1
Else
quickInfo.Add(quickInfo(applicableCount))
quickInfo(applicableCount) = info
applicableCount += 1
End If
End If
Next
' Now see if any candidates are ambiguous or lose against other candidates in the quickInfo array.
' This loop is destructive to the content of the quickInfo, some applicable candidates could be replaced with
' a "better" candidate, even though that candidate is not applicable, "losers" are deleted, etc.
For k As Integer = 0 To If(applicableCount > 0 OrElse Not includeEliminatedCandidates, applicableCount, quickInfo.Count) - 1
info = quickInfo(k)
If info.Candidate Is Nothing OrElse info.State = CandidateAnalysisResultState.Ambiguous Then
Continue For
End If
#If DEBUG Then
Dim isExtensionMethod As Boolean = info.Candidate.IsExtensionMethod
#End If
Dim firstSymbol As Symbol = info.Candidate.UnderlyingSymbol.OriginalDefinition
If firstSymbol.IsReducedExtensionMethod() Then
firstSymbol = DirectCast(firstSymbol, MethodSymbol).ReducedFrom
End If
For l As Integer = k + 1 To quickInfo.Count - 1
Dim info2 As QuickApplicabilityInfo = quickInfo(l)
If info2.Candidate Is Nothing OrElse info2.State = CandidateAnalysisResultState.Ambiguous Then
Continue For
End If
#If DEBUG Then
Debug.Assert(isExtensionMethod = info2.Candidate.IsExtensionMethod)
#End If
Dim secondSymbol As Symbol = info2.Candidate.UnderlyingSymbol.OriginalDefinition
If secondSymbol.IsReducedExtensionMethod() Then
secondSymbol = DirectCast(secondSymbol, MethodSymbol).ReducedFrom
End If
' The following check should be similar to the one performed by SourceNamedTypeSymbol.CheckForOverloadsErrors
' However, we explicitly ignore custom modifiers here, since this part is NYI for SourceNamedTypeSymbol.
Const significantDifferences As SymbolComparisonResults = SymbolComparisonResults.AllMismatches And
Not SymbolComparisonResults.MismatchesForConflictingMethods
Dim comparisonResults As SymbolComparisonResults = OverrideHidingHelper.DetailedSignatureCompare(
firstSymbol,
secondSymbol,
significantDifferences,
significantDifferences)
' Signature must be considered equal following VB rules.
If comparisonResults = 0 Then
Dim accessibilityCmp As Integer = LookupResult.CompareAccessibilityOfSymbolsConflictingInSameContainer(firstSymbol, secondSymbol)
If accessibilityCmp > 0 Then
' first wins
quickInfo(l) = Nothing
ElseIf accessibilityCmp < 0 Then
' second wins
quickInfo(k) = info2
quickInfo(l) = Nothing
firstSymbol = secondSymbol
info = info2
Else
Debug.Assert(accessibilityCmp = 0)
info = New QuickApplicabilityInfo(info.Candidate, CandidateAnalysisResultState.Ambiguous)
quickInfo(k) = info
quickInfo(l) = New QuickApplicabilityInfo(info2.Candidate, CandidateAnalysisResultState.Ambiguous)
End If
End If
Next
If info.State <> CandidateAnalysisResultState.Ambiguous Then
CollectOverloadedCandidate(results, info, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
ElseIf includeEliminatedCandidates Then
CollectOverloadedCandidate(results, info, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
For l As Integer = k + 1 To quickInfo.Count - 1
Dim info2 As QuickApplicabilityInfo = quickInfo(l)
If info2.Candidate IsNot Nothing AndAlso info2.State = CandidateAnalysisResultState.Ambiguous Then
quickInfo(l) = Nothing
CollectOverloadedCandidate(results, info2, typeArguments, arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
includeEliminatedCandidates, binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
End If
Next
End If
Next
Next
quickInfo.Free()
#If DEBUG Then
group.Clear()
#End If
End Sub
Private Structure QuickApplicabilityInfo
Public ReadOnly Candidate As Candidate
Public ReadOnly State As CandidateAnalysisResultState
Public ReadOnly AppliesToNormalForm As Boolean
Public ReadOnly AppliesToParamArrayForm As Boolean
Public Sub New(
candidate As Candidate,
state As CandidateAnalysisResultState,
Optional appliesToNormalForm As Boolean = True,
Optional appliesToParamArrayForm As Boolean = True
)
Debug.Assert(candidate IsNot Nothing)
Debug.Assert(appliesToNormalForm OrElse appliesToParamArrayForm)
Me.Candidate = candidate
Me.State = state
Me.AppliesToNormalForm = appliesToNormalForm
Me.AppliesToParamArrayForm = appliesToParamArrayForm
End Sub
End Structure
Private Shared Function DoQuickApplicabilityCheck(
candidate As Candidate,
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
isQueryOperatorInvocation As Boolean,
forceExpandedForm As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As QuickApplicabilityInfo
If isQueryOperatorInvocation AndAlso DirectCast(candidate.UnderlyingSymbol, MethodSymbol).IsSub Then
' Subs are never considered as candidates for Query Operators, but method group might have subs in it.
Return Nothing
End If
If candidate.UnderlyingSymbol.HasUnsupportedMetadata Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.HasUnsupportedMetadata)
End If
' If type arguments have been supplied, eliminate procedures that don't have an
' appropriate number of type parameters.
'§11.8.2 Applicable Methods
'Section 4.
' If type arguments have been specified, they are matched against the type parameter list.
' If the two lists do not have the same number of elements, the method is not applicable,
' unless the type argument list is empty.
If typeArguments.Length > 0 AndAlso candidate.Arity <> typeArguments.Length Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.BadGenericArity)
End If
' Eliminate procedures that cannot accept the number of supplied arguments.
Dim requiredCount As Integer
Dim maxCount As Integer
Dim hasParamArray As Boolean
candidate.GetAllParameterCounts(requiredCount, maxCount, hasParamArray)
'§11.8.2 Applicable Methods
'If there are more positional arguments than parameters and the last parameter is not a paramarray,
'the method is not applicable. Otherwise, the paramarray parameter is expanded with parameters of
'the paramarray element type to match the number of positional arguments. If a single argument expression
'matches a paramarray parameter and the type of the argument expression is convertible to both the type of
'the paramarray parameter and the paramarray element type, the method is applicable in both its expanded
'and unexpanded forms, with two exceptions. If the conversion from the type of the argument expression to
'the paramarray type is narrowing, then the method is only applicable in its expanded form. If the argument
'expression is the literal Nothing, then the method is only applicable in its unexpanded form.
If isQueryOperatorInvocation Then
' Query operators require exact match for argument count.
If arguments.Length <> maxCount Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.ArgumentCountMismatch, True, False)
End If
ElseIf arguments.Length < requiredCount OrElse
(Not hasParamArray AndAlso arguments.Length > maxCount) Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.ArgumentCountMismatch, Not hasParamArray, hasParamArray)
End If
Dim candidateUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = candidate.UnderlyingSymbol.GetUseSiteInfo()
useSiteInfo.Add(candidateUseSiteInfo)
If candidateUseSiteInfo.DiagnosticInfo IsNot Nothing Then
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.HasUseSiteError)
End If
' A method with a paramarray can be considered in two forms: in an
' expanded form or in an unexpanded form (i.e. as if the paramarray
' decoration was not specified). It can apply in both forms, as
' in the case of passing Object() to ParamArray x As Object() (because
' Object() converts to both Object() and Object).
' Does the method apply in its unexpanded form? This can only happen if
' either there is no paramarray or if the argument count matches exactly
' (if it's less, then the paramarray is expanded to nothing, if it's more,
' it's expanded to one or more parameters).
Dim applicableInNormalForm As Boolean = False
Dim applicableInParamArrayForm As Boolean = False
If Not hasParamArray OrElse (arguments.Length = maxCount AndAlso Not forceExpandedForm) Then
applicableInNormalForm = True
End If
' How about it's expanded form? It always applies if there's a paramarray.
If hasParamArray AndAlso Not isQueryOperatorInvocation Then
applicableInParamArrayForm = True
End If
Return New QuickApplicabilityInfo(candidate, CandidateAnalysisResultState.Applicable, applicableInNormalForm, applicableInParamArrayForm)
End Function
Private Shared Sub CollectOverloadedCandidate(
results As ArrayBuilder(Of CandidateAnalysisResult),
candidate As QuickApplicabilityInfo,
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
includeEliminatedCandidates As Boolean,
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Select Case candidate.State
Case CandidateAnalysisResultState.HasUnsupportedMetadata
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.HasUnsupportedMetadata))
End If
Case CandidateAnalysisResultState.HasUseSiteError
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.HasUseSiteError))
End If
Case CandidateAnalysisResultState.BadGenericArity
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.BadGenericArity))
End If
Case CandidateAnalysisResultState.ArgumentCountMismatch
Debug.Assert(candidate.AppliesToNormalForm <> candidate.AppliesToParamArrayForm)
If includeEliminatedCandidates Then
Dim candidateAnalysis As New CandidateAnalysisResult(ConstructIfNeedTo(candidate.Candidate, typeArguments), CandidateAnalysisResultState.ArgumentCountMismatch)
If candidate.AppliesToParamArrayForm Then
candidateAnalysis.SetIsExpandedParamArrayForm()
End If
results.Add(candidateAnalysis)
End If
Case CandidateAnalysisResultState.Applicable
Dim candidateAnalysis As CandidateAnalysisResult
If typeArguments.Length > 0 Then
candidateAnalysis = New CandidateAnalysisResult(candidate.Candidate.Construct(typeArguments))
Else
candidateAnalysis = New CandidateAnalysisResult(candidate.Candidate)
End If
#If DEBUG Then
Dim triedToAddSomething As Boolean = False
#End If
If candidate.AppliesToNormalForm Then
#If DEBUG Then
triedToAddSomething = True
#End If
InferTypeArgumentsIfNeedToAndCombineWithExistingCandidates(results, candidateAnalysis, typeArguments,
arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
End If
' How about it's expanded form? It always applies if there's a paramarray.
If candidate.AppliesToParamArrayForm Then
#If DEBUG Then
triedToAddSomething = True
#End If
candidateAnalysis.SetIsExpandedParamArrayForm()
candidateAnalysis.ExpandedParamArrayArgumentsUsed = Math.Max(arguments.Length - candidate.Candidate.ParameterCount + 1, 0)
InferTypeArgumentsIfNeedToAndCombineWithExistingCandidates(results, candidateAnalysis, typeArguments,
arguments, argumentNames,
delegateReturnType, delegateReturnTypeReferenceBoundNode,
binder, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
End If
#If DEBUG Then
Debug.Assert(triedToAddSomething)
#End If
Case CandidateAnalysisResultState.Ambiguous
If includeEliminatedCandidates Then
results.Add(New CandidateAnalysisResult(candidate.Candidate, CandidateAnalysisResultState.Ambiguous))
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(candidate.State)
End Select
End Sub
Private Shared Sub InferTypeArgumentsIfNeedToAndCombineWithExistingCandidates(
results As ArrayBuilder(Of CandidateAnalysisResult),
newCandidate As CandidateAnalysisResult,
typeArguments As ImmutableArray(Of TypeSymbol),
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
binder As Binder,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
If typeArguments.Length = 0 AndAlso newCandidate.Candidate.Arity > 0 Then
'§11.8.2 Applicable Methods
'Section 4.
'If the type argument list is empty, type inferencing is used to try and infer the type argument list.
'If type inferencing fails, the method is not applicable. Otherwise, the type arguments are filled
'in the place of the type parameters in the signature.
If Not InferTypeArguments(newCandidate, arguments, argumentNames, delegateReturnType, delegateReturnTypeReferenceBoundNode,
asyncLambdaSubToFunctionMismatch, binder, useSiteInfo) Then
Debug.Assert(newCandidate.State <> CandidateAnalysisResultState.Applicable)
results.Add(newCandidate)
Return
End If
End If
CombineCandidates(results, newCandidate, arguments.Length, argumentNames, useSiteInfo)
End Sub
''' <summary>
''' Combine new candidate with the list of existing candidates, applying various shadowing and
''' tie-breaking rules. New candidate may or may not be added to the result, some
''' existing candidates may be removed from the result.
''' </summary>
Private Shared Sub CombineCandidates(
results As ArrayBuilder(Of CandidateAnalysisResult),
newCandidate As CandidateAnalysisResult,
argumentCount As Integer,
argumentNames As ImmutableArray(Of String),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(newCandidate.State = CandidateAnalysisResultState.Applicable)
Dim operatorResolution As Boolean = newCandidate.Candidate.IsOperator
Debug.Assert(newCandidate.Candidate.ParameterCount >= argumentCount OrElse newCandidate.IsExpandedParamArrayForm)
Debug.Assert(argumentNames.IsDefault OrElse argumentNames.Length > 0)
Debug.Assert(Not operatorResolution OrElse argumentNames.IsDefault)
Dim i As Integer = 0
While i < results.Count
Dim existingCandidate As CandidateAnalysisResult = results(i)
' Skip over some eliminated candidates, which we will be unable to match signature against.
If existingCandidate.State = CandidateAnalysisResultState.ArgumentCountMismatch OrElse
existingCandidate.State = CandidateAnalysisResultState.BadGenericArity OrElse
existingCandidate.State = CandidateAnalysisResultState.Ambiguous Then
GoTo ContinueCandidatesLoop
End If
' Candidate can't hide another form of itself
If existingCandidate.Candidate Is newCandidate.Candidate Then
Debug.Assert(Not operatorResolution)
GoTo ContinueCandidatesLoop
End If
Dim existingWins As Boolean = False
Dim newWins As Boolean = False
' An overriding method hides the methods it overrides.
' In particular, this rule takes care of bug VSWhidbey #385900. Where type argument inference fails
' for an overriding method due to named argument name mismatch, but succeeds for the overridden method
' from base (the overridden method uses parameter name matching the named argument name). At the end,
' however, the overriding method is called, even though it doesn't have parameter with matching name.
' Also helps with methods overridden by restricted types (TypedReference, etc.), ShadowBasedOnReceiverType
' doesn't do the job for them because it relies on Conversions.ClassifyDirectCastConversion, which
' disallows boxing conversion for restricted types.
If Not operatorResolution AndAlso ShadowBasedOnOverriding(existingCandidate, newCandidate, existingWins, newWins) Then
GoTo DeterminedTheWinner
End If
If existingCandidate.State = CandidateAnalysisResultState.TypeInferenceFailed OrElse existingCandidate.SomeInferenceFailed OrElse
existingCandidate.State = CandidateAnalysisResultState.HasUseSiteError OrElse
existingCandidate.State = CandidateAnalysisResultState.HasUnsupportedMetadata Then
' Won't be able to match signature.
GoTo ContinueCandidatesLoop
End If
' It looks like the following code is applying some tie-breaking rules from section 7 of
' §11.8.1 Overloaded Method Resolution, but not all of them and even skips ParamArrays tie-breaking
' rule in some scenarios. I couldn't find an explanation of this behavior in the spec and
' simply tried to keep this code close to Dev10.
' Spec says that the tie-breaking rules should be applied only for members equally applicable to the argument list.
' [§11.8.1.1 Applicability] defines equally applicable members as follows:
' A member M is considered equally applicable as N if
' 1) their signatures are the same or
' 2) if each parameter type in M is the same as the corresponding parameter type in N.
' We can always check if signature is the same, but we cannot check the second condition in presence
' of named arguments because for them we don't know yet which parameter in M corresponds to which
' parameter in N.
Debug.Assert(existingCandidate.Candidate.ParameterCount >= argumentCount OrElse existingCandidate.IsExpandedParamArrayForm)
If argumentNames.IsDefault Then
Dim existingParamIndex As Integer = 0
Dim newParamIndex As Integer = 0
'CONSIDER: Can we somehow merge this with the complete signature comparison?
For j As Integer = 0 To argumentCount - 1 Step 1
Dim existingType As TypeSymbol = GetParameterTypeFromVirtualSignature(existingCandidate, existingParamIndex)
Dim newType As TypeSymbol = GetParameterTypeFromVirtualSignature(newCandidate, newParamIndex)
If Not existingType.IsSameTypeIgnoringAll(newType) Then
' Signatures are different, shadowing rules do not apply
GoTo ContinueCandidatesLoop
End If
' Advance to the next parameter in the existing candidate,
' unless we are on the expanded ParamArray parameter.
AdvanceParameterInVirtualSignature(existingCandidate, existingParamIndex)
' Advance to the next parameter in the new candidate,
' unless we are on the expanded ParamArray parameter.
AdvanceParameterInVirtualSignature(newCandidate, newParamIndex)
Next
Else
Debug.Assert(Not operatorResolution)
End If
Dim signatureMatch As Boolean = True
' Compare complete signature, with no regard to arguments
If existingCandidate.Candidate.ParameterCount <> newCandidate.Candidate.ParameterCount Then
Debug.Assert(Not operatorResolution)
signatureMatch = False
ElseIf operatorResolution Then
Debug.Assert(argumentCount = existingCandidate.Candidate.ParameterCount)
Debug.Assert(signatureMatch)
' Not lifted operators are preferred over lifted.
If existingCandidate.Candidate.IsLifted Then
If Not newCandidate.Candidate.IsLifted Then
newWins = True
GoTo DeterminedTheWinner
End If
ElseIf newCandidate.Candidate.IsLifted Then
Debug.Assert(Not existingCandidate.Candidate.IsLifted)
existingWins = True
GoTo DeterminedTheWinner
End If
Else
For j As Integer = 0 To existingCandidate.Candidate.ParameterCount - 1 Step 1
Dim existingType As TypeSymbol = existingCandidate.Candidate.Parameters(j).Type
Dim newType As TypeSymbol = newCandidate.Candidate.Parameters(j).Type
If Not existingType.IsSameTypeIgnoringAll(newType) Then
signatureMatch = False
Exit For
End If
Next
End If
If Not argumentNames.IsDefault AndAlso Not signatureMatch Then
' Signatures are different, shadowing rules do not apply
GoTo ContinueCandidatesLoop
End If
If Not signatureMatch Then
Debug.Assert(argumentNames.IsDefault)
' If we have gotten to this point it means that the 2 procedures have equal specificity,
' but signatures that do not match exactly (after generic substitution). This
' implies that we are dealing with differences in shape due to param arrays
' or optional arguments.
' So we look and see if one procedure maps fewer arguments to the
' param array than the other. The one using more, is then shadowed by the one using less.
'• If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
If ShadowBasedOnParamArrayUsage(existingCandidate, newCandidate, existingWins, newWins) Then
GoTo DeterminedTheWinner
End If
Else
' The signatures of the two methods match (after generic parameter substitution).
' This means that param array shadowing doesn't come into play.
' !!! Why? Where is this mentioned in the spec?
End If
Debug.Assert(argumentNames.IsDefault OrElse signatureMatch)
' In presence of named arguments, the following shadowing rules
' cannot be applied if any candidate is extension method because
' full signature match doesn't guarantee equal applicability (in presence of named arguments)
' and instance methods hide by signature regardless applicability rules do not apply to extension methods.
If argumentNames.IsDefault OrElse
Not (existingCandidate.Candidate.IsExtensionMethod OrElse newCandidate.Candidate.IsExtensionMethod) Then
'7.1. If M is defined in a more derived type than N, eliminate N from the set.
' This rule also applies to the types that extension methods are defined on.
'7.2. If M and N are extension methods and the target type of M is a class or
' structure and the target type of N is an interface, eliminate N from the set.
If ShadowBasedOnReceiverType(existingCandidate, newCandidate, existingWins, newWins, useSiteInfo) Then
GoTo DeterminedTheWinner
End If
'7.3. If M and N are extension methods and the target type of M has fewer type
' parameters than the target type of N, eliminate N from the set.
' !!! Note that spec talks about "fewer type parameters", but it is not really about count.
' !!! It is about one refers to a type parameter and the other one doesn't.
If ShadowBasedOnExtensionMethodTargetTypeGenericity(existingCandidate, newCandidate, existingWins, newWins) Then
GoTo DeterminedTheWinner
End If
End If
DeterminedTheWinner:
Debug.Assert(Not existingWins OrElse Not newWins) ' Both cannot win!
If newWins Then
' Remove existing
results.RemoveAt(i)
' We should continue the loop because at least with
' extension methods in the picture, there could be other
' winners and losers in the results.
' Since we removed the element, we should bypass index increment.
Continue While
ElseIf existingWins Then
' New candidate lost, shouldn't add it.
Return
End If
ContinueCandidatesLoop:
i += 1
End While
results.Add(newCandidate)
End Sub
Private Shared Function ShadowBasedOnOverriding(
existingCandidate As CandidateAnalysisResult, newCandidate As CandidateAnalysisResult,
ByRef existingWins As Boolean, ByRef newWins As Boolean
) As Boolean
Dim existingSymbol As Symbol = existingCandidate.Candidate.UnderlyingSymbol
Dim newSymbol As Symbol = newCandidate.Candidate.UnderlyingSymbol
Dim existingType As NamedTypeSymbol = existingSymbol.ContainingType
Dim newType As NamedTypeSymbol = newSymbol.ContainingType
' Optimization: We will rely on ShadowBasedOnReceiverType to give us the
' same effect later on for cases when existingCandidate is
' applicable and neither candidate is from restricted type.
Dim existingIsApplicable As Boolean = (existingCandidate.State = CandidateAnalysisResultState.Applicable)
If existingIsApplicable AndAlso Not existingType.IsRestrictedType() AndAlso Not newType.IsRestrictedType() Then
Return False
End If
' Optimization: symbols from the same type can't override each other.
' ShadowBasedOnReceiverType
If existingType.OriginalDefinition IsNot newType.OriginalDefinition Then
If newCandidate.Candidate.IsOverriddenBy(existingSymbol) Then
existingWins = True
Return True
ElseIf existingIsApplicable AndAlso existingCandidate.Candidate.IsOverriddenBy(newSymbol) Then
newWins = True
Return True
End If
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.5. If M is not an extension method and N is, eliminate N from the set.
''' 7.6. If M and N are extension methods and M was found before N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnExtensionVsInstanceAndPrecedence(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
If left.Candidate.IsExtensionMethod Then
If Not right.Candidate.IsExtensionMethod Then
'7.5.
rightWins = True
Return True
Else
' Both are extensions
If left.Candidate.PrecedenceLevel < right.Candidate.PrecedenceLevel Then
'7.6.
leftWins = True
Return True
ElseIf left.Candidate.PrecedenceLevel > right.Candidate.PrecedenceLevel Then
'7.6.
rightWins = True
Return True
End If
End If
ElseIf right.Candidate.IsExtensionMethod Then
'7.5.
leftWins = True
Return True
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.4. If M is less generic than N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnGenericity(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As Boolean
' §11.8.1.2 Genericity
' A member M is determined to be less generic than a member N as follows:
'
' 1. If, for each pair of matching parameters Mj and Nj, Mj is less or equally generic than Nj
' with respect to type parameters on the method, and at least one Mj is less generic with
' respect to type parameters on the method.
' 2. Otherwise, if for each pair of matching parameters Mj and Nj, Mj is less or equally generic
' than Nj with respect to type parameters on the type, and at least one Mj is less generic with
' respect to type parameters on the type, then M is less generic than N.
'
' A parameter M is considered to be equally generic to a parameter N if their types Mt and Nt
' both refer to type parameters or both don't refer to type parameters. M is considered to be less
' generic than N if Mt does not refer to a type parameter and Nt does.
'
' Extension method type parameters that were fixed during currying are considered type parameters on the type,
' not type parameters on the method.
' At the beginning we will track both method and type type parameters.
Dim track As TypeParameterKind = TypeParameterKind.Both
If Not (left.Candidate.IsGeneric OrElse right.Candidate.IsGeneric) Then
track = track And (Not TypeParameterKind.Method)
End If
If Not ((left.Candidate.UnderlyingSymbol.ContainingType.IsOrInGenericType() OrElse
(left.Candidate.IsExtensionMethod AndAlso Not left.Candidate.FixedTypeParameters.IsNull)) OrElse
(right.Candidate.UnderlyingSymbol.ContainingType.IsOrInGenericType() OrElse
(right.Candidate.IsExtensionMethod AndAlso Not right.Candidate.FixedTypeParameters.IsNull))) Then
track = track And (Not TypeParameterKind.Type)
End If
If track = TypeParameterKind.None Then
Return False ' There is no winner.
End If
#If DEBUG Then
Dim saveTrack = track
#End If
Dim leftHasLeastGenericParameterAgainstMethod As Boolean = False
Dim leftHasLeastGenericParameterAgainstType As Boolean = False
Dim rightHasLeastGenericParameterAgainstMethod As Boolean = False
Dim rightHasLeastGenericParameterAgainstType As Boolean = False
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For i = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Dim leftParamTypeForGenericityCheck As TypeSymbol = Nothing
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex, leftParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(i), leftParamTypeForGenericityCheck)
End If
Dim rightParamType As TypeSymbol
Dim rightParamTypeForGenericityCheck As TypeSymbol = Nothing
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex, rightParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(i), rightParamTypeForGenericityCheck)
End If
' Parameters matching omitted arguments do not participate.
If arguments(i).Kind = BoundKind.OmittedArgument Then
Continue For
End If
If SignatureMismatchForThePurposeOfShadowingBasedOnGenericity(leftParamType, rightParamType, arguments(i), binder) Then
Return False
End If
Dim leftRefersTo As TypeParameterKind = DetectReferencesToGenericParameters(leftParamTypeForGenericityCheck, track, left.Candidate.FixedTypeParameters)
Dim rightRefersTo As TypeParameterKind = DetectReferencesToGenericParameters(rightParamTypeForGenericityCheck, track, right.Candidate.FixedTypeParameters)
' Still looking for less generic with respect to type parameters on the method.
If (track And TypeParameterKind.Method) <> 0 Then
If (leftRefersTo And TypeParameterKind.Method) = 0 Then
If (rightRefersTo And TypeParameterKind.Method) <> 0 Then
leftHasLeastGenericParameterAgainstMethod = True
End If
ElseIf (rightRefersTo And TypeParameterKind.Method) = 0 Then
rightHasLeastGenericParameterAgainstMethod = True
End If
' If both won at least once, neither candidate is less generic with respect to type parameters on the method.
' Stop checking for this.
If leftHasLeastGenericParameterAgainstMethod AndAlso rightHasLeastGenericParameterAgainstMethod Then
track = track And (Not TypeParameterKind.Method)
End If
End If
' Still looking for less generic with respect to type parameters on the type.
If (track And TypeParameterKind.Type) <> 0 Then
If (leftRefersTo And TypeParameterKind.Type) = 0 Then
If (rightRefersTo And TypeParameterKind.Type) <> 0 Then
leftHasLeastGenericParameterAgainstType = True
End If
ElseIf (rightRefersTo And TypeParameterKind.Type) = 0 Then
rightHasLeastGenericParameterAgainstType = True
End If
' If both won at least once, neither candidate is less generic with respect to type parameters on the type.
' Stop checking for this.
If leftHasLeastGenericParameterAgainstType AndAlso rightHasLeastGenericParameterAgainstType Then
track = track And (Not TypeParameterKind.Type)
End If
End If
' Are we still looking for a winner?
If track = TypeParameterKind.None Then
#If DEBUG Then
Debug.Assert((saveTrack And TypeParameterKind.Method) = 0 OrElse (leftHasLeastGenericParameterAgainstMethod AndAlso rightHasLeastGenericParameterAgainstMethod))
Debug.Assert((saveTrack And TypeParameterKind.Type) = 0 OrElse (leftHasLeastGenericParameterAgainstType AndAlso rightHasLeastGenericParameterAgainstType))
#End If
Return False ' There is no winner.
End If
Next
If leftHasLeastGenericParameterAgainstMethod Then
If Not rightHasLeastGenericParameterAgainstMethod Then
leftWins = True
Return True
End If
ElseIf rightHasLeastGenericParameterAgainstMethod Then
rightWins = True
Return True
End If
If leftHasLeastGenericParameterAgainstType Then
If Not rightHasLeastGenericParameterAgainstType Then
leftWins = True
Return True
End If
ElseIf rightHasLeastGenericParameterAgainstType Then
rightWins = True
Return True
End If
Return False
End Function
Private Shared Function SignatureMismatchForThePurposeOfShadowingBasedOnGenericity(
leftParamType As TypeSymbol,
rightParamType As TypeSymbol,
argument As BoundExpression,
binder As Binder
) As Boolean
Debug.Assert(argument.Kind <> BoundKind.OmittedArgument)
' See Semantics::CompareGenericityIsSignatureMismatch in native compiler.
If leftParamType.IsSameTypeIgnoringAll(rightParamType) Then
Return False
Else
' Note: Undocumented rule.
' Different types. We still consider them the same if they are delegates with
' equivalent signatures, after possibly unwrapping Expression(Of D).
Dim leftIsExpressionTree As Boolean, rightIsExpressionTree As Boolean
Dim leftDelegateType As NamedTypeSymbol = leftParamType.DelegateOrExpressionDelegate(binder, leftIsExpressionTree)
Dim rightDelegateType As NamedTypeSymbol = rightParamType.DelegateOrExpressionDelegate(binder, rightIsExpressionTree)
' Native compiler will only compare D1 and D2 for Expression(Of D1) and D2 if the argument is a lambda. It will compare
' Expression(Of D1) and Expression (Of D2) regardless of the argument.
If leftDelegateType IsNot Nothing AndAlso rightDelegateType IsNot Nothing AndAlso
((leftIsExpressionTree = rightIsExpressionTree) OrElse argument.IsAnyLambda()) Then
Dim leftInvoke = leftDelegateType.DelegateInvokeMethod
Dim rightInvoke = rightDelegateType.DelegateInvokeMethod
If leftInvoke IsNot Nothing AndAlso rightInvoke IsNot Nothing AndAlso
MethodSignatureComparer.ParametersAndReturnTypeSignatureComparer.Equals(leftInvoke, rightInvoke) Then
Return False
End If
End If
End If
Return True
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1.3 Depth of genericity
''' </summary>
Private Shared Function ShadowBasedOnDepthOfGenericity(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean,
arguments As ImmutableArray(Of BoundExpression),
binder As Binder
) As Boolean
' §11.8.1.3 Depth of Genericity
' A member M is determined to have greater depth of genericity than a member N if, for each pair
' of matching parameters Mj and Nj, Mj has greater or equal depth of genericity than Nj, and at
' least one Mj has greater depth of genericity. Depth of genericity is defined as follows:
'
' 1. Anything other than a type parameter has greater depth of genericity than a type parameter;
' 2. Recursively, a constructed type has greater depth of genericity than another constructed type
' (with the same number of type arguments) if at least one type argument has greater depth
' of genericity and no type argument has less depth than the corresponding type argument in the other.
' 3. An array type has greater depth of genericity than another array type (with the same number
' of dimensions) if the element type of the first has greater depth of genericity than the
' element type of the second.
'
' For example:
'
' Module Test
' Sub f(Of T)(x As Task(Of T))
' End Sub
' Sub f(Of T)(x As T)
' End Sub
' Sub Main()
' Dim x As Task(Of Integer) = Nothing
' f(x) ' Calls the first overload
' End Sub
' End Module
Dim leftParamIndex As Integer = 0
Dim rightParamIndex As Integer = 0
For i = 0 To arguments.Length - 1 Step 1
Dim leftParamType As TypeSymbol
Dim leftParamTypeForGenericityCheck As TypeSymbol = Nothing
Debug.Assert(left.ArgsToParamsOpt.IsDefault = right.ArgsToParamsOpt.IsDefault)
If left.ArgsToParamsOpt.IsDefault Then
leftParamType = GetParameterTypeFromVirtualSignature(left, leftParamIndex, leftParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(left, leftParamIndex)
Else
leftParamType = GetParameterTypeFromVirtualSignature(left, left.ArgsToParamsOpt(i), leftParamTypeForGenericityCheck)
End If
Dim rightParamType As TypeSymbol
Dim rightParamTypeForGenericityCheck As TypeSymbol = Nothing
If right.ArgsToParamsOpt.IsDefault Then
rightParamType = GetParameterTypeFromVirtualSignature(right, rightParamIndex, rightParamTypeForGenericityCheck)
AdvanceParameterInVirtualSignature(right, rightParamIndex)
Else
rightParamType = GetParameterTypeFromVirtualSignature(right, right.ArgsToParamsOpt(i), rightParamTypeForGenericityCheck)
End If
' Parameters matching omitted arguments do not participate.
If arguments(i).Kind = BoundKind.OmittedArgument Then
Continue For
End If
If SignatureMismatchForThePurposeOfShadowingBasedOnGenericity(leftParamType, rightParamType, arguments(i), binder) Then
Return False ' no winner if the types of the parameter are different
End If
Dim leftParamWins As Boolean = False
Dim rightParamWins As Boolean = False
If CompareParameterTypeGenericDepth(leftParamTypeForGenericityCheck, rightParamTypeForGenericityCheck, leftParamWins, rightParamWins) Then
Debug.Assert(leftParamWins <> rightParamWins)
If leftParamWins Then
If rightWins Then
rightWins = False
Return False ' both won
Else
leftWins = True
End If
Else
If leftWins Then
leftWins = False
Return False ' both won
Else
rightWins = True
End If
End If
End If
Next
Debug.Assert(Not leftWins OrElse Not rightWins)
Return leftWins OrElse rightWins
End Function
''' <summary>
'''
''' </summary>
''' <returns>False if node of candidates wins</returns>
Private Shared Function CompareParameterTypeGenericDepth(leftType As TypeSymbol, rightType As TypeSymbol,
ByRef leftWins As Boolean, ByRef rightWins As Boolean) As Boolean
' Depth of genericity is defined as follows:
' 1. Anything other than a type parameter has greater depth of genericity than a type parameter;
' 2. Recursively, a constructed type has greater depth of genericity than another constructed
' type (with the same number of type arguments) if at least one type argument has greater
' depth of genericity and no type argument has less depth than the corresponding type
' argument in the other.
' 3. An array type has greater depth of genericity than another array type (with the same number
' of dimensions) if the element type of the first has greater depth of genericity than the
' element type of the second.
'
' For exact rules see Dev11 OverloadResolution.cpp: void Semantics::CompareParameterTypeGenericDepth(...)
If leftType Is rightType Then
Return False
End If
If leftType.IsTypeParameter Then
If rightType.IsTypeParameter Then
' Both type parameters => no winner
Return False
Else
' Left is a type parameter, but right is not
rightWins = True
Return True
End If
ElseIf rightType.IsTypeParameter Then
' Right is a type parameter, but left is not
leftWins = True
Return True
End If
' None of the two is a type parameter
If leftType.IsArrayType AndAlso rightType.IsArrayType Then
' Both are arrays
Dim leftArray = DirectCast(leftType, ArrayTypeSymbol)
Dim rightArray = DirectCast(rightType, ArrayTypeSymbol)
If leftArray.HasSameShapeAs(rightArray) Then
Return CompareParameterTypeGenericDepth(leftArray.ElementType, rightArray.ElementType, leftWins, rightWins)
End If
End If
' Both are generics
If leftType.Kind = SymbolKind.NamedType AndAlso rightType.Kind = SymbolKind.NamedType Then
Dim leftNamedType = DirectCast(leftType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol)
Dim rightNamedType = DirectCast(rightType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol)
' If their arities are equal
If leftNamedType.Arity = rightNamedType.Arity Then
Dim leftTypeArguments As ImmutableArray(Of TypeSymbol) = leftNamedType.TypeArgumentsNoUseSiteDiagnostics
Dim rightTypeArguments As ImmutableArray(Of TypeSymbol) = rightNamedType.TypeArgumentsNoUseSiteDiagnostics
For i = 0 To leftTypeArguments.Length - 1
Dim leftArgWins As Boolean = False
Dim rightArgWins As Boolean = False
If CompareParameterTypeGenericDepth(leftTypeArguments(i), rightTypeArguments(i), leftArgWins, rightArgWins) Then
Debug.Assert(leftArgWins <> rightArgWins)
If leftArgWins Then
If rightWins Then
rightWins = False
Return False
Else
leftWins = True
End If
Else
If leftWins Then
leftWins = False
Return False
Else
rightWins = True
End If
End If
End If
Next
Debug.Assert(Not leftWins OrElse Not rightWins)
Return leftWins OrElse rightWins
End If
End If
Return False
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.3. If M and N are extension methods and the target type of M has fewer type
''' parameters than the target type of N, eliminate N from the set.
''' !!! Note that spec talks about "fewer type parameters", but it is not really about count.
''' !!! It is about one refers to a type parameter and the other one doesn't.
''' </summary>
Private Shared Function ShadowBasedOnExtensionMethodTargetTypeGenericity(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
If Not left.Candidate.IsExtensionMethod OrElse Not right.Candidate.IsExtensionMethod Then
Return False
End If
'!!! Note, the spec does not mention this explicitly, but this rule applies only if receiver type
'!!! is the same for both methods.
If Not left.Candidate.ReceiverType.IsSameTypeIgnoringAll(right.Candidate.ReceiverType) Then
Return False
End If
' Only interested in method type parameters.
Dim leftRefersToATypeParameter = DetectReferencesToGenericParameters(left.Candidate.ReceiverTypeDefinition,
TypeParameterKind.Method,
BitVector.Null)
' Only interested in method type parameters.
Dim rightRefersToATypeParameter = DetectReferencesToGenericParameters(right.Candidate.ReceiverTypeDefinition,
TypeParameterKind.Method,
BitVector.Null)
If (leftRefersToATypeParameter And TypeParameterKind.Method) <> 0 Then
If (rightRefersToATypeParameter And TypeParameterKind.Method) = 0 Then
rightWins = True
Return True
End If
ElseIf (rightRefersToATypeParameter And TypeParameterKind.Method) <> 0 Then
leftWins = True
Return True
End If
Return False
End Function
<Flags()>
Private Enum TypeParameterKind
None = 0
Method = 1 << 0
Type = 1 << 1
Both = Method Or Type
End Enum
Private Shared Function DetectReferencesToGenericParameters(
symbol As NamedTypeSymbol,
track As TypeParameterKind,
methodTypeParametersToTreatAsTypeTypeParameters As BitVector
) As TypeParameterKind
Dim result As TypeParameterKind = TypeParameterKind.None
Do
If symbol Is symbol.OriginalDefinition Then
If (track And TypeParameterKind.Type) = 0 Then
Return result
End If
If symbol.Arity > 0 Then
Return result Or TypeParameterKind.Type
End If
Else
For Each argument As TypeSymbol In symbol.TypeArgumentsNoUseSiteDiagnostics
result = result Or DetectReferencesToGenericParameters(argument, track,
methodTypeParametersToTreatAsTypeTypeParameters)
If (result And track) = track Then
Return result
End If
Next
End If
symbol = symbol.ContainingType
Loop While symbol IsNot Nothing
Return result
End Function
Private Shared Function DetectReferencesToGenericParameters(
symbol As TypeParameterSymbol,
track As TypeParameterKind,
methodTypeParametersToTreatAsTypeTypeParameters As BitVector
) As TypeParameterKind
If symbol.ContainingSymbol.Kind = SymbolKind.NamedType Then
If (track And TypeParameterKind.Type) <> 0 Then
Return TypeParameterKind.Type
End If
Else
If methodTypeParametersToTreatAsTypeTypeParameters.IsNull OrElse Not methodTypeParametersToTreatAsTypeTypeParameters(symbol.Ordinal) Then
If (track And TypeParameterKind.Method) <> 0 Then
Return TypeParameterKind.Method
End If
Else
If (track And TypeParameterKind.Type) <> 0 Then
Return TypeParameterKind.Type
End If
End If
End If
Return TypeParameterKind.None
End Function
Private Shared Function DetectReferencesToGenericParameters(
this As TypeSymbol,
track As TypeParameterKind,
methodTypeParametersToTreatAsTypeTypeParameters As BitVector
) As TypeParameterKind
Select Case this.Kind
Case SymbolKind.TypeParameter
Return DetectReferencesToGenericParameters(DirectCast(this, TypeParameterSymbol), track,
methodTypeParametersToTreatAsTypeTypeParameters)
Case SymbolKind.ArrayType
Return DetectReferencesToGenericParameters(DirectCast(this, ArrayTypeSymbol).ElementType, track,
methodTypeParametersToTreatAsTypeTypeParameters)
Case SymbolKind.NamedType, SymbolKind.ErrorType
Return DetectReferencesToGenericParameters(DirectCast(this, NamedTypeSymbol), track,
methodTypeParametersToTreatAsTypeTypeParameters)
Case Else
Throw ExceptionUtilities.UnexpectedValue(this.Kind)
End Select
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' 7.1. If M is defined in a more derived type than N, eliminate N from the set.
''' This rule also applies to the types that extension methods are defined on.
''' 7.2. If M and N are extension methods and the target type of M is a class or
''' structure and the target type of N is an interface, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnReceiverType(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
Dim leftType = left.Candidate.ReceiverType
Dim rightType = right.Candidate.ReceiverType
If Not leftType.IsSameTypeIgnoringAll(rightType) Then
If DoesReceiverMatchInstance(leftType, rightType, useSiteInfo) Then
leftWins = True
Return True
ElseIf DoesReceiverMatchInstance(rightType, leftType, useSiteInfo) Then
rightWins = True
Return True
End If
End If
Return False
End Function
''' <summary>
''' For a receiver to match an instance, more or less, the type of that instance has to be convertible
''' to the type of the receiver with the same bit-representation (i.e. identity on value-types
''' and reference-convertibility on reference types).
''' Actually, we don't include the reference-convertibilities that seem nonsensical, e.g. enum() to underlyingtype()
''' We do include inheritance, implements and variance conversions amongst others.
''' </summary>
Public Shared Function DoesReceiverMatchInstance(instanceType As TypeSymbol, receiverType As TypeSymbol, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean
Return Conversions.HasWideningDirectCastConversionButNotEnumTypeConversion(instanceType, receiverType, useSiteInfo)
End Function
''' <summary>
''' Implements shadowing based on
''' §11.8.1 Overloaded Method Resolution.
''' • If M has fewer parameters from an expanded paramarray than N, eliminate N from the set.
''' </summary>
Private Shared Function ShadowBasedOnParamArrayUsage(
left As CandidateAnalysisResult, right As CandidateAnalysisResult,
ByRef leftWins As Boolean, ByRef rightWins As Boolean
) As Boolean
If left.IsExpandedParamArrayForm Then
If right.IsExpandedParamArrayForm Then
If left.ExpandedParamArrayArgumentsUsed > right.ExpandedParamArrayArgumentsUsed Then
rightWins = True
Return True
ElseIf left.ExpandedParamArrayArgumentsUsed < right.ExpandedParamArrayArgumentsUsed Then
leftWins = True
Return True
End If
Else
rightWins = True
Return True
End If
ElseIf right.IsExpandedParamArrayForm Then
leftWins = True
Return True
End If
Return False
End Function
Friend Shared Function GetParameterTypeFromVirtualSignature(
ByRef candidate As CandidateAnalysisResult,
paramIndex As Integer
) As TypeSymbol
Dim paramType As TypeSymbol = candidate.Candidate.Parameters(paramIndex).Type
If candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
paramType.Kind = SymbolKind.ArrayType Then
paramType = DirectCast(paramType, ArrayTypeSymbol).ElementType
End If
Return paramType
End Function
Private Shared Function GetParameterTypeFromVirtualSignature(
ByRef candidate As CandidateAnalysisResult,
paramIndex As Integer,
ByRef typeForGenericityCheck As TypeSymbol
) As TypeSymbol
Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex)
Dim paramForGenericityCheck = param.OriginalDefinition
If paramForGenericityCheck.ContainingSymbol.Kind = SymbolKind.Method Then
Dim method = DirectCast(paramForGenericityCheck.ContainingSymbol, MethodSymbol)
If method.IsReducedExtensionMethod Then
paramForGenericityCheck = method.ReducedFrom.Parameters(paramIndex + 1)
End If
End If
Dim paramType As TypeSymbol = param.Type
typeForGenericityCheck = paramForGenericityCheck.Type
If candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso
paramType.Kind = SymbolKind.ArrayType Then
paramType = DirectCast(paramType, ArrayTypeSymbol).ElementType
typeForGenericityCheck = DirectCast(typeForGenericityCheck, ArrayTypeSymbol).ElementType
End If
Return paramType
End Function
Friend Shared Sub AdvanceParameterInVirtualSignature(
ByRef candidate As CandidateAnalysisResult,
ByRef paramIndex As Integer
)
If Not (candidate.IsExpandedParamArrayForm AndAlso
paramIndex = candidate.Candidate.ParameterCount - 1) Then
paramIndex += 1
End If
End Sub
Private Shared Function InferTypeArguments(
ByRef candidate As CandidateAnalysisResult,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
binder As Binder,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As Boolean
Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Nothing
Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing
BuildParameterToArgumentMap(candidate, arguments, argumentNames, parameterToArgumentMap, paramArrayItems)
If candidate.State = CandidateAnalysisResultState.Applicable Then
Dim typeArguments As ImmutableArray(Of TypeSymbol) = Nothing
Dim inferenceLevel As TypeArgumentInference.InferenceLevel = TypeArgumentInference.InferenceLevel.None
Dim allFailedInferenceIsDueToObject As Boolean = False
Dim someInferenceFailed As Boolean = False
Dim inferenceErrorReasons As InferenceErrorReasons = InferenceErrorReasons.Other
Dim inferredTypeByAssumption As BitVector = Nothing
Dim typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken) = Nothing
If TypeArgumentInference.Infer(DirectCast(candidate.Candidate.UnderlyingSymbol, MethodSymbol),
arguments, parameterToArgumentMap, paramArrayItems,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
typeArguments:=typeArguments,
inferenceLevel:=inferenceLevel,
someInferenceFailed:=someInferenceFailed,
allFailedInferenceIsDueToObject:=allFailedInferenceIsDueToObject,
inferenceErrorReasons:=inferenceErrorReasons,
inferredTypeByAssumption:=inferredTypeByAssumption,
typeArgumentsLocation:=typeArgumentsLocation,
asyncLambdaSubToFunctionMismatch:=asyncLambdaSubToFunctionMismatch,
useSiteInfo:=useSiteInfo,
diagnostic:=candidate.TypeArgumentInferenceDiagnosticsOpt) Then
candidate.SetInferenceLevel(inferenceLevel)
candidate.Candidate = candidate.Candidate.Construct(typeArguments)
' Need check for Option Strict and warn if parameter type is an assumed inferred type.
If binder.OptionStrict = OptionStrict.On AndAlso Not inferredTypeByAssumption.IsNull Then
For i As Integer = 0 To typeArguments.Length - 1 Step 1
If inferredTypeByAssumption(i) Then
Dim diagnostics = candidate.TypeArgumentInferenceDiagnosticsOpt
If diagnostics Is Nothing Then
diagnostics = BindingDiagnosticBag.Create(withDiagnostics:=True, useSiteInfo.AccumulatesDependencies)
candidate.TypeArgumentInferenceDiagnosticsOpt = diagnostics
End If
Binder.ReportDiagnostic(diagnostics,
typeArgumentsLocation(i),
ERRID.WRN_TypeInferenceAssumed3,
candidate.Candidate.TypeParameters(i),
DirectCast(candidate.Candidate.UnderlyingSymbol, MethodSymbol).OriginalDefinition,
typeArguments(i))
End If
Next
End If
Else
candidate.State = CandidateAnalysisResultState.TypeInferenceFailed
If someInferenceFailed Then
candidate.SetSomeInferenceFailed()
End If
If allFailedInferenceIsDueToObject Then
candidate.SetAllFailedInferenceIsDueToObject()
If Not candidate.Candidate.IsExtensionMethod Then
candidate.IgnoreExtensionMethods = True
End If
End If
candidate.SetInferenceErrorReasons(inferenceErrorReasons)
candidate.NotInferredTypeArguments = BitVector.Create(typeArguments.Length)
For i As Integer = 0 To typeArguments.Length - 1 Step 1
If typeArguments(i) Is Nothing Then
candidate.NotInferredTypeArguments(i) = True
End If
Next
End If
Else
candidate.SetSomeInferenceFailed()
End If
If paramArrayItems IsNot Nothing Then
paramArrayItems.Free()
End If
If parameterToArgumentMap IsNot Nothing Then
parameterToArgumentMap.Free()
End If
Return (candidate.State = CandidateAnalysisResultState.Applicable)
End Function
Private Shared Function ConstructIfNeedTo(candidate As Candidate, typeArguments As ImmutableArray(Of TypeSymbol)) As Candidate
If typeArguments.Length > 0 Then
Return candidate.Construct(typeArguments)
End If
Return candidate
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./README.md | <p align="center">
<img width="450" src="https://user-images.githubusercontent.com/46729679/109719841-17b7dd00-7b5e-11eb-8f5e-87eb2d4d1be9.png" alt="Roslyn logo">
</p>
<h1 align="center">The .NET Compiler Platform</h1>
<p align="center"><a href="https://gitter.im/dotnet/roslyn?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" rel="nofollow"><img src="https://camo.githubusercontent.com/5dbac0213da25c445bd11f168587c11a200ba153ef3014e8408e462e410169b3/68747470733a2f2f6261646765732e6769747465722e696d2f4a6f696e253230436861742e737667" alt="Join the chat at https://gitter.im/dotnet/roslyn" data-canonical-src="https://badges.gitter.im/Join%20Chat.svg" style="max-width:100%;"></a> <a href="http://aka.ms/discord-csharp-roslyn" rel="nofollow"><img src="https://camo.githubusercontent.com/1ea6a95121cbf4179d411e853681838825392a7f0ae7e6bb1e03f4ea37c8fd5d/68747470733a2f2f646973636f72646170702e636f6d2f6170692f6775696c64732f3134333836373833393238323032303335322f7769646765742e706e67" alt="Chat on Discord" data-canonical-src="https://discordapp.com/api/guilds/143867839282020352/widget.png" style="max-width:100%;"></a></p>
Roslyn is the open-source implementation of both the C# and Visual Basic compilers with an API surface for building code analysis tools.
### C# and Visual Basic Language Feature Suggestions
If you want to suggest a new feature for the C# or Visual Basic languages go here:
- [dotnet/csharplang](https://github.com/dotnet/csharplang) for C# specific issues
- [dotnet/vblang](https://github.com/dotnet/vblang) for VB-specific features
- [dotnet/csharplang](https://github.com/dotnet/csharplang) for features that affect both languages
### Contributing
All work on the C# and Visual Basic compiler happens directly on [GitHub](https://github.com/dotnet/roslyn). Both core team members and external contributors send pull requests which go through the same review process.
If you are interested in fixing issues and contributing directly to the code base, a great way to get started is to ask some questions on [GitHub Discussions](https://github.com/dotnet/roslyn/discussions)! Then check out our [contributing guide](https://github.com/dotnet/roslyn/blob/main/docs/contributing/Building%2C%20Debugging%2C%20and%20Testing%20on%20Windows.md) which covers the following:
- [Coding guidelines](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Contributing-Code.md)
- [The development workflow, including debugging and running tests](https://github.com/dotnet/roslyn/blob/main/docs/contributing/Building%2C%20Debugging%2C%20and%20Testing%20on%20Windows.md)
- [Submitting pull requests](https://github.com/dotnet/roslyn/blob/main/CONTRIBUTING.md)
- Finding a bug to fix in the [IDE](https://aka.ms/roslyn-ide-bugs-help-wanted) or [Compiler](https://aka.ms/roslyn-compiler-bugs-help-wanted)
- Finding a feature to implement in the [IDE](https://aka.ms/roslyn-ide-feature-help-wanted) or [Compiler](https://aka.ms/roslyn-compiler-feature-help-wanted)
- Roslyn API suggestions should go through the [API review process](<docs/contributing/API Review Process.md>)
### Community
The Roslyn community can be found on [GitHub Discussions](https://github.com/dotnet/roslyn/discussions), where you can ask questions, voice ideas, and share your projects.
To chat with other community members, you can join the Roslyn [Discord](https://discord.com/invite/tGJvv88) or [Gitter](https://gitter.im/dotnet/roslyn).
Our [Code of Conduct](CODE-OF-CONDUCT.md) applies to all Roslyn community channels and has adopted the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).
### Documentation
Visit [Roslyn Architecture Overview](https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/compiler-api-model) to get started with Roslyn’s API’s.
### NuGet Feeds
**The latest pre-release builds** are available from the following public NuGet feeds:
- [Compiler](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`
- [IDE Services](https://dev.azure.com/azure-public/vside/_packaging?_a=feed&feed=vssdk): `https://pkgs.dev.azure.com/azure-public/vside/_packaging/vssdk/nuget/v3/index.json`
- [.NET SDK](https://dev.azure.com/dnceng/public/_packaging?_a=feed&feed=dotnet5): `https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json`
[//]: # (Begin current test results)
### Continuous Integration status
#### Builds
|Branch|Windows Debug|Windows Release|Unix Debug|
|:--:|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|
#### Desktop Unit Tests
|Branch|Debug x86|Debug x64|Release x86|Release x64|
|:--:|:--:|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|
#### CoreClr Unit Tests
|Branch|Windows Debug|Windows Release|Linux|
|:--:|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|
#### Integration Tests
|Branch|Debug x86|Debug x64|Release x86|Release x64
|:--:|:--:|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main-vs-deps&view=logs)|
#### Misc Tests
|Branch|Determinism|Build Correctness|Source build|Spanish|MacOS|
|:--:|:--:|:--|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|
[//]: # (End current test results)
### .NET Foundation
This project is part of the [.NET Foundation](http://www.dotnetfoundation.org/projects) along with other
projects like [the .NET Runtime](https://github.com/dotnet/runtime/).
| <p align="center">
<img width="450" src="https://user-images.githubusercontent.com/46729679/109719841-17b7dd00-7b5e-11eb-8f5e-87eb2d4d1be9.png" alt="Roslyn logo">
</p>
<h1 align="center">The .NET Compiler Platform</h1>
<p align="center"><a href="https://gitter.im/dotnet/roslyn?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" rel="nofollow"><img src="https://camo.githubusercontent.com/5dbac0213da25c445bd11f168587c11a200ba153ef3014e8408e462e410169b3/68747470733a2f2f6261646765732e6769747465722e696d2f4a6f696e253230436861742e737667" alt="Join the chat at https://gitter.im/dotnet/roslyn" data-canonical-src="https://badges.gitter.im/Join%20Chat.svg" style="max-width:100%;"></a> <a href="http://aka.ms/discord-csharp-roslyn" rel="nofollow"><img src="https://camo.githubusercontent.com/1ea6a95121cbf4179d411e853681838825392a7f0ae7e6bb1e03f4ea37c8fd5d/68747470733a2f2f646973636f72646170702e636f6d2f6170692f6775696c64732f3134333836373833393238323032303335322f7769646765742e706e67" alt="Chat on Discord" data-canonical-src="https://discordapp.com/api/guilds/143867839282020352/widget.png" style="max-width:100%;"></a></p>
Roslyn is the open-source implementation of both the C# and Visual Basic compilers with an API surface for building code analysis tools.
### C# and Visual Basic Language Feature Suggestions
If you want to suggest a new feature for the C# or Visual Basic languages go here:
- [dotnet/csharplang](https://github.com/dotnet/csharplang) for C# specific issues
- [dotnet/vblang](https://github.com/dotnet/vblang) for VB-specific features
- [dotnet/csharplang](https://github.com/dotnet/csharplang) for features that affect both languages
### Contributing
All work on the C# and Visual Basic compiler happens directly on [GitHub](https://github.com/dotnet/roslyn). Both core team members and external contributors send pull requests which go through the same review process.
If you are interested in fixing issues and contributing directly to the code base, a great way to get started is to ask some questions on [GitHub Discussions](https://github.com/dotnet/roslyn/discussions)! Then check out our [contributing guide](https://github.com/dotnet/roslyn/blob/main/docs/contributing/Building%2C%20Debugging%2C%20and%20Testing%20on%20Windows.md) which covers the following:
- [Coding guidelines](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Contributing-Code.md)
- [The development workflow, including debugging and running tests](https://github.com/dotnet/roslyn/blob/main/docs/contributing/Building%2C%20Debugging%2C%20and%20Testing%20on%20Windows.md)
- [Submitting pull requests](https://github.com/dotnet/roslyn/blob/main/CONTRIBUTING.md)
- Finding a bug to fix in the [IDE](https://aka.ms/roslyn-ide-bugs-help-wanted) or [Compiler](https://aka.ms/roslyn-compiler-bugs-help-wanted)
- Finding a feature to implement in the [IDE](https://aka.ms/roslyn-ide-feature-help-wanted) or [Compiler](https://aka.ms/roslyn-compiler-feature-help-wanted)
- Roslyn API suggestions should go through the [API review process](<docs/contributing/API Review Process.md>)
### Community
The Roslyn community can be found on [GitHub Discussions](https://github.com/dotnet/roslyn/discussions), where you can ask questions, voice ideas, and share your projects.
To chat with other community members, you can join the Roslyn [Discord](https://discord.com/invite/tGJvv88) or [Gitter](https://gitter.im/dotnet/roslyn).
Our [Code of Conduct](CODE-OF-CONDUCT.md) applies to all Roslyn community channels and has adopted the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).
### Documentation
Visit [Roslyn Architecture Overview](https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/compiler-api-model) to get started with Roslyn’s API’s.
### NuGet Feeds
**The latest pre-release builds** are available from the following public NuGet feeds:
- [Compiler](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`
- [IDE Services](https://dev.azure.com/azure-public/vside/_packaging?_a=feed&feed=vssdk): `https://pkgs.dev.azure.com/azure-public/vside/_packaging/vssdk/nuget/v3/index.json`
- [.NET SDK](https://dev.azure.com/dnceng/public/_packaging?_a=feed&feed=dotnet5): `https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json`
[//]: # (Begin current test results)
### Continuous Integration status
#### Builds
|Branch|Windows Debug|Windows Release|Unix Debug|
|:--:|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|
#### Desktop Unit Tests
|Branch|Debug x86|Debug x64|Release x86|Release x64|
|:--:|:--:|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|
#### CoreClr Unit Tests
|Branch|Windows Debug|Windows Release|Linux|
|:--:|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|
#### Integration Tests
|Branch|Debug x86|Debug x64|Release x86|Release x64
|:--:|:--:|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=245&branchname=main-vs-deps&view=logs)|
#### Misc Tests
|Branch|Determinism|Build Correctness|Source build|Spanish|MacOS|
|:--:|:--:|:--|:--:|:--:|:--:|
**main**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main&view=logs)|
**main-vs-deps**|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|[](https://dev.azure.com/dnceng/public/_build/latest?definitionId=15&branchname=main-vs-deps&view=logs)|
[//]: # (End current test results)
### .NET Foundation
This project is part of the [.NET Foundation](http://www.dotnetfoundation.org/projects) along with other
projects like [the .NET Runtime](https://github.com/dotnet/runtime/).
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Features/Core/Portable/EditAndContinue/ProjectAnalysisSummary.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.EditAndContinue
{
internal enum ProjectAnalysisSummary
{
/// <summary>
/// Project hasn't been changed.
/// </summary>
NoChanges,
/// <summary>
/// Project contains compilation errors that block EnC analysis.
/// </summary>
CompilationErrors,
/// <summary>
/// Project contains rude edits.
/// </summary>
RudeEdits,
/// <summary>
/// The project only changed in comments, whitespaces, etc. that don't require compilation.
/// </summary>
ValidInsignificantChanges,
/// <summary>
/// The project contains valid changes that require application of a delta.
/// </summary>
ValidChanges
}
}
| // Licensed to the .NET Foundation under one or more 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.EditAndContinue
{
internal enum ProjectAnalysisSummary
{
/// <summary>
/// Project hasn't been changed.
/// </summary>
NoChanges,
/// <summary>
/// Project contains compilation errors that block EnC analysis.
/// </summary>
CompilationErrors,
/// <summary>
/// Project contains rude edits.
/// </summary>
RudeEdits,
/// <summary>
/// The project only changed in comments, whitespaces, etc. that don't require compilation.
/// </summary>
ValidInsignificantChanges,
/// <summary>
/// The project contains valid changes that require application of a delta.
/// </summary>
ValidChanges
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Statements_Tests.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.Reflection
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
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' This class tests binding of various statements; i.e., the code in Binder_Statements.vb
'
' Tests should be added here for every construct that can be bound
' correctly, with a test that compiles, verifies, and runs code for that construct.
' Tests should also be added here for every diagnostic that can be generated.
Public Class Binder_Statements_Tests
Inherits BasicTestBase
<Fact>
Public Sub HelloWorld1()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Module M
Sub Main()
System.Console.WriteLine("Hello, world!")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world!")
End Sub
<Fact>
Public Sub HelloWorld2()
CompileAndVerify(
<compilation name="HelloWorld2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim x as object
x = 42
Console.WriteLine("Hello, world {0} {1}", 135.2.ToString(System.Globalization.CultureInfo.InvariantCulture), x)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world 135.2 42")
End Sub
<Fact>
Public Sub LocalWithSimpleInitialization()
CompileAndVerify(
<compilation name="LocalWithSimpleInitialization">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String = "Hello world"
Console.WriteLine(s)
s = nothing
Console.WriteLine(s)
Dim i As Integer = 1
Console.WriteLine(i)
Dim d As Double = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
]]>)
End Sub
<Fact>
Public Sub LocalAsNew()
CompileAndVerify(
<compilation name="LocalAsNew">
<file name="a.vb">
Imports System
Class C
Sub New (msg as string)
Me.msg = msg
End Sub
Sub Report()
Console.WriteLine(msg)
End Sub
private msg as string
End Class
Module M1
Sub Main()
dim myC as New C("hello")
myC.Report()
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hello")
End Sub
<Fact>
Public Sub LocalAsNewArrayError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class C
Sub New()
End Sub
End Class
Module M1
Sub Main()
' Arrays cannot be declared with 'New'.
dim c1() as new C()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
dim c1() as new C()
~~~
</expected>)
End Sub
<Fact>
Public Sub LocalAsNewArrayError001()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class X
Dim a(), b As New S
End Class
Class X1
Dim a, b() As New S
End Class
Class X2
Dim a, b(3) As New S
End Class
Class X3
Dim a, b As New S(){}
End Class
Structure S
End Structure
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
Dim a(), b As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b() As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b(3) As New S
~~~~
BC30205: End of statement expected.
Dim a, b As New S(){}
~
</expected>)
End Sub
<WorkItem(545766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545766")>
<Fact>
Public Sub LocalSameNameAsOperatorAllowed()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalSameNameAsOperatorAllowed">
<file name="a.vb">
Imports System
Class C
Public Shared Operator IsTrue(ByVal w As C) As Boolean
Dim IsTrue As Boolean = True
Return IsTrue
End Operator
Public Shared Operator IsFalse(ByVal w As C) As Boolean
Dim IsFalse As Boolean = True
Return IsFalse
End Operator
End Class
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub ParameterlessSub()
CompileAndVerify(
<compilation name="ParameterlessSub">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Hello, world")
Console.WriteLine()
Console.WriteLine("Goodbye, world")
End Sub
Sub Main()
Goo
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello, world
Goodbye, world
]]>)
End Sub
<Fact>
Public Sub CallStatement()
CompileAndVerify(
<compilation name="CallStatement">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Call without parameters")
End Sub
Sub Goo(s as string)
Console.WriteLine(s)
End Sub
Function SayHi as string
return "Hi"
End Function
Function One as integer
return 1
End Function
Sub Main()
Goo(SayHi)
goo
call goo
call goo("call with parameters")
dim i = One + One
Console.WriteLine(i)
i = One
Console.WriteLine(i)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hi
Call without parameters
Call without parameters
call with parameters
2
1
]]>)
End Sub
<Fact>
Public Sub CallStatementMethodNotFound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodNotFound">
<file name="a.vb">
Imports System
Module M1
Sub Main()
call goo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'goo' is not declared. It may be inaccessible due to its protection level.
call goo
~~~
</expected>)
End Sub
<WorkItem(538590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538590")>
<Fact>
Public Sub CallStatementNothingAsInvocationExpression_Bug_4247()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Module M1
Sub Main()
Dim myLocalArr as Integer()
Dim myLocalVar as Integer = 42
call myLocalArr(0)
call myLocalVar
call Nothing
call 911
call new Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30454: Expression is not a method.
call myLocalArr(0)
~~~~~~~~~~
BC42104: Variable 'myLocalArr' is used before it has been assigned a value. A null reference exception could result at runtime.
call myLocalArr(0)
~~~~~~~~~~
BC30454: Expression is not a method.
call myLocalVar
~~~~~~~~~~
BC30454: Expression is not a method.
call Nothing
~~~~~~~
BC30454: Expression is not a method.
call 911
~~~
BC30454: Expression is not a method.
call new Integer
~~~~~~~~~~~
</expected>)
End Sub
' related to bug 4247
<Fact>
Public Sub CallStatementNamespaceAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Namespace N1.N2
Module M1
Sub Main()
call N1
call N1.N2
End Sub
End Module
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30112: 'N1' is a namespace and cannot be used as an expression.
call N1
~~
BC30112: 'N1.N2' is a namespace and cannot be used as an expression.
call N1.N2
~~~~~
</expected>)
End Sub
' related to bug 4247
<WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")>
<Fact>
Public Sub CallStatementTypeAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Class Class1
End Class
Module M1
Sub Main()
call Class1
call Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30109: 'Class1' is a class type and cannot be used as an expression.
call Class1
~~~~~~
BC30110: 'Integer' is a structure type and cannot be used as an expression.
call Integer
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AssignmentStatement()
CompileAndVerify(
<compilation name="AssignmentStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String
s = "Hello world"
Console.WriteLine(s)
Dim i As Integer
i = 1
Console.WriteLine(i)
Dim d As Double
d = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
d = i
Console.WriteLine(d)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
1
]]>)
End Sub
<Fact>
Public Sub FieldAssignmentStatement()
CompileAndVerify(
<compilation name="FieldAssignmentStatement">
<file name="a.vb">
Imports System
Class C1
public i as integer
End class
Structure S1
public s as string
End Structure
Module M1
Sub Main()
dim myC as C1 = new C1
myC.i = 10
Console.WriteLine(myC.i)
dim myS as S1 = new S1
myS.s = "a"
Console.WriteLine(MyS.s)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
10
a
]]>)
End Sub
<Fact>
Public Sub AssignmentWithBadLValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AssignmentWithBadLValue">
<file name="a.vb">
Imports System
Module M1
Function f as integer
return 0
End function
Sub s
End Sub
Sub Main()
f = 0
s = 1
dim i as integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30068: Expression is a value and therefore cannot be the target of an assignment.
f = 0
~
BC30068: Expression is a value and therefore cannot be the target of an assignment.
s = 1
~
BC42024: Unused local variable: 'i'.
dim i as integer
~
</expected>)
End Sub
<Fact>
Public Sub MultilineIfStatement1()
CompileAndVerify(
<compilation name="MultilineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
Dim cond2 As Boolean
Dim cond3 As Boolean
cond = True
cond2 = True
cond3 = True
If cond Then
Console.WriteLine("1. ThenPart")
End If
If cond Then
Console.WriteLine("2. ThenPart")
Else
Console.WriteLine("2. ElsePart")
End If
If cond Then
Console.WriteLine("3. ThenPart")
Else If cond2
Console.WriteLine("3. ElseIfPart")
End If
If cond Then
Console.WriteLine("4. ThenPart")
Else If cond2
Console.WriteLine("4. ElseIf1Part")
Else If cond3
Console.WriteLine("4. ElseIf2Part")
Else
Console.WriteLine("4. ElsePart")
End If
cond = False
If cond Then
Console.WriteLine("5. ThenPart")
End If
If cond Then
Console.WriteLine("6. ThenPart")
Else
Console.WriteLine("6. ElsePart")
End If
If cond Then
Console.WriteLine("7. ThenPart")
Else If cond2
Console.WriteLine("7. ElseIfPart")
End If
If cond Then
Console.WriteLine("8. ThenPart")
Else If cond2
Console.WriteLine("8. ElseIf1Part")
Else If cond3
Console.WriteLine("8. ElseIf2Part")
Else
Console.WriteLine("8. ElsePart")
End If
cond2 = false
If cond Then
Console.WriteLine("9. ThenPart")
Else If cond2
Console.WriteLine("9. ElseIfPart")
End If
If cond Then
Console.WriteLine("10. ThenPart")
Else If cond2
Console.WriteLine("10. ElseIf1Part")
Else If cond3
Console.WriteLine("10. ElseIf2Part")
Else
Console.WriteLine("10. ElsePart")
End If
cond3 = false
If cond Then
Console.WriteLine("11. ThenPart")
Else If cond2
Console.WriteLine("11. ElseIf1Part")
Else If cond3
Console.WriteLine("11. ElseIf2Part")
Else
Console.WriteLine("11. ElsePart")
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPart
3. ThenPart
4. ThenPart
6. ElsePart
7. ElseIfPart
8. ElseIf1Part
10. ElseIf2Part
11. ElsePart
]]>)
End Sub
<Fact>
Public Sub SingleLineIfStatement1()
CompileAndVerify(
<compilation name="SingleLineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
cond = True
If cond Then Console.WriteLine("1. ThenPart")
If cond Then Console.WriteLine("2. ThenPartA"): COnsole.WriteLine("2. ThenPartB")
If cond Then Console.WriteLine("3. ThenPartA"): COnsole.WriteLine("3. ThenPartB") Else Console.WriteLine("3. ElsePartA"): Console.WriteLine("3. ElsePartB")
If cond Then Console.WriteLine("4. ThenPart") Else Console.WriteLine("4. ElsePartA"): Console.WriteLine("4. ElsePartB")
If cond Then Console.WriteLine("5. ThenPartA"): Console.WriteLine("5. ThenPartB") Else Console.WriteLine("5. ElsePart")
If cond Then Console.WriteLine("6. ThenPart") Else Console.WriteLine("6. ElsePart")
cond = false
If cond Then Console.WriteLine("7. ThenPart")
If cond Then Console.WriteLine("8. ThenPartA"): COnsole.WriteLine("8. ThenPartB")
If cond Then Console.WriteLine("9. ThenPart"): COnsole.WriteLine("9. ThenPartB") Else Console.WriteLine("9. ElsePartA"): Console.WriteLine("9. ElsePartB")
If cond Then Console.WriteLine("10. ThenPart") Else Console.WriteLine("10. ElsePartA"): Console.WriteLine("10. ElsePartB")
If cond Then Console.WriteLine("11. ThenPartA"): Console.WriteLine("11. ThenPartB") Else Console.WriteLine("11. ElsePart")
If cond Then Console.WriteLine("12. ThenPart") Else Console.WriteLine("12. ElsePart")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPartA
2. ThenPartB
3. ThenPartA
3. ThenPartB
4. ThenPart
5. ThenPartA
5. ThenPartB
6. ThenPart
9. ElsePartA
9. ElsePartB
10. ElsePartA
10. ElsePartB
11. ElsePart
12. ElsePart
]]>)
End Sub
<Fact>
Public Sub DoLoop1()
CompileAndVerify(
<compilation name="DoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do While breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop2()
CompileAndVerify(
<compilation name="DoLoop2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do Until breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop3()
CompileAndVerify(
<compilation name="DoLoop3">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop While breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop4()
CompileAndVerify(
<compilation name="DoLoop4">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop Until breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub WhileLoop1()
CompileAndVerify(
<compilation name="WhileLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
While not breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
End While
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub ExitContinueDoLoop1()
CompileAndVerify(
<compilation name="ExitContinueDoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
dim continueLoop as Boolean
breakLoop = True: continueLoop = true
Do While breakLoop
Console.WriteLine("Stmt1")
If continueLoop Then
Console.WriteLine("Continuing")
continueLoop = false
Continue Do
End If
Console.WriteLine("Exiting")
Exit Do
Console.WriteLine("Stmt2")
Loop
Console.WriteLine("After Loop")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Continuing
Stmt1
Exiting
After Loop
]]>)
End Sub
<Fact>
Public Sub ExitSub()
CompileAndVerify(
<compilation name="ExitSub">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
breakLoop = True
Do While breakLoop
Console.WriteLine("Stmt1")
Console.WriteLine("Exiting")
Exit Sub
Console.WriteLine("Stmt2") 'should not output
Loop
Console.WriteLine("After Loop") 'should not output
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Exiting
]]>)
End Sub
<Fact>
Public Sub ExitFunction()
CompileAndVerify(
<compilation name="ExitFunction">
<file name="a.vb">
Imports System
Module M1
Function Fact(i as integer) as integer
fact = 1
do
if i <= 0 then
exit function
else
fact = i * fact
i = i - 1
end if
loop
End Function
Sub Main()
Console.WriteLine(Fact(0))
Console.WriteLine(Fact(3))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
6
]]>)
End Sub
<Fact>
Public Sub BadExit()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadExit">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Exit Do ' ok
Exit For
Exit Try
Exit Select
Exit While
Loop
Exit Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30096: 'Exit For' can only appear inside a 'For' statement.
Exit For
~~~~~~~~
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
BC30099: 'Exit Select' can only appear inside a 'Select' statement.
Exit Select
~~~~~~~~~~~
BC30097: 'Exit While' can only appear inside a 'While' statement.
Exit While
~~~~~~~~~~
BC30089: 'Exit Do' can only appear inside a 'Do' statement.
Exit Do ' outside loop
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadContinue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadContinue">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Continue Do ' ok
Continue For
Continue While
Loop
Continue Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30783: 'Continue For' can only appear inside a 'For' statement.
Continue For
~~~~~~~~~~~~
BC30784: 'Continue While' can only appear inside a 'While' statement.
Continue While
~~~~~~~~~~~~~~
BC30782: 'Continue Do' can only appear inside a 'Do' statement.
Continue Do ' outside loop
~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Return1()
CompileAndVerify(
<compilation name="Return1">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
F1 = 1
End Function
Function F2 as Integer
if true then
F2 = 2
else
return 3
end if
End Function
Function F3 as Integer
return 3
End Function
Sub S1
return
End Sub
Sub Main()
dim result as integer
result = F1()
Console.WriteLine(result)
result = F2()
Console.WriteLine(result)
result = F3()
Console.WriteLine(result)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
2
3
]]>)
End Sub
<Fact>
Public Sub BadReturn()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadReturn">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
return
End Function
Sub S1
return 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30654: 'Return' statement in a Function, Get, or Operator must return a value.
return
~~~~~~
BC30647: 'Return' statement in a Sub or a Set cannot return a value.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NoReturnUnreachableEnd()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoReturnUnreachableEnd">
<file name="a.vb">
Imports System
Module M1
Function goo() As Boolean
While True
End While
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadArrayInitWithExplicitArraySize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(3) as integer = 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
dim a(3) as integer = 1
~~~~
BC30311: Value of type 'Integer' cannot be converted to 'Integer()'.
dim a(3) as integer = 1
~
</expected>)
End Sub
<Fact>
Public Sub BadArrayWithNegativeSize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-3) as integer
dim b = new integer(-3){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30611: Array dimensions cannot have a negative size.
dim a(-3) as integer
~~
BC30611: Array dimensions cannot have a negative size.
dim b = new integer(-3){}
~~
</expected>)
End Sub
<Fact>
Public Sub ArrayWithMinusOneUpperBound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-1) as integer
dim b = new integer(-1){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(542987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542987")>
<Fact()>
Public Sub MultiDimensionalArrayWithTooFewInitializers()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MultiDimensionalArrayWithTooFewInitializers">
<file name="Program.vb">
Module Program
Sub Main()
Dim x = New Integer(0, 1) {{}}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30567: Array initializer is missing 2 elements.
Dim x = New Integer(0, 1) {{}}
~~
</expected>)
End Sub
<WorkItem(542988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542988")>
<Fact()>
Public Sub Max32ArrayDimensionsAreAllowed()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Max32ArrayDimensionsAreAllowed">
<file name="Program.vb">
Module Program
Sub Main()
Dim z1(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim z2(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim x1 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim x2 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim y1 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
Dim y2 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
End Sub
End Module
</file>
</compilation>).
VerifyDiagnostics(
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"))
End Sub
<Fact>
Public Sub GotoIf()
CompileAndVerify(
<compilation name="GotoIf">
<file name="a.vb">
Imports System
Module M1
Sub GotoIf()
GoTo l1
If False Then
l1:
Console.WriteLine("Jump into If")
End If
End Sub
Sub GotoWhile()
GoTo l1
While False
l1:
Console.WriteLine("Jump into While")
End While
End Sub
Sub GotoDo()
GoTo l1
Do While False
l1:
Console.WriteLine("Jump into Do")
Loop
End Sub
Sub GotoSelect()
Dim i As Integer = 0
GoTo l1
Select Case i
Case 0
l1:
Console.WriteLine("Jump into Select")
End Select
End Sub
Sub Main()
GotoIf()
GotoWhile()
GotoDo()
GotoSelect()
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Jump into If
Jump into While
Jump into Do
Jump into Select
]]>)
End Sub
<Fact()>
Public Sub GotoIntoBlockErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoIntoBlockErrors">
<file name="a.vb">
Imports System
Module M1
Sub GotoFor()
For i as Integer = 0 To 10
l1:
Console.WriteLine()
Next
GoTo l1
End Sub
Sub GotoWith()
Dim c1 = New C()
With c1
l1:
Console.WriteLine()
End With
GoTo l1
End Sub
Sub GotoUsing()
Using c1 as IDisposable = nothing
l1:
Console.WriteLine()
End Using
GoTo l1
End Sub
Sub GotoTry()
Try
l1:
Console.WriteLine()
Finally
End Try
GoTo l1
End Sub
Sub GotoLambda()
Dim x = Sub()
l1:
End Sub
GoTo l1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30757: 'GoTo l1' is not valid because 'l1' is inside a 'For' or 'For Each' statement that does not contain this statement.
GoTo l1
~~
BC30002: Type 'C' is not defined.
Dim c1 = New C()
~
BC30756: 'GoTo l1' is not valid because 'l1' is inside a 'With' statement that does not contain this statement.
GoTo l1
~~
BC36009: 'GoTo l1' is not valid because 'l1' is inside a 'Using' statement that does not contain this statement.
GoTo l1
~~
BC30754: 'GoTo l1' is not valid because 'l1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo l1
~~
BC30132: Label 'l1' is not defined.
GoTo l1
~~
</expected>)
End Sub
<Fact()>
Public Sub GotoDecimalLabels()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoDecimalLabels">
<file name="a.vb">
Imports System
Module M
Sub Main()
1 : Goto &H2
2 : Goto 01
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(543381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543381")>
<Fact()>
Public Sub GotoUndefinedLabel()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoUndefinedLabel">
<file name="a.vb">
Imports System
Class c1
Shared Sub Main()
GoTo lab1
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30132: Label 'lab1' is not defined.
GoTo lab1
~~~~
</expected>)
End Sub
<WorkItem(538574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538574")>
<Fact()>
Public Sub ArrayModifiersOnVariableAndType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ArrayModifiersOnVariableAndType">
<file name="a.vb">
Imports System
Module M1
public a() as integer()
public b(1) as integer()
Sub S1
dim a() as integer() = nothing
dim b(1) as string()
End Sub
Sub S2(x() as integer())
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors>
BC31087: Array modifiers cannot be specified on both a variable and its type.
public a() as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
public b(1) as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim a() as integer() = nothing
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim b(1) as string()
~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
Sub S2(x() as integer())
~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Bug6663()
' Test dependent on referenced mscorlib, but NOT system.dll.
Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="Bug6663">
<file name="a.vb">
Imports System
Module Program
Sub Main()
Console.WriteLine("".ToString() = "".ToString())
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe)
CompileAndVerify(comp, expectedOutput:="True")
End Sub
<WorkItem(540390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540390")>
<Fact()>
Public Sub Bug6637()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Imports System
Module M1
Sub Main()
Dim a(3) As Integer
For i = 0 To 3
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = 0 To 3
~
</expected>)
End Sub
<WorkItem(540412, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540412")>
<Fact()>
Public Sub Bug6662()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Class C
Shared Sub M()
For i = Nothing To 10
Dim d as System.Action = Sub() i = i + 1
Next
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = Nothing To 10
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
</expected>)
End Sub
<WorkItem(542801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542801")>
<Fact()>
Public Sub ExtTryFromFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Class BaseClass
Function Method() As String
Dim x = New Integer() {}
Try
Exit Try
Catch ex1 As Exception When True
Exit Try
Finally
Exit Try
End Try
Return "x"
End Function
End Class
Class DerivedClass
Inherits BaseClass
Shared Sub Main()
End Sub
End Class
</file>
</compilation>, {SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotLocal()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotLocal">
<file name="goo.vb">
Module M1
Private ex as System.Exception
Sub Main()
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact(), WorkItem(651622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651622")>
Public Sub Bug651622()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="goo.vb">
Module Module1
Sub Main()
Try
Catch Main
Catch x as System.Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Main' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Main
~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchStatic()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchStatic">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Static ex as exception = nothing
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchUndeclared()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchUndeclared">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Try
' Explicit off does not have effect on Catch - ex is still undefined.
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'ex' is not declared. It may be inaccessible due to its protection level.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Dim ex as String = "qq"
Try
Catch ex
End Try
Try
Catch ex1 as String
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex
~~
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex1 as String
~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotVariableOrParameter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotVariableOrParameter">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Goo
End Sub
Sub Main()
Try
Catch Goo
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Goo' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch ex
Catch ex1 as Exception
Catch
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch
Catch ex
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex
~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When true
Catch ex
' filter does NOT make this reachable.
Catch ex1 as Exception When true
' implicitly this is a "Catch ex As Exception When true" so still unreachable
Catch When true
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception When true
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch When true
~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchOverlapped()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex As SystemException = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When True
Catch ex
' filter does NOT make this reachable.
Catch ex1 As ArgumentException When True
' implicitly this is a "Catch ex As Exception When true"
Catch When True
' this is ok since it is not derived from SystemException
' and catch above has a filter
Catch ex1 As ApplicationException
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'SystemException'.
Catch ex1 As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchShadowing()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Dim field As String
Function Goo(Of T)(ex As Exception) As Exception
Dim ex1 As SystemException = Nothing
Try
Dim ex2 As Exception = nothing
Catch ex As Exception
Catch ex1 As Exception
Catch Goo As ArgumentException When True
' this is ok
Catch ex2 As exception
Dim ex3 As exception = nothing
'this is ok
Catch ex3 As ApplicationException
' this is ok
Catch field As Exception
End Try
return nothing
End Function
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30734: 'ex' is already declared as a parameter of this method.
Catch ex As Exception
~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 As Exception
~~~~~~~~~~~~~~~~~~~~~~
BC30616: Variable 'ex1' hides a variable in an enclosing block.
Catch ex1 As Exception
~~~
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'Exception'.
Catch Goo As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30290: Local variable cannot have the same name as the function containing it.
Catch Goo As ArgumentException When True
~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex2 As exception
~~~~~~~~~~~~~~~~~~~~~~
BC42029: 'Catch' block never reached, because 'ApplicationException' inherits from 'Exception'.
Catch ex3 As ApplicationException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch field As Exception
~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(837820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837820")>
<Fact()>
Public Sub CatchShadowingGeneric()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Class cls3(Of T As NullReferenceException)
Sub scen3()
Try
Catch ex As T
Catch ex As NullReferenceException
End Try
End Sub
Sub scen4()
Try
Catch ex As NullReferenceException
'COMPILEWarning: BC42029 ,"Catch ex As T"
Catch ex As T
End Try
End Sub
End Class
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'T' inherits from 'NullReferenceException'.
Catch ex As T
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoOutOfFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoOutOfFinally">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
l1:
Try
Finally
try
goto l1
catch
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
goto l1
~~
</expected>)
End Sub
<Fact()>
Public Sub BranchOutOfFinally1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BranchOutOfFinally1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
for i as integer = 1 to 10
Try
Finally
continue for
End Try
Next
End Sub
Function Goo() as integer
l1:
Try
Finally
try
return 1
catch
return 1
End Try
End Try
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
continue for
~~~~~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
Catch ex As Exception
l1:
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
l1:
Catch ex As Exception
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInLateAddressOf()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Option Strict Off
Imports System
Module Program
Delegate Sub d1(ByRef x As Integer, y As Integer)
Sub Main()
Dim obj As Object '= New cls1
Dim o As d1 = AddressOf obj.goo
Dim l As Integer = 0
o(l, 2)
Console.WriteLine(l)
End Sub
Class cls1
Shared Sub goo(ByRef x As Integer, y As Integer)
x = 42
Console.WriteLine(x + y)
End Sub
End Class
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim o As d1 = AddressOf obj.goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Dim B as StackOverflowException
Dim C as Exception
Try
A = new ApplicationException
B = new StackOverflowException
C = new Exception
Console.Writeline(A) 'this is ok
Catch ex as NullReferenceException When A.Message isnot nothing
Catch ex as DivideByZeroException
Console.Writeline(B)
Finally
Console.Writeline(C)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Catch ex as NullReferenceException When A.Message isnot nothing
~
BC42104: Variable 'B' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(B)
~
BC42104: Variable 'C' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(C)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
' ok , A is assigned in the filter and in the catch
Catch A When A.Message isnot nothing
Console.Writeline(A)
Catch ex as Exception
A = new ApplicationException
Finally
'error
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter2">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter3">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter4">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
Finally
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Exception
Get
Return New Exception
End Get
End Property
WriteOnly Property Boo As Exception
Set(value As Exception)
End Set
End Property
Sub Main()
Throw Moo
Throw Boo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30524: Property 'Boo' is 'WriteOnly'.
Throw Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly e as new Exception
ReadOnly s as string = "qq"
Sub Main()
Throw e
Throw s
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30665: 'Throw' operand must derive from 'System.Exception'.
Throw s
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RethrowNotInCatch()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RethrowNotInCatch">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Throw
Try
Throw
Catch ex As Exception
Throw
Dim a As Action = Sub()
ex.ToString()
Throw
End Sub
Try
Throw
Catch
Throw
Finally
Throw
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub ForNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Integer
Get
Return 1
End Get
End Property
WriteOnly Property Boo As integer
Set(value As integer)
End Set
End Property
Sub Main()
For Moo = 1 to Moo step Moo
Next
For Boo = 1 to Boo step Boo
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Moo = 1 to Moo step Moo
~~~
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CustomDatatypeForLoop()
Dim source =
<compilation>
<file name="goo.vb"><![CDATA[
Imports System
Module Module1
Public Sub Main()
Dim x As New c1
For x = 1 To 3
Console.WriteLine("hi")
Next
End Sub
End Module
Public Class c1
Public val As Integer
Public Shared Widening Operator CType(ByVal arg1 As Integer) As c1
Console.WriteLine("c1::CType(Integer) As c1")
Dim c As New c1
c.val = arg1 'what happens if this is last statement?
Return c
End Operator
Public Shared Widening Operator CType(ByVal arg1 As c1) As Integer
Console.WriteLine("c1::CType(c1) As Integer")
Dim x As Integer
x = arg1.val
Return x
End Operator
Public Shared Operator +(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::+(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val + arg2.val
Return c
End Operator
Public Shared Operator -(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::-(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val - arg2.val
Return c
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::>=(c1, Integer) As Boolean")
If arg1.val >= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::<=(c1, Integer) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::<=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::>=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::<=(c1, c1) As Boolean")
If arg1.val <= arg2.val Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::>=(c1, c1) As Boolean")
If arg1.val >= arg2.val Then
Return True
Else
Return False
End If
End Operator
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, <![CDATA[c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::-(c1, c1) As c1
c1::>=(c1, c1) As Boolean
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
]]>)
End Sub
<Fact()>
Public Sub SelectCase1_SwitchTable()
CompileAndVerify(
<compilation name="SelectCase1">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case 0
Console.WriteLine("Equal to 0")
Case 1, 2, 3, 4, 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9, 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<Fact()>
Public Sub SelectCase2_IfList()
CompileAndVerify(
<compilation name="SelectCase2">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case Is < 1
Console.WriteLine("Less than 1")
Case 1 To 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Less than 1
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<WorkItem(542156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542156")>
<Fact()>
Public Sub ImplicitVarInRedim()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Option Explicit Off
Module M
Sub Main()
Redim x(10)
System.Console.WriteLine("OK")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="OK")
End Sub
<Fact()>
Public Sub EndStatementsInMethodBodyShouldNotThrowNYI()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EndStatementsInMethodBodyShouldNotThrowNYI">
<file name="a.vb">
Namespace N1
Public Class C1
Public Sub S1()
for i as integer = 23 to 42
next
next
do
loop while true
loop
end if
end select
end try
end using
end while
end with
end synclock
Try
Catch ex As System.Exception
End Try
catch
Try
Catch ex As System.Exception
finally
finally
End Try
finally
End Sub
Public Sub S2
end namespace
end module
end class
end structure
end interface
end enum
end function
end operator
end property
end get
end set
end event
end addhandler
end removehandler
end raiseevent
End Sub
end Class
end Namespace
Namespace N2
Class C2
function F1() as integer
end sub
return 42
end function
End Class
End Namespace
</file>
</compilation>)
Dim expectedErrors1 = <errors>
BC30481: 'Class' statement must end with a matching 'End Class'.
Public Class C1
~~~~~~~~~~~~~~~
BC30092: 'Next' must be preceded by a matching 'For'.
next
~~~~
BC30091: 'Loop' must be preceded by a matching 'Do'.
loop
~~~~
BC30087: 'End If' must be preceded by a matching 'If'.
end if
~~~~~~
BC30088: 'End Select' must be preceded by a matching 'Select Case'.
end select
~~~~~~~~~~
BC30383: 'End Try' must be preceded by a matching 'Try'.
end try
~~~~~~~
BC36007: 'End Using' must be preceded by a matching 'Using'.
end using
~~~~~~~~~
BC30090: 'End While' must be preceded by a matching 'While'.
end while
~~~~~~~~~
BC30093: 'End With' must be preceded by a matching 'With'.
end with
~~~~~~~~
BC30674: 'End SyncLock' must be preceded by a matching 'SyncLock'.
end synclock
~~~~~~~~~~~~
BC30380: 'Catch' cannot appear outside a 'Try' statement.
catch
~~~~~
BC30381: 'Finally' can only appear once in a 'Try' statement.
finally
~~~~~~~
BC30382: 'Finally' cannot appear outside a 'Try' statement.
finally
~~~~~~~
BC30026: 'End Sub' expected.
Public Sub S2
~~~~~~~~~~~~~
BC30622: 'End Module' must be preceded by a matching 'Module'.
end module
~~~~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end class
~~~~~~~~~
BC30621: 'End Structure' must be preceded by a matching 'Structure'.
end structure
~~~~~~~~~~~~~
BC30252: 'End Interface' must be preceded by a matching 'Interface'.
end interface
~~~~~~~~~~~~~
BC30184: 'End Enum' must be preceded by a matching 'Enum'.
end enum
~~~~~~~~
BC30430: 'End Function' must be preceded by a matching 'Function'.
end function
~~~~~~~~~~~~
BC33007: 'End Operator' must be preceded by a matching 'Operator'.
end operator
~~~~~~~~~~~~
BC30431: 'End Property' must be preceded by a matching 'Property'.
end property
~~~~~~~~~~~~
BC30630: 'End Get' must be preceded by a matching 'Get'.
end get
~~~~~~~
BC30632: 'End Set' must be preceded by a matching 'Set'.
end set
~~~~~~~
BC31123: 'End Event' must be preceded by a matching 'Custom Event'.
end event
~~~~~~~~~
BC31124: 'End AddHandler' must be preceded by a matching 'AddHandler' declaration.
end addhandler
~~~~~~~~~~~~~~
BC31125: 'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.
end removehandler
~~~~~~~~~~~~~~~~~
BC31126: 'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.
end raiseevent
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End Sub
~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end Class
~~~~~~~~~
BC30623: 'End Namespace' must be preceded by a matching 'Namespace'.
end Namespace
~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
end sub
~~~~~~~
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub AddHandlerMissingStuff()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload,
AddHandler , del
AddHandler
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30201: Expression expected.
AddHandler v.DomainUnload,
~
BC30201: Expression expected.
AddHandler , del
~
BC30196: Comma expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerUninitialized()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
' no warnings here, variable is used
Dim del As System.EventHandler
' warning here
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'del' is used before it has been assigned a value. A null reference exception could result at runtime.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNotSimple()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' real event with arg list
AddHandler (v.DomainUnload()), del
' not an event
AddHandler (v.GetType()), del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.DomainUnload()), del
~~~~~~~~~~~~~~~~
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.GetType()), del
~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerLambda()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim v = AppDomain.CreateDomain("qq")
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
AppDomain.Unload(v)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42326: Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerNotEvent()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' not an event
AddHandler (v.GetType), del
' not anything
AddHandler v.GetTyp, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30676: 'GetType' is not an event of 'AppDomain'.
AddHandler (v.GetType), del
~~~~~~~
BC30456: 'GetTyp' is not a member of 'AppDomain'.
AddHandler v.GetTyp, del
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNoConversion()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim v = AppDomain.CreateDomain("qq")
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
AddHandler v.DomainUnload, AddressOf H
Dim del as Action(of Object, EventArgs) = Sub(sender As Object, a As EventArgs) Console.Write("unload")
AddHandler v.DomainUnload, del
End Sub
Sub H(i as integer)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36670: Nested sub does not have a signature that is compatible with delegate 'EventHandler'.
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31143: Method 'Public Sub H(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As EventArgs)'.
AddHandler v.DomainUnload, AddressOf H
~
BC30311: Value of type 'Action(Of Object, EventArgs)' cannot be converted to 'EventHandler'.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub LegalGotoCasesTryCatchFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Module M1
Sub Main()
dim x1 = function()
labelOK6:
goto labelok7
if true then
goto labelok6
labelok7:
end if
return 23
end function
dim x2 = sub()
labelOK8:
goto labelok9
if true then
goto labelok8
labelok9:
end if
end sub
Try
Goto LabelOK1
LabelOK1:
Catch
Goto LabelOK2
LabelOK2:
Try
goto LabelOK1
goto LabelOK2:
LabelOK5:
Catch
goto LabelOK1
goto LabelOK5
goto LabelOK2
Finally
End Try
Finally
Goto LabelOK3
LabelOK3:
End Try
Exit Sub
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(543055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543055")>
<Fact()>
Public Sub Bug10583()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Try
GoTo label
GoTo label5
Catch ex As Exception
label:
Finally
label5:
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30754: 'GoTo label' is not valid because 'label' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label
~~~~~
BC30754: 'GoTo label5' is not valid because 'label5' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label5
~~~~~~
</expected>)
End Sub
<WorkItem(543060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543060")>
<Fact()>
Public Sub SelectCase_ImplicitOperator()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Class X
Public Shared Operator =(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Operator <>(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Widening Operator CType(expandedName As String) As X
Return New X()
End Operator
End Class
Sub Main()
End Sub
Sub Test(x As X)
Select Case x
Case "a"
Console.WriteLine("Equal to a")
Case "s"
Console.WriteLine("Equal to A")
Case "3"
Console.WriteLine("Error")
Case "5"
Console.WriteLine("Error")
Case "6"
Console.WriteLine("Error")
Case "9"
Console.WriteLine("Error")
Case "11"
Console.WriteLine("Error")
Case "12"
Console.WriteLine("Error")
Case "13"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
</expected>)
End Sub
<WorkItem(543333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543333")>
<Fact()>
Public Sub Binding_Return_As_Declaration()
Dim compilation1 = CreateCompilationWithMscorlib40(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Class Program
Shared Main()
Return Nothing
End sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30689: Statement cannot appear outside of a method body.
Return Nothing
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End sub
~~~~~~~
</expected>)
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
While (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
While (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
If (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
If (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Try
Catch
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Try
Catch
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Do
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Do
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Else
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Else
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(544465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544465")>
<Fact()>
Public Sub DuplicateNullableLocals()
Dim source =
<compilation>
<file name="a.vb">
Option Explicit Off
Module M
Sub S()
Dim A? As Integer = 1
Dim A? As Integer? = 1
End Sub
End Module
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_CantSpecifyNullableOnBoth, "As Integer?"),
Diagnostic(ERRID.ERR_DuplicateLocals1, "A?").WithArguments("A"))
End Sub
<WorkItem(544431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544431")>
<Fact()>
Public Sub IllegalModifiers()
Dim source =
<compilation>
<file name="a.vb">
Class C
Public Custom E
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfCustomModifier, "Custom"))
End Sub
<Fact()>
Public Sub InvalidCode_ConstInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Const Interface
</file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors>
BC30397: 'Const' is not valid on an Interface declaration.
Const Interface
~~~~~
BC30253: 'Interface' must end with a matching 'End Interface'.
Const Interface
~~~~~~~~~~~~~~~
BC30203: Identifier expected.
Const Interface
~
</errors>)
End Sub
<WorkItem(545196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545196")>
<Fact()>
Public Sub InvalidCode_Event()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Event
</file>
</compilation>)
compilation.AssertTheseParseDiagnostics(<errors>
BC30203: Identifier expected.
Event
~
</errors>)
End Sub
<Fact>
Public Sub StopAndEnd_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim m = GetType(Module1)
System.Console.WriteLine(m.GetMethod("TestEnd").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("TestStop").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("Dummy").GetMethodImplementationFlags)
Try
System.Console.WriteLine("Before End")
TestEnd()
System.Console.WriteLine("After End")
Finally
System.Console.WriteLine("In Finally")
End Try
System.Console.WriteLine("After Try")
End Sub
Sub TestEnd()
End
End Sub
Sub TestStop()
Stop
End Sub
Sub Dummy()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation,
symbolValidator:=Sub(m As ModuleSymbol)
Dim m1 = m.ContainingAssembly.GetTypeByMetadataName("Module1")
Assert.Equal(MethodImplAttributes.Managed Or MethodImplAttributes.NoInlining Or MethodImplAttributes.NoOptimization,
DirectCast(m1.GetMembers("TestEnd").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("TestStop").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("Dummy").Single(), PEMethodSymbol).ImplementationAttributes)
End Sub)
compilationVerifier.VerifyIL("Module1.TestEnd",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp()"
IL_0005: ret
}
]]>)
compilationVerifier.VerifyIL("Module1.TestStop",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub System.Diagnostics.Debugger.Break()"
IL_0005: ret
}
]]>)
compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.DynamicallyLinkedLibrary))
AssertTheseDiagnostics(compilation,
<expected>
BC30615: 'End' statement cannot be used in class library projects.
End
~~~
</expected>)
End Sub
<Fact>
Public Sub StopAndEnd_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim x As Object
Dim y As Object
Stop
x.ToString()
End
y.ToString()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
x.ToString()
~
</expected>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub StopAndEnd_3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public state As Integer = 0
Public Sub Main()
On Error GoTo handler
Throw New NullReferenceException()
Stop
Console.WriteLine("Done")
Return
handler:
Console.WriteLine(Microsoft.VisualBasic.Information.Err.GetException().GetType())
If state = 1 Then
Resume
End If
Resume Next
End Sub
End Module
Namespace System.Diagnostics
Public Class Debugger
Public Shared Sub Break()
Console.WriteLine("In Break")
Select Case Module1.state
Case 0, 1
Module1.state += 1
Case Else
Console.WriteLine("Test issue!!!")
Return
End Select
Throw New NotSupportedException()
End Sub
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
System.NullReferenceException
In Break
System.NotSupportedException
In Break
System.NotSupportedException
Done
]]>)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithSingleLineIf()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then End Else Console.WriteLine("Test")
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithSingleLineIfWithDll()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then End Else Console.WriteLine("Test")
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC30615: 'End' statement cannot be used in class library projects.
If True Then End Else Console.WriteLine("Test")
~~~
</expected>)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithMultiLineIf()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then
End
Else
Console.WriteLine("Test")
End If
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(660010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/660010")>
<Fact>
Public Sub Regress660010()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Inherits value
End C
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=XmlReferences)
AssertTheseDiagnostics(compilation,
<expected>
BC30481: 'Class' statement must end with a matching 'End Class'.
Class C
~~~~~~~
BC30002: Type 'value' is not defined.
Inherits value
~~~~~
BC30678: 'End' statement not valid.
End C
~~~
</expected>)
End Sub
<WorkItem(718436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718436")>
<Fact>
Public Sub NotYetImplementedStatement()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Sub M()
Inherits A
Implements I
Imports X
Option Strict On
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source)
AssertTheseDiagnostics(compilation,
<expected>
BC30024: Statement is not valid inside a method.
Inherits A
~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Implements I
~~~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Imports X
~~~~~~~~~
BC30024: Statement is not valid inside a method.
Option Strict On
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleRemoveAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method family specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected RemoveHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleAddAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method family specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected AddHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
AddHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub EventTypeIsNotADelegate()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::remove_Test
.event E1 Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC37223: 'Public Event Test As E1' is an unsupported event.
AddHandler e.Test, e
~~~~~~
BC37223: 'Public Event Test As E1' is an unsupported event.
RemoveHandler e.Test, e
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test() cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test()
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action, class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test() cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test()
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action, class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub NonVoidAccessors()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance int32
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance int32
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance int32 E1::add_Test(class [mscorlib]System.Action)
.removeon instance int32 E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation1, expectedOutput:="add_Test
remove_Test")
End Sub
''' <summary>
''' Tests that FULLWIDTH COLON (U+FF1A) is never parsed as part of XML name,
''' but is instead parsed as a statement separator when it immediately follows an XML name.
''' If the next token is an identifier or keyword, it should be parsed as a separate statement.
''' An XML name should never include more than one colon.
''' See also: http://fileformat.info/info/unicode/char/FF1A
''' </summary>
<Fact>
<WorkItem(529880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529880")>
Public Sub FullWidthColonInXmlNames()
' FULLWIDTH COLON is represented by "~" below
Dim source = <![CDATA[
Imports System
Module M
Sub Main()
Test1()
Test2()
Test3()
Test4()
Test5()
Test6()
Test7()
Test8()
End Sub
Sub Test1()
Console.WriteLine(">1")
Dim x = <a/>.@xml:goo
Console.WriteLine("<1")
End Sub
Sub Test2()
Console.WriteLine(">2")
Dim x = <a/>.@xml:goo:goo
Console.WriteLine("<2")
End Sub
Sub Test3()
Console.WriteLine(">3")
Dim x = <a/>.@xml:return
Console.WriteLine("<3")
End Sub
Sub Test4()
Console.WriteLine(">4")
Dim x = <a/>.@xml:return:return
Console.WriteLine("<4")
End Sub
Sub Test5()
Console.WriteLine(">5")
Dim x = <a/>.@xml~goo
Console.WriteLine("<5")
End Sub
Sub Test6()
Console.WriteLine(">6")
Dim x = <a/>.@xml~return
Console.WriteLine("<6")
End Sub
Sub Test7()
Console.WriteLine(">7")
Dim x = <a/>.@xml~goo~return
Console.WriteLine("<7")
End Sub
Sub Test8()
Console.WriteLine(">8")
Dim x = <a/>.@xml~REM
Console.WriteLine("<8")
End Sub
Sub goo
Console.WriteLine("goo")
End Sub
Sub [return]
Console.WriteLine("return")
End Sub
Sub [REM]
Console.WriteLine("REM")
End Sub
End Module]]>.Value.Replace("~"c, SyntaxFacts.FULLWIDTH_COLON)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="FullWidthColonInXmlNames">
<file name="M.vb"><%= source %></file>
</compilation>,
XmlReferences,
TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
>1
<1
>2
goo
<2
>3
<3
>4
>5
goo
<5
>6
>7
goo
>8
<8]]>.Value.Replace(vbLf, Environment.NewLine))
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.Reflection
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
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' This class tests binding of various statements; i.e., the code in Binder_Statements.vb
'
' Tests should be added here for every construct that can be bound
' correctly, with a test that compiles, verifies, and runs code for that construct.
' Tests should also be added here for every diagnostic that can be generated.
Public Class Binder_Statements_Tests
Inherits BasicTestBase
<Fact>
Public Sub HelloWorld1()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Module M
Sub Main()
System.Console.WriteLine("Hello, world!")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world!")
End Sub
<Fact>
Public Sub HelloWorld2()
CompileAndVerify(
<compilation name="HelloWorld2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim x as object
x = 42
Console.WriteLine("Hello, world {0} {1}", 135.2.ToString(System.Globalization.CultureInfo.InvariantCulture), x)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world 135.2 42")
End Sub
<Fact>
Public Sub LocalWithSimpleInitialization()
CompileAndVerify(
<compilation name="LocalWithSimpleInitialization">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String = "Hello world"
Console.WriteLine(s)
s = nothing
Console.WriteLine(s)
Dim i As Integer = 1
Console.WriteLine(i)
Dim d As Double = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
]]>)
End Sub
<Fact>
Public Sub LocalAsNew()
CompileAndVerify(
<compilation name="LocalAsNew">
<file name="a.vb">
Imports System
Class C
Sub New (msg as string)
Me.msg = msg
End Sub
Sub Report()
Console.WriteLine(msg)
End Sub
private msg as string
End Class
Module M1
Sub Main()
dim myC as New C("hello")
myC.Report()
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hello")
End Sub
<Fact>
Public Sub LocalAsNewArrayError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class C
Sub New()
End Sub
End Class
Module M1
Sub Main()
' Arrays cannot be declared with 'New'.
dim c1() as new C()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
dim c1() as new C()
~~~
</expected>)
End Sub
<Fact>
Public Sub LocalAsNewArrayError001()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class X
Dim a(), b As New S
End Class
Class X1
Dim a, b() As New S
End Class
Class X2
Dim a, b(3) As New S
End Class
Class X3
Dim a, b As New S(){}
End Class
Structure S
End Structure
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
Dim a(), b As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b() As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b(3) As New S
~~~~
BC30205: End of statement expected.
Dim a, b As New S(){}
~
</expected>)
End Sub
<WorkItem(545766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545766")>
<Fact>
Public Sub LocalSameNameAsOperatorAllowed()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalSameNameAsOperatorAllowed">
<file name="a.vb">
Imports System
Class C
Public Shared Operator IsTrue(ByVal w As C) As Boolean
Dim IsTrue As Boolean = True
Return IsTrue
End Operator
Public Shared Operator IsFalse(ByVal w As C) As Boolean
Dim IsFalse As Boolean = True
Return IsFalse
End Operator
End Class
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub ParameterlessSub()
CompileAndVerify(
<compilation name="ParameterlessSub">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Hello, world")
Console.WriteLine()
Console.WriteLine("Goodbye, world")
End Sub
Sub Main()
Goo
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello, world
Goodbye, world
]]>)
End Sub
<Fact>
Public Sub CallStatement()
CompileAndVerify(
<compilation name="CallStatement">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Call without parameters")
End Sub
Sub Goo(s as string)
Console.WriteLine(s)
End Sub
Function SayHi as string
return "Hi"
End Function
Function One as integer
return 1
End Function
Sub Main()
Goo(SayHi)
goo
call goo
call goo("call with parameters")
dim i = One + One
Console.WriteLine(i)
i = One
Console.WriteLine(i)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hi
Call without parameters
Call without parameters
call with parameters
2
1
]]>)
End Sub
<Fact>
Public Sub CallStatementMethodNotFound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodNotFound">
<file name="a.vb">
Imports System
Module M1
Sub Main()
call goo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'goo' is not declared. It may be inaccessible due to its protection level.
call goo
~~~
</expected>)
End Sub
<WorkItem(538590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538590")>
<Fact>
Public Sub CallStatementNothingAsInvocationExpression_Bug_4247()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Module M1
Sub Main()
Dim myLocalArr as Integer()
Dim myLocalVar as Integer = 42
call myLocalArr(0)
call myLocalVar
call Nothing
call 911
call new Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30454: Expression is not a method.
call myLocalArr(0)
~~~~~~~~~~
BC42104: Variable 'myLocalArr' is used before it has been assigned a value. A null reference exception could result at runtime.
call myLocalArr(0)
~~~~~~~~~~
BC30454: Expression is not a method.
call myLocalVar
~~~~~~~~~~
BC30454: Expression is not a method.
call Nothing
~~~~~~~
BC30454: Expression is not a method.
call 911
~~~
BC30454: Expression is not a method.
call new Integer
~~~~~~~~~~~
</expected>)
End Sub
' related to bug 4247
<Fact>
Public Sub CallStatementNamespaceAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Namespace N1.N2
Module M1
Sub Main()
call N1
call N1.N2
End Sub
End Module
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30112: 'N1' is a namespace and cannot be used as an expression.
call N1
~~
BC30112: 'N1.N2' is a namespace and cannot be used as an expression.
call N1.N2
~~~~~
</expected>)
End Sub
' related to bug 4247
<WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")>
<Fact>
Public Sub CallStatementTypeAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Class Class1
End Class
Module M1
Sub Main()
call Class1
call Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30109: 'Class1' is a class type and cannot be used as an expression.
call Class1
~~~~~~
BC30110: 'Integer' is a structure type and cannot be used as an expression.
call Integer
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AssignmentStatement()
CompileAndVerify(
<compilation name="AssignmentStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String
s = "Hello world"
Console.WriteLine(s)
Dim i As Integer
i = 1
Console.WriteLine(i)
Dim d As Double
d = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
d = i
Console.WriteLine(d)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
1
]]>)
End Sub
<Fact>
Public Sub FieldAssignmentStatement()
CompileAndVerify(
<compilation name="FieldAssignmentStatement">
<file name="a.vb">
Imports System
Class C1
public i as integer
End class
Structure S1
public s as string
End Structure
Module M1
Sub Main()
dim myC as C1 = new C1
myC.i = 10
Console.WriteLine(myC.i)
dim myS as S1 = new S1
myS.s = "a"
Console.WriteLine(MyS.s)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
10
a
]]>)
End Sub
<Fact>
Public Sub AssignmentWithBadLValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AssignmentWithBadLValue">
<file name="a.vb">
Imports System
Module M1
Function f as integer
return 0
End function
Sub s
End Sub
Sub Main()
f = 0
s = 1
dim i as integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30068: Expression is a value and therefore cannot be the target of an assignment.
f = 0
~
BC30068: Expression is a value and therefore cannot be the target of an assignment.
s = 1
~
BC42024: Unused local variable: 'i'.
dim i as integer
~
</expected>)
End Sub
<Fact>
Public Sub MultilineIfStatement1()
CompileAndVerify(
<compilation name="MultilineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
Dim cond2 As Boolean
Dim cond3 As Boolean
cond = True
cond2 = True
cond3 = True
If cond Then
Console.WriteLine("1. ThenPart")
End If
If cond Then
Console.WriteLine("2. ThenPart")
Else
Console.WriteLine("2. ElsePart")
End If
If cond Then
Console.WriteLine("3. ThenPart")
Else If cond2
Console.WriteLine("3. ElseIfPart")
End If
If cond Then
Console.WriteLine("4. ThenPart")
Else If cond2
Console.WriteLine("4. ElseIf1Part")
Else If cond3
Console.WriteLine("4. ElseIf2Part")
Else
Console.WriteLine("4. ElsePart")
End If
cond = False
If cond Then
Console.WriteLine("5. ThenPart")
End If
If cond Then
Console.WriteLine("6. ThenPart")
Else
Console.WriteLine("6. ElsePart")
End If
If cond Then
Console.WriteLine("7. ThenPart")
Else If cond2
Console.WriteLine("7. ElseIfPart")
End If
If cond Then
Console.WriteLine("8. ThenPart")
Else If cond2
Console.WriteLine("8. ElseIf1Part")
Else If cond3
Console.WriteLine("8. ElseIf2Part")
Else
Console.WriteLine("8. ElsePart")
End If
cond2 = false
If cond Then
Console.WriteLine("9. ThenPart")
Else If cond2
Console.WriteLine("9. ElseIfPart")
End If
If cond Then
Console.WriteLine("10. ThenPart")
Else If cond2
Console.WriteLine("10. ElseIf1Part")
Else If cond3
Console.WriteLine("10. ElseIf2Part")
Else
Console.WriteLine("10. ElsePart")
End If
cond3 = false
If cond Then
Console.WriteLine("11. ThenPart")
Else If cond2
Console.WriteLine("11. ElseIf1Part")
Else If cond3
Console.WriteLine("11. ElseIf2Part")
Else
Console.WriteLine("11. ElsePart")
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPart
3. ThenPart
4. ThenPart
6. ElsePart
7. ElseIfPart
8. ElseIf1Part
10. ElseIf2Part
11. ElsePart
]]>)
End Sub
<Fact>
Public Sub SingleLineIfStatement1()
CompileAndVerify(
<compilation name="SingleLineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
cond = True
If cond Then Console.WriteLine("1. ThenPart")
If cond Then Console.WriteLine("2. ThenPartA"): COnsole.WriteLine("2. ThenPartB")
If cond Then Console.WriteLine("3. ThenPartA"): COnsole.WriteLine("3. ThenPartB") Else Console.WriteLine("3. ElsePartA"): Console.WriteLine("3. ElsePartB")
If cond Then Console.WriteLine("4. ThenPart") Else Console.WriteLine("4. ElsePartA"): Console.WriteLine("4. ElsePartB")
If cond Then Console.WriteLine("5. ThenPartA"): Console.WriteLine("5. ThenPartB") Else Console.WriteLine("5. ElsePart")
If cond Then Console.WriteLine("6. ThenPart") Else Console.WriteLine("6. ElsePart")
cond = false
If cond Then Console.WriteLine("7. ThenPart")
If cond Then Console.WriteLine("8. ThenPartA"): COnsole.WriteLine("8. ThenPartB")
If cond Then Console.WriteLine("9. ThenPart"): COnsole.WriteLine("9. ThenPartB") Else Console.WriteLine("9. ElsePartA"): Console.WriteLine("9. ElsePartB")
If cond Then Console.WriteLine("10. ThenPart") Else Console.WriteLine("10. ElsePartA"): Console.WriteLine("10. ElsePartB")
If cond Then Console.WriteLine("11. ThenPartA"): Console.WriteLine("11. ThenPartB") Else Console.WriteLine("11. ElsePart")
If cond Then Console.WriteLine("12. ThenPart") Else Console.WriteLine("12. ElsePart")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPartA
2. ThenPartB
3. ThenPartA
3. ThenPartB
4. ThenPart
5. ThenPartA
5. ThenPartB
6. ThenPart
9. ElsePartA
9. ElsePartB
10. ElsePartA
10. ElsePartB
11. ElsePart
12. ElsePart
]]>)
End Sub
<Fact>
Public Sub DoLoop1()
CompileAndVerify(
<compilation name="DoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do While breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop2()
CompileAndVerify(
<compilation name="DoLoop2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do Until breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop3()
CompileAndVerify(
<compilation name="DoLoop3">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop While breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop4()
CompileAndVerify(
<compilation name="DoLoop4">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop Until breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub WhileLoop1()
CompileAndVerify(
<compilation name="WhileLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
While not breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
End While
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub ExitContinueDoLoop1()
CompileAndVerify(
<compilation name="ExitContinueDoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
dim continueLoop as Boolean
breakLoop = True: continueLoop = true
Do While breakLoop
Console.WriteLine("Stmt1")
If continueLoop Then
Console.WriteLine("Continuing")
continueLoop = false
Continue Do
End If
Console.WriteLine("Exiting")
Exit Do
Console.WriteLine("Stmt2")
Loop
Console.WriteLine("After Loop")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Continuing
Stmt1
Exiting
After Loop
]]>)
End Sub
<Fact>
Public Sub ExitSub()
CompileAndVerify(
<compilation name="ExitSub">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
breakLoop = True
Do While breakLoop
Console.WriteLine("Stmt1")
Console.WriteLine("Exiting")
Exit Sub
Console.WriteLine("Stmt2") 'should not output
Loop
Console.WriteLine("After Loop") 'should not output
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Exiting
]]>)
End Sub
<Fact>
Public Sub ExitFunction()
CompileAndVerify(
<compilation name="ExitFunction">
<file name="a.vb">
Imports System
Module M1
Function Fact(i as integer) as integer
fact = 1
do
if i <= 0 then
exit function
else
fact = i * fact
i = i - 1
end if
loop
End Function
Sub Main()
Console.WriteLine(Fact(0))
Console.WriteLine(Fact(3))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
6
]]>)
End Sub
<Fact>
Public Sub BadExit()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadExit">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Exit Do ' ok
Exit For
Exit Try
Exit Select
Exit While
Loop
Exit Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30096: 'Exit For' can only appear inside a 'For' statement.
Exit For
~~~~~~~~
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
BC30099: 'Exit Select' can only appear inside a 'Select' statement.
Exit Select
~~~~~~~~~~~
BC30097: 'Exit While' can only appear inside a 'While' statement.
Exit While
~~~~~~~~~~
BC30089: 'Exit Do' can only appear inside a 'Do' statement.
Exit Do ' outside loop
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadContinue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadContinue">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Continue Do ' ok
Continue For
Continue While
Loop
Continue Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30783: 'Continue For' can only appear inside a 'For' statement.
Continue For
~~~~~~~~~~~~
BC30784: 'Continue While' can only appear inside a 'While' statement.
Continue While
~~~~~~~~~~~~~~
BC30782: 'Continue Do' can only appear inside a 'Do' statement.
Continue Do ' outside loop
~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Return1()
CompileAndVerify(
<compilation name="Return1">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
F1 = 1
End Function
Function F2 as Integer
if true then
F2 = 2
else
return 3
end if
End Function
Function F3 as Integer
return 3
End Function
Sub S1
return
End Sub
Sub Main()
dim result as integer
result = F1()
Console.WriteLine(result)
result = F2()
Console.WriteLine(result)
result = F3()
Console.WriteLine(result)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
2
3
]]>)
End Sub
<Fact>
Public Sub BadReturn()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadReturn">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
return
End Function
Sub S1
return 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30654: 'Return' statement in a Function, Get, or Operator must return a value.
return
~~~~~~
BC30647: 'Return' statement in a Sub or a Set cannot return a value.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NoReturnUnreachableEnd()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoReturnUnreachableEnd">
<file name="a.vb">
Imports System
Module M1
Function goo() As Boolean
While True
End While
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadArrayInitWithExplicitArraySize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(3) as integer = 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
dim a(3) as integer = 1
~~~~
BC30311: Value of type 'Integer' cannot be converted to 'Integer()'.
dim a(3) as integer = 1
~
</expected>)
End Sub
<Fact>
Public Sub BadArrayWithNegativeSize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-3) as integer
dim b = new integer(-3){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30611: Array dimensions cannot have a negative size.
dim a(-3) as integer
~~
BC30611: Array dimensions cannot have a negative size.
dim b = new integer(-3){}
~~
</expected>)
End Sub
<Fact>
Public Sub ArrayWithMinusOneUpperBound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-1) as integer
dim b = new integer(-1){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(542987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542987")>
<Fact()>
Public Sub MultiDimensionalArrayWithTooFewInitializers()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MultiDimensionalArrayWithTooFewInitializers">
<file name="Program.vb">
Module Program
Sub Main()
Dim x = New Integer(0, 1) {{}}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30567: Array initializer is missing 2 elements.
Dim x = New Integer(0, 1) {{}}
~~
</expected>)
End Sub
<WorkItem(542988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542988")>
<Fact()>
Public Sub Max32ArrayDimensionsAreAllowed()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Max32ArrayDimensionsAreAllowed">
<file name="Program.vb">
Module Program
Sub Main()
Dim z1(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim z2(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim x1 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim x2 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim y1 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
Dim y2 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
End Sub
End Module
</file>
</compilation>).
VerifyDiagnostics(
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"))
End Sub
<Fact>
Public Sub GotoIf()
CompileAndVerify(
<compilation name="GotoIf">
<file name="a.vb">
Imports System
Module M1
Sub GotoIf()
GoTo l1
If False Then
l1:
Console.WriteLine("Jump into If")
End If
End Sub
Sub GotoWhile()
GoTo l1
While False
l1:
Console.WriteLine("Jump into While")
End While
End Sub
Sub GotoDo()
GoTo l1
Do While False
l1:
Console.WriteLine("Jump into Do")
Loop
End Sub
Sub GotoSelect()
Dim i As Integer = 0
GoTo l1
Select Case i
Case 0
l1:
Console.WriteLine("Jump into Select")
End Select
End Sub
Sub Main()
GotoIf()
GotoWhile()
GotoDo()
GotoSelect()
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Jump into If
Jump into While
Jump into Do
Jump into Select
]]>)
End Sub
<Fact()>
Public Sub GotoIntoBlockErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoIntoBlockErrors">
<file name="a.vb">
Imports System
Module M1
Sub GotoFor()
For i as Integer = 0 To 10
l1:
Console.WriteLine()
Next
GoTo l1
End Sub
Sub GotoWith()
Dim c1 = New C()
With c1
l1:
Console.WriteLine()
End With
GoTo l1
End Sub
Sub GotoUsing()
Using c1 as IDisposable = nothing
l1:
Console.WriteLine()
End Using
GoTo l1
End Sub
Sub GotoTry()
Try
l1:
Console.WriteLine()
Finally
End Try
GoTo l1
End Sub
Sub GotoLambda()
Dim x = Sub()
l1:
End Sub
GoTo l1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30757: 'GoTo l1' is not valid because 'l1' is inside a 'For' or 'For Each' statement that does not contain this statement.
GoTo l1
~~
BC30002: Type 'C' is not defined.
Dim c1 = New C()
~
BC30756: 'GoTo l1' is not valid because 'l1' is inside a 'With' statement that does not contain this statement.
GoTo l1
~~
BC36009: 'GoTo l1' is not valid because 'l1' is inside a 'Using' statement that does not contain this statement.
GoTo l1
~~
BC30754: 'GoTo l1' is not valid because 'l1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo l1
~~
BC30132: Label 'l1' is not defined.
GoTo l1
~~
</expected>)
End Sub
<Fact()>
Public Sub GotoDecimalLabels()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoDecimalLabels">
<file name="a.vb">
Imports System
Module M
Sub Main()
1 : Goto &H2
2 : Goto 01
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(543381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543381")>
<Fact()>
Public Sub GotoUndefinedLabel()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoUndefinedLabel">
<file name="a.vb">
Imports System
Class c1
Shared Sub Main()
GoTo lab1
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30132: Label 'lab1' is not defined.
GoTo lab1
~~~~
</expected>)
End Sub
<WorkItem(538574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538574")>
<Fact()>
Public Sub ArrayModifiersOnVariableAndType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ArrayModifiersOnVariableAndType">
<file name="a.vb">
Imports System
Module M1
public a() as integer()
public b(1) as integer()
Sub S1
dim a() as integer() = nothing
dim b(1) as string()
End Sub
Sub S2(x() as integer())
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors>
BC31087: Array modifiers cannot be specified on both a variable and its type.
public a() as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
public b(1) as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim a() as integer() = nothing
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim b(1) as string()
~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
Sub S2(x() as integer())
~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Bug6663()
' Test dependent on referenced mscorlib, but NOT system.dll.
Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="Bug6663">
<file name="a.vb">
Imports System
Module Program
Sub Main()
Console.WriteLine("".ToString() = "".ToString())
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe)
CompileAndVerify(comp, expectedOutput:="True")
End Sub
<WorkItem(540390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540390")>
<Fact()>
Public Sub Bug6637()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Imports System
Module M1
Sub Main()
Dim a(3) As Integer
For i = 0 To 3
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = 0 To 3
~
</expected>)
End Sub
<WorkItem(540412, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540412")>
<Fact()>
Public Sub Bug6662()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Class C
Shared Sub M()
For i = Nothing To 10
Dim d as System.Action = Sub() i = i + 1
Next
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = Nothing To 10
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
</expected>)
End Sub
<WorkItem(542801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542801")>
<Fact()>
Public Sub ExtTryFromFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Class BaseClass
Function Method() As String
Dim x = New Integer() {}
Try
Exit Try
Catch ex1 As Exception When True
Exit Try
Finally
Exit Try
End Try
Return "x"
End Function
End Class
Class DerivedClass
Inherits BaseClass
Shared Sub Main()
End Sub
End Class
</file>
</compilation>, {SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotLocal()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotLocal">
<file name="goo.vb">
Module M1
Private ex as System.Exception
Sub Main()
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact(), WorkItem(651622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651622")>
Public Sub Bug651622()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="goo.vb">
Module Module1
Sub Main()
Try
Catch Main
Catch x as System.Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Main' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Main
~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchStatic()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchStatic">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Static ex as exception = nothing
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchUndeclared()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchUndeclared">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Try
' Explicit off does not have effect on Catch - ex is still undefined.
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'ex' is not declared. It may be inaccessible due to its protection level.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Dim ex as String = "qq"
Try
Catch ex
End Try
Try
Catch ex1 as String
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex
~~
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex1 as String
~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotVariableOrParameter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotVariableOrParameter">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Goo
End Sub
Sub Main()
Try
Catch Goo
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Goo' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch ex
Catch ex1 as Exception
Catch
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch
Catch ex
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex
~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When true
Catch ex
' filter does NOT make this reachable.
Catch ex1 as Exception When true
' implicitly this is a "Catch ex As Exception When true" so still unreachable
Catch When true
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception When true
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch When true
~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchOverlapped()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex As SystemException = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When True
Catch ex
' filter does NOT make this reachable.
Catch ex1 As ArgumentException When True
' implicitly this is a "Catch ex As Exception When true"
Catch When True
' this is ok since it is not derived from SystemException
' and catch above has a filter
Catch ex1 As ApplicationException
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'SystemException'.
Catch ex1 As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchShadowing()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Dim field As String
Function Goo(Of T)(ex As Exception) As Exception
Dim ex1 As SystemException = Nothing
Try
Dim ex2 As Exception = nothing
Catch ex As Exception
Catch ex1 As Exception
Catch Goo As ArgumentException When True
' this is ok
Catch ex2 As exception
Dim ex3 As exception = nothing
'this is ok
Catch ex3 As ApplicationException
' this is ok
Catch field As Exception
End Try
return nothing
End Function
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30734: 'ex' is already declared as a parameter of this method.
Catch ex As Exception
~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 As Exception
~~~~~~~~~~~~~~~~~~~~~~
BC30616: Variable 'ex1' hides a variable in an enclosing block.
Catch ex1 As Exception
~~~
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'Exception'.
Catch Goo As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30290: Local variable cannot have the same name as the function containing it.
Catch Goo As ArgumentException When True
~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex2 As exception
~~~~~~~~~~~~~~~~~~~~~~
BC42029: 'Catch' block never reached, because 'ApplicationException' inherits from 'Exception'.
Catch ex3 As ApplicationException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch field As Exception
~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(837820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837820")>
<Fact()>
Public Sub CatchShadowingGeneric()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Class cls3(Of T As NullReferenceException)
Sub scen3()
Try
Catch ex As T
Catch ex As NullReferenceException
End Try
End Sub
Sub scen4()
Try
Catch ex As NullReferenceException
'COMPILEWarning: BC42029 ,"Catch ex As T"
Catch ex As T
End Try
End Sub
End Class
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'T' inherits from 'NullReferenceException'.
Catch ex As T
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoOutOfFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoOutOfFinally">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
l1:
Try
Finally
try
goto l1
catch
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
goto l1
~~
</expected>)
End Sub
<Fact()>
Public Sub BranchOutOfFinally1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BranchOutOfFinally1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
for i as integer = 1 to 10
Try
Finally
continue for
End Try
Next
End Sub
Function Goo() as integer
l1:
Try
Finally
try
return 1
catch
return 1
End Try
End Try
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
continue for
~~~~~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
Catch ex As Exception
l1:
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
l1:
Catch ex As Exception
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInLateAddressOf()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Option Strict Off
Imports System
Module Program
Delegate Sub d1(ByRef x As Integer, y As Integer)
Sub Main()
Dim obj As Object '= New cls1
Dim o As d1 = AddressOf obj.goo
Dim l As Integer = 0
o(l, 2)
Console.WriteLine(l)
End Sub
Class cls1
Shared Sub goo(ByRef x As Integer, y As Integer)
x = 42
Console.WriteLine(x + y)
End Sub
End Class
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim o As d1 = AddressOf obj.goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Dim B as StackOverflowException
Dim C as Exception
Try
A = new ApplicationException
B = new StackOverflowException
C = new Exception
Console.Writeline(A) 'this is ok
Catch ex as NullReferenceException When A.Message isnot nothing
Catch ex as DivideByZeroException
Console.Writeline(B)
Finally
Console.Writeline(C)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Catch ex as NullReferenceException When A.Message isnot nothing
~
BC42104: Variable 'B' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(B)
~
BC42104: Variable 'C' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(C)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
' ok , A is assigned in the filter and in the catch
Catch A When A.Message isnot nothing
Console.Writeline(A)
Catch ex as Exception
A = new ApplicationException
Finally
'error
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter2">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter3">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter4">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
Finally
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Exception
Get
Return New Exception
End Get
End Property
WriteOnly Property Boo As Exception
Set(value As Exception)
End Set
End Property
Sub Main()
Throw Moo
Throw Boo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30524: Property 'Boo' is 'WriteOnly'.
Throw Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly e as new Exception
ReadOnly s as string = "qq"
Sub Main()
Throw e
Throw s
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30665: 'Throw' operand must derive from 'System.Exception'.
Throw s
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RethrowNotInCatch()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RethrowNotInCatch">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Throw
Try
Throw
Catch ex As Exception
Throw
Dim a As Action = Sub()
ex.ToString()
Throw
End Sub
Try
Throw
Catch
Throw
Finally
Throw
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub ForNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Integer
Get
Return 1
End Get
End Property
WriteOnly Property Boo As integer
Set(value As integer)
End Set
End Property
Sub Main()
For Moo = 1 to Moo step Moo
Next
For Boo = 1 to Boo step Boo
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Moo = 1 to Moo step Moo
~~~
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CustomDatatypeForLoop()
Dim source =
<compilation>
<file name="goo.vb"><![CDATA[
Imports System
Module Module1
Public Sub Main()
Dim x As New c1
For x = 1 To 3
Console.WriteLine("hi")
Next
End Sub
End Module
Public Class c1
Public val As Integer
Public Shared Widening Operator CType(ByVal arg1 As Integer) As c1
Console.WriteLine("c1::CType(Integer) As c1")
Dim c As New c1
c.val = arg1 'what happens if this is last statement?
Return c
End Operator
Public Shared Widening Operator CType(ByVal arg1 As c1) As Integer
Console.WriteLine("c1::CType(c1) As Integer")
Dim x As Integer
x = arg1.val
Return x
End Operator
Public Shared Operator +(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::+(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val + arg2.val
Return c
End Operator
Public Shared Operator -(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::-(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val - arg2.val
Return c
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::>=(c1, Integer) As Boolean")
If arg1.val >= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::<=(c1, Integer) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::<=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::>=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::<=(c1, c1) As Boolean")
If arg1.val <= arg2.val Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::>=(c1, c1) As Boolean")
If arg1.val >= arg2.val Then
Return True
Else
Return False
End If
End Operator
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, <![CDATA[c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::-(c1, c1) As c1
c1::>=(c1, c1) As Boolean
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
]]>)
End Sub
<Fact()>
Public Sub SelectCase1_SwitchTable()
CompileAndVerify(
<compilation name="SelectCase1">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case 0
Console.WriteLine("Equal to 0")
Case 1, 2, 3, 4, 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9, 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<Fact()>
Public Sub SelectCase2_IfList()
CompileAndVerify(
<compilation name="SelectCase2">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case Is < 1
Console.WriteLine("Less than 1")
Case 1 To 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Less than 1
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<WorkItem(542156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542156")>
<Fact()>
Public Sub ImplicitVarInRedim()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Option Explicit Off
Module M
Sub Main()
Redim x(10)
System.Console.WriteLine("OK")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="OK")
End Sub
<Fact()>
Public Sub EndStatementsInMethodBodyShouldNotThrowNYI()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EndStatementsInMethodBodyShouldNotThrowNYI">
<file name="a.vb">
Namespace N1
Public Class C1
Public Sub S1()
for i as integer = 23 to 42
next
next
do
loop while true
loop
end if
end select
end try
end using
end while
end with
end synclock
Try
Catch ex As System.Exception
End Try
catch
Try
Catch ex As System.Exception
finally
finally
End Try
finally
End Sub
Public Sub S2
end namespace
end module
end class
end structure
end interface
end enum
end function
end operator
end property
end get
end set
end event
end addhandler
end removehandler
end raiseevent
End Sub
end Class
end Namespace
Namespace N2
Class C2
function F1() as integer
end sub
return 42
end function
End Class
End Namespace
</file>
</compilation>)
Dim expectedErrors1 = <errors>
BC30481: 'Class' statement must end with a matching 'End Class'.
Public Class C1
~~~~~~~~~~~~~~~
BC30092: 'Next' must be preceded by a matching 'For'.
next
~~~~
BC30091: 'Loop' must be preceded by a matching 'Do'.
loop
~~~~
BC30087: 'End If' must be preceded by a matching 'If'.
end if
~~~~~~
BC30088: 'End Select' must be preceded by a matching 'Select Case'.
end select
~~~~~~~~~~
BC30383: 'End Try' must be preceded by a matching 'Try'.
end try
~~~~~~~
BC36007: 'End Using' must be preceded by a matching 'Using'.
end using
~~~~~~~~~
BC30090: 'End While' must be preceded by a matching 'While'.
end while
~~~~~~~~~
BC30093: 'End With' must be preceded by a matching 'With'.
end with
~~~~~~~~
BC30674: 'End SyncLock' must be preceded by a matching 'SyncLock'.
end synclock
~~~~~~~~~~~~
BC30380: 'Catch' cannot appear outside a 'Try' statement.
catch
~~~~~
BC30381: 'Finally' can only appear once in a 'Try' statement.
finally
~~~~~~~
BC30382: 'Finally' cannot appear outside a 'Try' statement.
finally
~~~~~~~
BC30026: 'End Sub' expected.
Public Sub S2
~~~~~~~~~~~~~
BC30622: 'End Module' must be preceded by a matching 'Module'.
end module
~~~~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end class
~~~~~~~~~
BC30621: 'End Structure' must be preceded by a matching 'Structure'.
end structure
~~~~~~~~~~~~~
BC30252: 'End Interface' must be preceded by a matching 'Interface'.
end interface
~~~~~~~~~~~~~
BC30184: 'End Enum' must be preceded by a matching 'Enum'.
end enum
~~~~~~~~
BC30430: 'End Function' must be preceded by a matching 'Function'.
end function
~~~~~~~~~~~~
BC33007: 'End Operator' must be preceded by a matching 'Operator'.
end operator
~~~~~~~~~~~~
BC30431: 'End Property' must be preceded by a matching 'Property'.
end property
~~~~~~~~~~~~
BC30630: 'End Get' must be preceded by a matching 'Get'.
end get
~~~~~~~
BC30632: 'End Set' must be preceded by a matching 'Set'.
end set
~~~~~~~
BC31123: 'End Event' must be preceded by a matching 'Custom Event'.
end event
~~~~~~~~~
BC31124: 'End AddHandler' must be preceded by a matching 'AddHandler' declaration.
end addhandler
~~~~~~~~~~~~~~
BC31125: 'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.
end removehandler
~~~~~~~~~~~~~~~~~
BC31126: 'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.
end raiseevent
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End Sub
~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end Class
~~~~~~~~~
BC30623: 'End Namespace' must be preceded by a matching 'Namespace'.
end Namespace
~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
end sub
~~~~~~~
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub AddHandlerMissingStuff()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload,
AddHandler , del
AddHandler
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30201: Expression expected.
AddHandler v.DomainUnload,
~
BC30201: Expression expected.
AddHandler , del
~
BC30196: Comma expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerUninitialized()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
' no warnings here, variable is used
Dim del As System.EventHandler
' warning here
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'del' is used before it has been assigned a value. A null reference exception could result at runtime.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNotSimple()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' real event with arg list
AddHandler (v.DomainUnload()), del
' not an event
AddHandler (v.GetType()), del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.DomainUnload()), del
~~~~~~~~~~~~~~~~
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.GetType()), del
~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerLambda()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim v = AppDomain.CreateDomain("qq")
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
AppDomain.Unload(v)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42326: Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerNotEvent()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' not an event
AddHandler (v.GetType), del
' not anything
AddHandler v.GetTyp, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30676: 'GetType' is not an event of 'AppDomain'.
AddHandler (v.GetType), del
~~~~~~~
BC30456: 'GetTyp' is not a member of 'AppDomain'.
AddHandler v.GetTyp, del
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNoConversion()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim v = AppDomain.CreateDomain("qq")
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
AddHandler v.DomainUnload, AddressOf H
Dim del as Action(of Object, EventArgs) = Sub(sender As Object, a As EventArgs) Console.Write("unload")
AddHandler v.DomainUnload, del
End Sub
Sub H(i as integer)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36670: Nested sub does not have a signature that is compatible with delegate 'EventHandler'.
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31143: Method 'Public Sub H(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As EventArgs)'.
AddHandler v.DomainUnload, AddressOf H
~
BC30311: Value of type 'Action(Of Object, EventArgs)' cannot be converted to 'EventHandler'.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub LegalGotoCasesTryCatchFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Module M1
Sub Main()
dim x1 = function()
labelOK6:
goto labelok7
if true then
goto labelok6
labelok7:
end if
return 23
end function
dim x2 = sub()
labelOK8:
goto labelok9
if true then
goto labelok8
labelok9:
end if
end sub
Try
Goto LabelOK1
LabelOK1:
Catch
Goto LabelOK2
LabelOK2:
Try
goto LabelOK1
goto LabelOK2:
LabelOK5:
Catch
goto LabelOK1
goto LabelOK5
goto LabelOK2
Finally
End Try
Finally
Goto LabelOK3
LabelOK3:
End Try
Exit Sub
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(543055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543055")>
<Fact()>
Public Sub Bug10583()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Try
GoTo label
GoTo label5
Catch ex As Exception
label:
Finally
label5:
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30754: 'GoTo label' is not valid because 'label' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label
~~~~~
BC30754: 'GoTo label5' is not valid because 'label5' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label5
~~~~~~
</expected>)
End Sub
<WorkItem(543060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543060")>
<Fact()>
Public Sub SelectCase_ImplicitOperator()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Class X
Public Shared Operator =(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Operator <>(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Widening Operator CType(expandedName As String) As X
Return New X()
End Operator
End Class
Sub Main()
End Sub
Sub Test(x As X)
Select Case x
Case "a"
Console.WriteLine("Equal to a")
Case "s"
Console.WriteLine("Equal to A")
Case "3"
Console.WriteLine("Error")
Case "5"
Console.WriteLine("Error")
Case "6"
Console.WriteLine("Error")
Case "9"
Console.WriteLine("Error")
Case "11"
Console.WriteLine("Error")
Case "12"
Console.WriteLine("Error")
Case "13"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
</expected>)
End Sub
<WorkItem(543333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543333")>
<Fact()>
Public Sub Binding_Return_As_Declaration()
Dim compilation1 = CreateCompilationWithMscorlib40(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Class Program
Shared Main()
Return Nothing
End sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30689: Statement cannot appear outside of a method body.
Return Nothing
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End sub
~~~~~~~
</expected>)
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
While (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
While (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
If (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
If (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Try
Catch
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Try
Catch
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Do
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Do
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Else
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Else
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(544465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544465")>
<Fact()>
Public Sub DuplicateNullableLocals()
Dim source =
<compilation>
<file name="a.vb">
Option Explicit Off
Module M
Sub S()
Dim A? As Integer = 1
Dim A? As Integer? = 1
End Sub
End Module
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_CantSpecifyNullableOnBoth, "As Integer?"),
Diagnostic(ERRID.ERR_DuplicateLocals1, "A?").WithArguments("A"))
End Sub
<WorkItem(544431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544431")>
<Fact()>
Public Sub IllegalModifiers()
Dim source =
<compilation>
<file name="a.vb">
Class C
Public Custom E
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfCustomModifier, "Custom"))
End Sub
<Fact()>
Public Sub InvalidCode_ConstInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Const Interface
</file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors>
BC30397: 'Const' is not valid on an Interface declaration.
Const Interface
~~~~~
BC30253: 'Interface' must end with a matching 'End Interface'.
Const Interface
~~~~~~~~~~~~~~~
BC30203: Identifier expected.
Const Interface
~
</errors>)
End Sub
<WorkItem(545196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545196")>
<Fact()>
Public Sub InvalidCode_Event()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Event
</file>
</compilation>)
compilation.AssertTheseParseDiagnostics(<errors>
BC30203: Identifier expected.
Event
~
</errors>)
End Sub
<Fact>
Public Sub StopAndEnd_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim m = GetType(Module1)
System.Console.WriteLine(m.GetMethod("TestEnd").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("TestStop").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("Dummy").GetMethodImplementationFlags)
Try
System.Console.WriteLine("Before End")
TestEnd()
System.Console.WriteLine("After End")
Finally
System.Console.WriteLine("In Finally")
End Try
System.Console.WriteLine("After Try")
End Sub
Sub TestEnd()
End
End Sub
Sub TestStop()
Stop
End Sub
Sub Dummy()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation,
symbolValidator:=Sub(m As ModuleSymbol)
Dim m1 = m.ContainingAssembly.GetTypeByMetadataName("Module1")
Assert.Equal(MethodImplAttributes.Managed Or MethodImplAttributes.NoInlining Or MethodImplAttributes.NoOptimization,
DirectCast(m1.GetMembers("TestEnd").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("TestStop").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("Dummy").Single(), PEMethodSymbol).ImplementationAttributes)
End Sub)
compilationVerifier.VerifyIL("Module1.TestEnd",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp()"
IL_0005: ret
}
]]>)
compilationVerifier.VerifyIL("Module1.TestStop",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub System.Diagnostics.Debugger.Break()"
IL_0005: ret
}
]]>)
compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.DynamicallyLinkedLibrary))
AssertTheseDiagnostics(compilation,
<expected>
BC30615: 'End' statement cannot be used in class library projects.
End
~~~
</expected>)
End Sub
<Fact>
Public Sub StopAndEnd_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim x As Object
Dim y As Object
Stop
x.ToString()
End
y.ToString()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
x.ToString()
~
</expected>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub StopAndEnd_3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public state As Integer = 0
Public Sub Main()
On Error GoTo handler
Throw New NullReferenceException()
Stop
Console.WriteLine("Done")
Return
handler:
Console.WriteLine(Microsoft.VisualBasic.Information.Err.GetException().GetType())
If state = 1 Then
Resume
End If
Resume Next
End Sub
End Module
Namespace System.Diagnostics
Public Class Debugger
Public Shared Sub Break()
Console.WriteLine("In Break")
Select Case Module1.state
Case 0, 1
Module1.state += 1
Case Else
Console.WriteLine("Test issue!!!")
Return
End Select
Throw New NotSupportedException()
End Sub
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
System.NullReferenceException
In Break
System.NotSupportedException
In Break
System.NotSupportedException
Done
]]>)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithSingleLineIf()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then End Else Console.WriteLine("Test")
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithSingleLineIfWithDll()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then End Else Console.WriteLine("Test")
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC30615: 'End' statement cannot be used in class library projects.
If True Then End Else Console.WriteLine("Test")
~~~
</expected>)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithMultiLineIf()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then
End
Else
Console.WriteLine("Test")
End If
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(660010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/660010")>
<Fact>
Public Sub Regress660010()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Inherits value
End C
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=XmlReferences)
AssertTheseDiagnostics(compilation,
<expected>
BC30481: 'Class' statement must end with a matching 'End Class'.
Class C
~~~~~~~
BC30002: Type 'value' is not defined.
Inherits value
~~~~~
BC30678: 'End' statement not valid.
End C
~~~
</expected>)
End Sub
<WorkItem(718436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718436")>
<Fact>
Public Sub NotYetImplementedStatement()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Sub M()
Inherits A
Implements I
Imports X
Option Strict On
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source)
AssertTheseDiagnostics(compilation,
<expected>
BC30024: Statement is not valid inside a method.
Inherits A
~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Implements I
~~~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Imports X
~~~~~~~~~
BC30024: Statement is not valid inside a method.
Option Strict On
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleRemoveAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method family specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected RemoveHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleAddAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method family specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected AddHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
AddHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub EventTypeIsNotADelegate()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::remove_Test
.event E1 Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC37223: 'Public Event Test As E1' is an unsupported event.
AddHandler e.Test, e
~~~~~~
BC37223: 'Public Event Test As E1' is an unsupported event.
RemoveHandler e.Test, e
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test() cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test()
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action, class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test() cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test()
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action, class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub NonVoidAccessors()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance int32
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance int32
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance int32 E1::add_Test(class [mscorlib]System.Action)
.removeon instance int32 E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation1, expectedOutput:="add_Test
remove_Test")
End Sub
''' <summary>
''' Tests that FULLWIDTH COLON (U+FF1A) is never parsed as part of XML name,
''' but is instead parsed as a statement separator when it immediately follows an XML name.
''' If the next token is an identifier or keyword, it should be parsed as a separate statement.
''' An XML name should never include more than one colon.
''' See also: http://fileformat.info/info/unicode/char/FF1A
''' </summary>
<Fact>
<WorkItem(529880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529880")>
Public Sub FullWidthColonInXmlNames()
' FULLWIDTH COLON is represented by "~" below
Dim source = <![CDATA[
Imports System
Module M
Sub Main()
Test1()
Test2()
Test3()
Test4()
Test5()
Test6()
Test7()
Test8()
End Sub
Sub Test1()
Console.WriteLine(">1")
Dim x = <a/>.@xml:goo
Console.WriteLine("<1")
End Sub
Sub Test2()
Console.WriteLine(">2")
Dim x = <a/>.@xml:goo:goo
Console.WriteLine("<2")
End Sub
Sub Test3()
Console.WriteLine(">3")
Dim x = <a/>.@xml:return
Console.WriteLine("<3")
End Sub
Sub Test4()
Console.WriteLine(">4")
Dim x = <a/>.@xml:return:return
Console.WriteLine("<4")
End Sub
Sub Test5()
Console.WriteLine(">5")
Dim x = <a/>.@xml~goo
Console.WriteLine("<5")
End Sub
Sub Test6()
Console.WriteLine(">6")
Dim x = <a/>.@xml~return
Console.WriteLine("<6")
End Sub
Sub Test7()
Console.WriteLine(">7")
Dim x = <a/>.@xml~goo~return
Console.WriteLine("<7")
End Sub
Sub Test8()
Console.WriteLine(">8")
Dim x = <a/>.@xml~REM
Console.WriteLine("<8")
End Sub
Sub goo
Console.WriteLine("goo")
End Sub
Sub [return]
Console.WriteLine("return")
End Sub
Sub [REM]
Console.WriteLine("REM")
End Sub
End Module]]>.Value.Replace("~"c, SyntaxFacts.FULLWIDTH_COLON)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="FullWidthColonInXmlNames">
<file name="M.vb"><%= source %></file>
</compilation>,
XmlReferences,
TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
>1
<1
>2
goo
<2
>3
<3
>4
>5
goo
<5
>6
>7
goo
>8
<8]]>.Value.Replace(vbLf, Environment.NewLine))
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Workspaces/MSBuildTest/Resources/SolutionFiles/CSharp_EmptyLines.sln |
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpProject", "CSharpProject\CSharpProject.csproj", "{686DD036-86AA-443E-8A10-DDB43266A8C4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
|
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpProject", "CSharpProject\CSharpProject.csproj", "{686DD036-86AA-443E-8A10-DDB43266A8C4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{686DD036-86AA-443E-8A10-DDB43266A8C4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{686DD036-86AA-443E-8A10-DDB43266A8C4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/CSharp/Test/Semantic/Semantics/IndexAndRangeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IndexAndRangeTests : CompilingTestBase
{
private const string RangeCtorSignature = "System.Range..ctor(System.Index start, System.Index end)";
private const string RangeStartAtSignature = "System.Range System.Range.StartAt(System.Index start)";
private const string RangeEndAtSignature = "System.Range System.Range.EndAt(System.Index end)";
private const string RangeAllSignature = "System.Range System.Range.All.get";
[Fact]
public void RangeBadIndexerTypes()
{
var src = @"
using System;
public static class Program {
public static void Main() {
var a = new Span<byte>();
var b = a[""str2""];
var c = a[null];
var d = a[Main()];
var e = a[new object()];
Console.WriteLine(zzz[0]);
}
}";
var comp = CreateCompilationWithIndexAndRangeAndSpan(src);
comp.VerifyDiagnostics(
// (7,19): error CS1503: Argument 1: cannot convert from 'string' to 'int'
// var b = a["str2"];
Diagnostic(ErrorCode.ERR_BadArgType, @"""str2""").WithArguments("1", "string", "int").WithLocation(7, 19),
// (8,19): error CS1503: Argument 1: cannot convert from '<null>' to 'int'
// var c = a[null];
Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int").WithLocation(8, 19),
// (9,19): error CS1503: Argument 1: cannot convert from 'void' to 'int'
// var d = a[Main()];
Diagnostic(ErrorCode.ERR_BadArgType, "Main()").WithArguments("1", "void", "int").WithLocation(9, 19),
// (10,19): error CS1503: Argument 1: cannot convert from 'object' to 'int'
// var e = a[new object()];
Diagnostic(ErrorCode.ERR_BadArgType, "new object()").WithArguments("1", "object", "int").WithLocation(10, 19),
// (11,27): error CS0103: The name 'zzz' does not exist in the current context
// Console.WriteLine(zzz[0]);
Diagnostic(ErrorCode.ERR_NameNotInContext, "zzz").WithArguments("zzz").WithLocation(11, 27));
}
[Fact]
public void PatternIndexRangeLangVer()
{
var src = @"
using System;
struct S
{
public int Length => 0;
public int Slice(int x, int y) => 0;
}
class C
{
void M(string s, Index i, Range r)
{
_ = s[i];
_ = s[r];
_ = new S()[r];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics();
comp = CreateCompilationWithIndexAndRange(src, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (12,13): error CS8652: The feature 'index operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// _ = s[i];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "s[i]").WithArguments("index operator", "8.0").WithLocation(12, 13),
// (13,13): error CS8652: The feature 'index operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// _ = s[r];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "s[r]").WithArguments("index operator", "8.0").WithLocation(13, 13),
// (14,13): error CS8652: The feature 'index operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// _ = new S()[r];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "new S()[r]").WithArguments("index operator", "8.0").WithLocation(14, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_01()
{
var src = @"
using System;
struct S
{
public int this[int i] => 0;
public int Length => 0;
public int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i]; // 1, 2
_ = this[r]; // 3, 4
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): warning CS8656: Call to non-readonly member 'S.Length.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1, 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Length.get", "this").WithLocation(11, 13),
// (11,13): warning CS8656: Call to non-readonly member 'S.this[int].get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1, 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.this[int].get", "this").WithLocation(11, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Length.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 3, 4
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Length.get", "this").WithLocation(12, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Slice(int, int)' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 3, 4
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Slice(int, int)", "this").WithLocation(12, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_02()
{
var src = @"
using System;
struct S
{
public int this[int i] => 0;
public readonly int Length => 0;
public int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i]; // 1
_ = this[r]; // 2
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): warning CS8656: Call to non-readonly member 'S.this[int].get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.this[int].get", "this").WithLocation(11, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Slice(int, int)' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Slice(int, int)", "this").WithLocation(12, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_03()
{
var src = @"
using System;
struct S
{
public readonly int this[int i] => 0;
public int Length => 0;
public readonly int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i]; // 1
_ = this[r]; // 2
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): warning CS8656: Call to non-readonly member 'S.Length.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Length.get", "this").WithLocation(11, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Length.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Length.get", "this").WithLocation(12, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_04()
{
var src = @"
using System;
struct S
{
public readonly int this[int i] => 0;
public int Count => 0;
public readonly int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i]; // 1
_ = this[r]; // 2
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): warning CS8656: Call to non-readonly member 'S.Count.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Count.get", "this").WithLocation(11, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Count.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Count.get", "this").WithLocation(12, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_05()
{
var src = @"
using System;
struct S
{
public readonly int this[int i] => 0;
public readonly int Length => 0;
public readonly int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i];
_ = this[r];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics();
}
[Fact]
public void SpanPatternRangeDelegate()
{
var src = @"
using System;
class C
{
void Throws<T>(Func<T> f) { }
public static void Main()
{
string s = ""abcd"";
Throws(() => new Span<char>(s.ToCharArray())[0..1]);
}
}";
var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (9,9): error CS0306: The type 'Span<char>' may not be used as a type argument
// Throws(() => new Span<char>(s.ToCharArray())[0..1]);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "Throws").WithArguments("System.Span<char>").WithLocation(9, 9));
}
[Fact]
public void PatternIndexNoRefIndexer()
{
var src = @"
struct S
{
public int Length => 0;
public int this[int i] => 0;
}
class C
{
void M(S s)
{
ref readonly int x = ref s[^2];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,34): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// ref readonly int x = ref s[^2];
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "s[^2]").WithArguments("S.this[int]").WithLocation(11, 34));
}
[Fact]
public void PatternRangeSpanNoReturn()
{
var src = @"
using System;
class C
{
Span<int> M()
{
Span<int> s1 = stackalloc int[10];
Span<int> s2 = s1[0..2];
return s2;
}
}";
var comp = CreateCompilationWithIndexAndRangeAndSpan(src);
comp.VerifyDiagnostics(
// (9,16): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope
// return s2;
Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(9, 16));
}
[Fact]
public void PatternIndexAndRangeLengthInaccessible()
{
var src = @"
class B
{
private int Length => 0;
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,15): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = b[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(12, 15),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangeLengthNoGetter()
{
var src = @"
class B
{
public int Length { set { } }
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,15): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = b[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(12, 15),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangeGetLengthInaccessible()
{
var src = @"
class B
{
public int Length { private get => 0; set { } }
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,15): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = b[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(12, 15),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangePatternMethodsInaccessible()
{
var src = @"
class B
{
public int Length => 0;
public int this[int i] { private get => 0; set { } }
private int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,13): error CS0271: The property or indexer 'B.this[int]' cannot be used in this context because the get accessor is inaccessible
// _ = b[^0];
Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b[^0]").WithArguments("B.this[int]").WithLocation(12, 13),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangeStaticLength()
{
var src = @"
class B
{
public static int Length => 0;
public int this[int i] => 0;
private int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,15): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = b[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(12, 15),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangeStaticSlice()
{
var src = @"
class B
{
public int Length => 0;
private static int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): error CS0021: Cannot apply indexing with [] to an expression of type 'B'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadIndexLHS, "b[0..]").WithArguments("B").WithLocation(11, 13)
);
}
[Fact]
public void PatternIndexAndRangeNoGetOffset()
{
var src = @"
namespace System
{
public struct Index
{
public Index(int value, bool fromEnd) { }
public static implicit operator Index(int value) => default;
}
public struct Range
{
public Range(Index start, Index end) { }
public Index Start => default;
public Index End => default;
}
}
class C
{
public int Length => 0;
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
void M()
{
_ = this[^0];
_ = this[0..];
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (23,13): error CS0656: Missing compiler required member 'System.Index.GetOffset'
// _ = this[^0];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "this[^0]").WithArguments("System.Index", "GetOffset").WithLocation(23, 13),
// (24,13): error CS0656: Missing compiler required member 'System.Index.GetOffset'
// _ = this[0..];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "this[0..]").WithArguments("System.Index", "GetOffset").WithLocation(24, 13)
);
}
[Theory]
[InlineData("Start")]
[InlineData("End")]
public void PatternIndexAndRangeNoStartAndEnd(string propertyName)
{
var src = @"
namespace System
{
public struct Index
{
public Index(int value, bool fromEnd) { }
public static implicit operator Index(int value) => default;
public int GetOffset(int length) => 0;
}
public struct Range
{
public Range(Index start, Index end) { }
public Index " + propertyName + @" => default;
}
}
class C
{
public int Length => 0;
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
void M()
{
_ = this[^0];
_ = this[0..];
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (24,13): error CS0656: Missing compiler required member 'System.Range.get_...'
// _ = this[0..];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "this[0..]").WithArguments("System.Range", "get_" + (propertyName == "Start" ? "End" : "Start")).WithLocation(24, 13)
);
}
[Fact]
public void PatternIndexAndRangeNoOptionalParams()
{
var comp = CreateCompilationWithIndexAndRange(@"
class C
{
public int Length => 0;
public int this[int i, int j = 0] => i;
public int Slice(int i, int j, int k = 0) => i;
public void M()
{
_ = this[^0];
_ = this[0..];
}
}");
comp.VerifyDiagnostics(
// (9,18): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = this[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(9, 18),
// (10,18): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = this[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(10, 18));
}
[Fact]
public void PatternIndexAndRangeUseOriginalDefition()
{
var comp = CreateCompilationWithIndexAndRange(@"
struct S1<T>
{
public int Length => 0;
public int this[T t] => 0;
public int Slice(T t, int j) => 0;
}
struct S2<T>
{
public T Length => default;
public int this[int t] => 0;
public int Slice(int t, int j) => 0;
}
class C
{
void M()
{
var s1 = new S1<int>();
_ = s1[^0];
_ = s1[0..];
var s2 = new S2<int>();
_ = s2[^0];
_ = s2[0..];
}
}");
comp.VerifyDiagnostics(
// (19,16): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = s1[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(19, 16),
// (20,16): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = s1[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(20, 16),
// (23,16): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = s2[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(23, 16),
// (24,16): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = s2[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(24, 16));
}
[Fact]
[WorkItem(31889, "https://github.com/dotnet/roslyn/issues/31889")]
public void ArrayRangeIllegalRef()
{
var comp = CreateEmptyCompilation(@"
namespace System
{
public struct Int32 { }
public struct Boolean { }
public class ValueType { }
public class String { }
public class Object { }
public class Void { }
public struct Nullable<T> where T : struct
{
}
public struct Index
{
public Index(int value, bool fromEnd) { }
public static implicit operator Index(int value) => default;
}
public struct Range
{
public Range(Index start, Index end) { }
}
}
namespace System.Runtime.CompilerServices
{
public static class RuntimeHelpers
{
public static T[] GetSubArray<T>(T[] array, Range range) => null;
}
}
public class C {
public ref int[] M(int[] arr) {
ref int[] x = ref arr[0..2];
M(in arr[0..2]);
M(arr[0..2]);
return ref arr[0..2];
}
void M(in int[] arr) { }
}");
comp.VerifyDiagnostics(
// (32,27): error CS1510: A ref or out value must be an assignable variable
// ref int[] x = ref arr[0..2];
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "arr[0..2]").WithLocation(32, 27),
// (33,14): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// M(in arr[0..2]);
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "arr[0..2]").WithLocation(33, 14),
// (35,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref arr[0..2];
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "arr[0..2]").WithLocation(35, 20));
}
[Fact]
[WorkItem(31889, "https://github.com/dotnet/roslyn/issues/31889")]
public void ArrayRangeIllegalRefNoRange()
{
var comp = CreateCompilationWithIndex(@"
public class C {
public void M(int[] arr) {
ref int[] x = ref arr[0..2];
}
}");
comp.VerifyDiagnostics(
// (4,31): error CS0518: Predefined type 'System.Range' is not defined or imported
// ref int[] x = ref arr[0..2];
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0..2").WithArguments("System.Range").WithLocation(4, 31));
}
[Fact]
public void ArrayRangeIndexerNoHelper()
{
var comp = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
public Range(Index start, Index end) { }
}
}
public class C {
public void M(int[] arr) {
var x = arr[0..2];
}
}");
comp.VerifyDiagnostics(
// (11,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray'
// var x = arr[0..2];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "0..2").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "GetSubArray").WithLocation(11, 21));
}
[Fact]
public void ArrayIndexIndexerNoHelper()
{
const string source = @"
class C
{
public void M(int[] arr)
{
var x = arr[^2];
}
}";
var comp = CreateCompilation(source + @"
namespace System
{
public readonly struct Index
{
public Index(int value, bool fromEnd) { }
}
}");
comp.VerifyDiagnostics(
// (6,17): error CS0656: Missing compiler required member 'System.Index.GetOffset'
// var x = arr[^2];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "^2").WithArguments("System.Index", "GetOffset").WithLocation(6, 21));
comp = CreateCompilation(source + @"
namespace System
{
public readonly struct Index
{
public Index(int value, bool fromEnd) { }
public int GetOffset(int length) => 0;
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void StringIndexers()
{
// The string type in our standard references don't have indexers for string or range
var comp = CreateCompilationWithIndexAndRange(@"
class C
{
public void M(string s)
{
var x = s[^0];
var y = s[1..];
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(31889, "https://github.com/dotnet/roslyn/issues/31889")]
public void FromEndIllegalRef()
{
var comp = CreateCompilationWithIndex(@"
using System;
public class C {
public ref Index M() {
ref Index x = ref ^0;
M(in ^0);
M(^0);
return ref ^0;
}
void M(in int[] arr) { }
}");
comp.VerifyDiagnostics(
// (5,27): error CS1510: A ref or out value must be an assignable variable
// ref Index x = ref ^0;
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "^0").WithLocation(5, 27),
// (6,14): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// M(in ^0);
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "^0").WithLocation(6, 14),
// (7,11): error CS1503: Argument 1: cannot convert from 'System.Index' to 'in int[]'
// M(^0);
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "in int[]").WithLocation(7, 11),
// (8,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref ^0;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "^0").WithLocation(8, 20));
}
[Fact]
[WorkItem(31889, "https://github.com/dotnet/roslyn/issues/31889")]
public void FromEndIllegalRefNoIndex()
{
var comp = CreateCompilationWithIndex(@"
public class C {
public void M() {
ref var x = ref ^0;
}
}");
comp.VerifyDiagnostics(
// (4,25): error CS1510: A ref or out value must be an assignable variable
// ref var x = ref ^0;
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "^0").WithLocation(4, 25));
}
[Fact]
public void IndexExpression_TypeNotFound()
{
var compilation = CreateCompilation(@"
class Test
{
void M(int arg)
{
var x = ^arg;
}
}").VerifyDiagnostics(
// (6,17): error CS0656: Missing compiler required member 'System.Index..ctor'
// var x = ^arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "^arg").WithArguments("System.Index", ".ctor").WithLocation(6, 17),
// (6,17): error CS0518: Predefined type 'System.Index' is not defined or imported
// var x = ^arg;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "^arg").WithArguments("System.Index").WithLocation(6, 17));
}
[Fact]
public void IndexExpression_LiftedTypeIsNotNullable()
{
var compilation = CreateCompilation(@"
namespace System
{
public class Index
{
public Index(int value, bool fromEnd) { }
}
}
class Test
{
void M(int? arg)
{
var x = ^arg;
}
}").VerifyDiagnostics(
// (13,17): error CS0453: The type 'Index' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// var x = ^arg;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "^arg").WithArguments("System.Nullable<T>", "T", "System.Index").WithLocation(13, 17));
}
[Fact]
public void IndexExpression_NullableConstructorNotFound()
{
var compilation = CreateEmptyCompilation(@"
namespace System
{
public struct Int32 { }
public struct Boolean { }
public class ValueType { }
public class String { }
public class Object { }
public class Void { }
public struct Nullable<T> where T : struct
{
}
public struct Index
{
public Index(int value, bool fromEnd) { }
}
}
class Test
{
void M(int? arg)
{
var x = ^arg;
}
}").VerifyDiagnostics(
// (22,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor'
// var x = ^arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "^arg").WithArguments("System.Nullable`1", ".ctor").WithLocation(22, 17));
}
[Fact]
public void IndexExpression_ConstructorNotFound()
{
var compilation = CreateCompilation(@"
namespace System
{
public readonly struct Index
{
}
}
class Test
{
void M(int arg)
{
var x = ^arg;
}
}").VerifyDiagnostics(
// (12,17): error CS0656: Missing compiler required member 'System.Index..ctor'
// var x = ^arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "^arg").WithArguments("System.Index", ".ctor").WithLocation(12, 17));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("System.Index", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(expression).Symbol);
}
[Fact]
public void IndexExpression_SemanticModel()
{
var compilation = CreateCompilationWithIndex(@"
class Test
{
void M(int arg)
{
var x = ^arg;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("^", expression.OperatorToken.ToFullString());
Assert.Equal("System.Index", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal("System.Index..ctor(System.Int32 value, [System.Boolean fromEnd = false])", model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void IndexExpression_Nullable_SemanticModel()
{
var compilation = CreateCompilationWithIndex(@"
class Test
{
void M(int? arg)
{
var x = ^arg;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("^", expression.OperatorToken.ToFullString());
Assert.Equal("System.Index?", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal("System.Index..ctor(System.Int32 value, [System.Boolean fromEnd = false])", model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void IndexExpression_InvalidTypes()
{
var compilation = CreateCompilationWithIndex(@"
class Test
{
void M()
{
var x = ^""string"";
var y = ^1.5;
var z = ^true;
}
}").VerifyDiagnostics(
//(6,17): error CS0029: Cannot implicitly convert type 'string' to 'int'
// var x = ^"string";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"^""string""").WithArguments("string", "int").WithLocation(6, 17),
//(7,17): error CS0029: Cannot implicitly convert type 'double' to 'int'
// var y = ^1.5;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "^1.5").WithArguments("double", "int").WithLocation(7, 17),
//(8,17): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// var z = ^true;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "^true").WithArguments("bool", "int").WithLocation(8, 17));
}
[Fact]
public void IndexExpression_NoOperatorOverloading()
{
var compilation = CreateCompilationWithIndex(@"
public class Test
{
public static Test operator ^(Test value) => default;
}").VerifyDiagnostics(
// (4,33): error CS1019: Overloadable unary operator expected
// public static Test operator ^(Test value) => default;
Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "^").WithLocation(4, 33));
}
[Fact]
public void IndexExpression_OlderLanguageVersion()
{
var expected = new[]
{
// (6,17): error CS8652: The feature 'index operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x = ^1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "^1").WithArguments("index operator", "8.0").WithLocation(6, 17)
};
const string source = @"
class Test
{
void M()
{
var x = ^1;
}
}";
var compilation = CreateCompilationWithIndex(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected);
compilation = CreateCompilationWithIndex(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void RangeExpression_RangeNotFound()
{
var compilation = CreateCompilationWithIndex(@"
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics(
// (6,17): error CS0518: Predefined type 'System.Range' is not defined or imported
// var a = 1..2;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1..2").WithArguments("System.Range").WithLocation(6, 17),
// (7,17): error CS0518: Predefined type 'System.Range' is not defined or imported
// var b = 1..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1..").WithArguments("System.Range").WithLocation(7, 17),
// (8,17): error CS0518: Predefined type 'System.Range' is not defined or imported
// var c = ..2;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..2").WithArguments("System.Range").WithLocation(8, 17),
// (9,17): error CS0518: Predefined type 'System.Range' is not defined or imported
// var d = ..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..").WithArguments("System.Range").WithLocation(9, 17));
}
[Fact]
public void RangeExpression_LiftedRangeNotNullable()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public class Range
{
public Range(Index start, Index end) { }
}
}
class Test
{
void M(System.Index? index)
{
var a = index..index;
}
}").VerifyDiagnostics(
// (13,17): error CS0453: The type 'Range' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// var a = index..index;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "index..index").WithArguments("System.Nullable<T>", "T", "System.Range").WithLocation(13, 17));
}
[Fact]
public void RangeExpression_LiftedIndexNotNullable()
{
var compilation = CreateCompilation(@"
namespace System
{
public class Index
{
public Index(int value, bool fromEnd) { }
public static implicit operator Index(int value) => new Index(value, fromEnd: false);
}
public readonly struct Range
{
public Range(Index start, Index end) { }
}
}
class Test
{
void M(int? index)
{
var a = index..index;
}
}").VerifyDiagnostics(
// (18,17): error CS0453: The type 'Index' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// var a = index..index;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "index").WithArguments("System.Nullable<T>", "T", "System.Index").WithLocation(18, 17),
// (18,17): error CS0029: Cannot implicitly convert type 'int?' to 'System.Index?'
// var a = index..index;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "index").WithArguments("int?", "System.Index?").WithLocation(18, 17),
// (18,24): error CS0453: The type 'Index' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// var a = index..index;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "index").WithArguments("System.Nullable<T>", "T", "System.Index").WithLocation(18, 24),
// (18,24): error CS0029: Cannot implicitly convert type 'int?' to 'System.Index?'
// var a = index..index;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "index").WithArguments("int?", "System.Index?").WithLocation(18, 24));
}
[Fact]
public void RangeExpression_WithoutRangeCtor()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
// public Range(Index start, Index end) => default;
public static Range StartAt(Index start) => default;
public static Range EndAt(Index end) => default;
public static Range All => default;
}
}
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics(
// (16,17): error CS0656: Missing compiler required member 'System.Range..ctor'
// var a = 1..2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "1..2").WithArguments("System.Range", ".ctor").WithLocation(16, 17));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expressions = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ToArray();
Assert.Equal(4, expressions.Length);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[0]).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(expressions[0]).Symbol);
Assert.Equal("System.Int32", model.GetTypeInfo(expressions[0].RightOperand).Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(expressions[0].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range", model.GetTypeInfo(expressions[1]).Type.ToTestDisplayString());
Assert.Equal(RangeStartAtSignature, model.GetSymbolInfo(expressions[1]).Symbol.ToTestDisplayString());
Assert.Null(expressions[1].RightOperand);
Assert.Equal("System.Int32", model.GetTypeInfo(expressions[1].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range", model.GetTypeInfo(expressions[2]).Type.ToTestDisplayString());
Assert.Equal(RangeEndAtSignature, model.GetSymbolInfo(expressions[2]).Symbol.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(expressions[2].RightOperand).Type.ToTestDisplayString());
Assert.Null(expressions[2].LeftOperand);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[3]).Type.ToTestDisplayString());
Assert.Equal(RangeAllSignature, model.GetSymbolInfo(expressions[3]).Symbol.ToTestDisplayString());
Assert.Null(expressions[3].RightOperand);
Assert.Null(expressions[3].LeftOperand);
}
[Fact]
public void RangeExpression_NullableConstructorNotFound()
{
var compilation = CreateEmptyCompilation(@"
namespace System
{
public struct Int32 { }
public struct Boolean { }
public class ValueType { }
public class String { }
public class Object { }
public class Void { }
public struct Nullable<T> where T : struct
{
}
public struct Index
{
public Index(int value, bool fromEnd) { }
}
public readonly struct Range
{
public Range(Index start, Index end) { }
}
}
class Test
{
void M(System.Index? arg)
{
var x = arg..arg;
}
}").VerifyDiagnostics(
// (26,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor'
// var x = arg..arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "arg").WithArguments("System.Nullable`1", ".ctor").WithLocation(26, 17),
// (26,22): error CS0656: Missing compiler required member 'System.Nullable`1..ctor'
// var x = arg..arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "arg").WithArguments("System.Nullable`1", ".ctor").WithLocation(26, 22),
// (26,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor'
// var x = arg..arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "arg..arg").WithArguments("System.Nullable`1", ".ctor").WithLocation(26, 17));
}
[Fact]
public void RangeExpression_BooleanNotFound()
{
var compilation = CreateEmptyCompilation(@"
namespace System
{
public struct Int32 { }
public class ValueType { }
public class String { }
public class Object { }
public class Void { }
public struct Nullable<T> where T : struct
{
public Nullable(T value) { }
}
public struct Index
{
}
public readonly struct Range
{
public Range(Index start, Index end) { }
}
}
class Test
{
void M(System.Index? arg)
{
var x = arg..arg;
}
}").VerifyDiagnostics(
// (25,17): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// var x = arg..arg;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "arg..arg").WithArguments("System.Boolean").WithLocation(25, 17));
}
[Fact]
public void RangeExpression_WithoutRangeStartAt()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
public Range(Index start, Index end) { }
// public static Range StartAt(Index start) => default;
public static Range EndAt(Index end) => default;
public static Range All() => default;
}
}
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ElementAt(1);
Assert.Equal("System.Range", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void RangeExpression_WithoutRangeEndAt()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
public Range(Index start, Index end) { }
public static Range StartAt(Index start) => default;
// public static Range EndAt(Index end) => default;
public static Range All() => default;
}
}
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ElementAt(2);
Assert.Equal("System.Range", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void RangeExpression_WithoutRangeAll()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
public Range(Index start, Index end) { }
public static Range StartAt(Index start) => default;
public static Range EndAt(Index end) => default;
// public static Range All() => default;
}
}
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ElementAt(3);
Assert.Equal("System.Range", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void RangeExpression_SemanticModel()
{
var compilation = CreateCompilationWithIndexAndRange(@"
using System;
class Test
{
void M(Index start, Index end)
{
var a = start..end;
var b = start..;
var c = ..end;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expressions = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ToArray();
Assert.Equal(4, expressions.Length);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[0]).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expressions[0]).Symbol.ToTestDisplayString());
Assert.Equal("System.Index", model.GetTypeInfo(expressions[0].RightOperand).Type.ToTestDisplayString());
Assert.Equal("System.Index", model.GetTypeInfo(expressions[0].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range", model.GetTypeInfo(expressions[1]).Type.ToTestDisplayString());
Assert.Equal(RangeStartAtSignature, model.GetSymbolInfo(expressions[1]).Symbol.ToTestDisplayString());
Assert.Null(expressions[1].RightOperand);
Assert.Equal("System.Index", model.GetTypeInfo(expressions[1].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range", model.GetTypeInfo(expressions[2]).Type.ToTestDisplayString());
Assert.Equal(RangeEndAtSignature, model.GetSymbolInfo(expressions[2]).Symbol.ToTestDisplayString());
Assert.Equal("System.Index", model.GetTypeInfo(expressions[2].RightOperand).Type.ToTestDisplayString());
Assert.Null(expressions[2].LeftOperand);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[3]).Type.ToTestDisplayString());
Assert.Equal(RangeAllSignature, model.GetSymbolInfo(expressions[3]).Symbol.ToTestDisplayString());
Assert.Null(expressions[3].RightOperand);
Assert.Null(expressions[3].LeftOperand);
}
[Fact]
public void RangeExpression_Nullable_SemanticModel()
{
var compilation = CreateCompilationWithIndexAndRange(@"
using System;
class Test
{
void M(Index? start, Index? end)
{
var a = start..end;
var b = start..;
var c = ..end;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expressions = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ToArray();
Assert.Equal(4, expressions.Length);
Assert.Equal("System.Range?", model.GetTypeInfo(expressions[0]).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expressions[0]).Symbol.ToTestDisplayString());
Assert.Equal("System.Index?", model.GetTypeInfo(expressions[0].RightOperand).Type.ToTestDisplayString());
Assert.Equal("System.Index?", model.GetTypeInfo(expressions[0].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range?", model.GetTypeInfo(expressions[1]).Type.ToTestDisplayString());
Assert.Equal(RangeStartAtSignature, model.GetSymbolInfo(expressions[1]).Symbol.ToTestDisplayString());
Assert.Null(expressions[1].RightOperand);
Assert.Equal("System.Index?", model.GetTypeInfo(expressions[1].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range?", model.GetTypeInfo(expressions[2]).Type.ToTestDisplayString());
Assert.Equal(RangeEndAtSignature, model.GetSymbolInfo(expressions[2]).Symbol.ToTestDisplayString());
Assert.Equal("System.Index?", model.GetTypeInfo(expressions[2].RightOperand).Type.ToTestDisplayString());
Assert.Null(expressions[2].LeftOperand);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[3]).Type.ToTestDisplayString());
Assert.Equal(RangeAllSignature, model.GetSymbolInfo(expressions[3]).Symbol.ToTestDisplayString());
Assert.Null(expressions[3].RightOperand);
Assert.Null(expressions[3].LeftOperand);
}
[Fact]
public void RangeExpression_InvalidTypes()
{
var compilation = CreateCompilationWithIndexAndRange(@"
class Test
{
void M()
{
var a = 1..""string"";
var b = 1.5..;
var c = ..true;
var d = ..M();
}
}").VerifyDiagnostics(
// (6,20): error CS0029: Cannot implicitly convert type 'string' to 'System.Index'
// var a = 1.."string";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""string""").WithArguments("string", "System.Index").WithLocation(6, 20),
// (7,17): error CS0029: Cannot implicitly convert type 'double' to 'System.Index'
// var b = 1.5..;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.5").WithArguments("double", "System.Index").WithLocation(7, 17),
// (8,19): error CS0029: Cannot implicitly convert type 'bool' to 'System.Index'
// var c = ..true;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "true").WithArguments("bool", "System.Index").WithLocation(8, 19),
// (9,19): error CS0029: Cannot implicitly convert type 'void' to 'System.Index'
// var d = ..M();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "M()").WithArguments("void", "System.Index").WithLocation(9, 19));
}
[Fact]
public void RangeExpression_NoOperatorOverloading()
{
var compilation = CreateCompilationWithIndexAndRange(@"
public class Test
{
public static Test operator ..(Test value) => default;
public static Test operator ..(Test value1, Test value2) => default;
}").VerifyDiagnostics(
// (4,33): error CS1019: Overloadable unary operator expected
// public static Test operator ..(Test value) => default;
Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "..").WithLocation(4, 33),
// (5,33): error CS1020: Overloadable binary operator expected
// public static Test operator ..(Test value1, Test value2) => default;
Diagnostic(ErrorCode.ERR_OvlBinaryOperatorExpected, "..").WithLocation(5, 33));
}
[Fact]
public void RangeExpression_OlderLanguageVersion()
{
const string source = @"
class Test
{
void M()
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}";
var expected = new[]
{
// (6,17): error CS8652: The feature 'range operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var a = 1..2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1..2").WithArguments("range operator", "8.0").WithLocation(6, 17),
// (7,17): error CS8652: The feature 'range operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var b = 1..;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1..").WithArguments("range operator", "8.0").WithLocation(7, 17),
// (8,17): error CS8652: The feature 'range operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var c = ..2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "..2").WithArguments("range operator", "8.0").WithLocation(8, 17),
// (9,17): error CS8652: The feature 'range operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var d = ..;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "..").WithArguments("range operator", "8.0").WithLocation(9, 17)
};
CreateCompilationWithIndexAndRange(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected);
CreateCompilationWithIndexAndRange(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void IndexOnNonTypedNodes()
{
CreateCompilationWithIndex(@"
class Test
{
void M()
{
var a = ^M;
var b = ^null;
var c = ^default;
}
}").VerifyDiagnostics(
// (6,17): error CS0428: Cannot convert method group 'M' to non-delegate type 'int'. Did you intend to invoke the method?
// var a = ^M;
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "^M").WithArguments("M", "int").WithLocation(6, 17),
// (7,17): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// var b = ^null;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "^null").WithArguments("int").WithLocation(7, 17));
}
[Fact]
public void RangeOnNonTypedNodes()
{
CreateCompilationWithIndexAndRange(@"
class Test
{
void M()
{
var a = 0..M;
var b = 0..null;
var c = 0..default;
var d = M..0;
var e = null..0;
var f = default..0;
}
}").VerifyDiagnostics(
// (6,20): error CS0428: Cannot convert method group 'M' to non-delegate type 'Index'. Did you intend to invoke the method?
// var a = 0..M;
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "M").WithArguments("M", "System.Index").WithLocation(6, 20),
// (7,20): error CS0037: Cannot convert null to 'Index' because it is a non-nullable value type
// var b = 0..null;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("System.Index").WithLocation(7, 20),
// (10,17): error CS0428: Cannot convert method group 'M' to non-delegate type 'Index'. Did you intend to invoke the method?
// var d = M..0;
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "M").WithArguments("M", "System.Index").WithLocation(10, 17),
// (11,17): error CS0037: Cannot convert null to 'Index' because it is a non-nullable value type
// var e = null..0;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("System.Index").WithLocation(11, 17));
}
[Fact]
public void Range_OnVarOut_Error()
{
CreateCompilationWithIndexAndRange(@"
using System;
partial class Program
{
static void Main()
{
var result = y..Create(out Index y);
}
static Index Create(out Index y)
{
y = ^2;
return ^1;
}
}").VerifyDiagnostics(
// (7,22): error CS0841: Cannot use local variable 'y' before it is declared
// var result = y..Create(out Index y);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 22));
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void DontAllowNamedArgumentsForImplicitRangeIndexer()
{
CreateCompilationWithIndexAndRangeAndSpan(@"
using System;
public class C
{
public static void M(string text)
{
_ = text[startIndex: 1..^1];
_ = text[range: 1..^1];
_ = text[notEvenTheCorrectName: 1..^1];
_ = new Span<char>(text.ToCharArray())[start: 1..^1];
_ = new Span<char>(text.ToCharArray())[range: 1..^1];
_ = new Span<char>(text.ToCharArray())[notEvenTheCorrectName: 1..^1];
}
}").VerifyDiagnostics(
// (7,18): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = text[startIndex: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "startIndex").WithLocation(7, 18),
// (8,18): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = text[range: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "range").WithLocation(8, 18),
// (9,18): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = text[notEvenTheCorrectName: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "notEvenTheCorrectName").WithLocation(9, 18),
// (10,48): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[start: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "start").WithLocation(10, 48),
// (11,48): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[range: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "range").WithLocation(11, 48),
// (12,48): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[notEvenTheCorrectName: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "notEvenTheCorrectName").WithLocation(12, 48));
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void DontAllowNamedArgumentsForImplicitIndexIndexer()
{
CreateCompilationWithIndexAndRangeAndSpan(@"
using System;
public class C
{
public static void M(string text)
{
_ = text[index: ^1];
_ = text[notEvenTheCorrectName: ^1];
_ = new Span<char>(text.ToCharArray())[index: ^1];
_ = new Span<char>(text.ToCharArray())[notEvenTheCorrectName: ^1];
}
}").VerifyDiagnostics(
// (7,18): error CS8428: Invocation of implicit Index Indexer cannot name the argument.
// _ = text[index: ^1];
Diagnostic(ErrorCode.ERR_ImplicitIndexIndexerWithName, "index").WithLocation(7, 18),
// (8,18): error CS8428: Invocation of implicit Index Indexer cannot name the argument.
// _ = text[notEvenTheCorrectName: ^1];
Diagnostic(ErrorCode.ERR_ImplicitIndexIndexerWithName, "notEvenTheCorrectName").WithLocation(8, 18),
// (9,48): error CS8428: Invocation of implicit Index Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[index: ^1];
Diagnostic(ErrorCode.ERR_ImplicitIndexIndexerWithName, "index").WithLocation(9, 48),
// (10,48): error CS8428: Invocation of implicit Index Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[notEvenTheCorrectName: ^1];
Diagnostic(ErrorCode.ERR_ImplicitIndexIndexerWithName, "notEvenTheCorrectName").WithLocation(10, 48));
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void AllowNamedArgumentsForRealRangeIndexer1()
{
var comp = CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Range range] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[range: 1..^1]);
}
}", options: TestOptions.ReleaseExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void AllowNamedArgumentsForRealRangeIndexer2()
{
var comp = CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Range param] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[param: 1..^1]);
}
}", options: TestOptions.ReleaseExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void DontAllowIncorrectNamedArgumentsForRealRangeIndexer()
{
CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Range range] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[param: 1..^1]);
}
}").VerifyDiagnostics(
// (11,31): error CS1739: The best overload for 'this' does not have a parameter named 'param'
// Console.Write(new A()[param: 1..^1]);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "param").WithArguments("this", "param").WithLocation(11, 31));
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void AllowNamedArgumentsForRealIndexIndexer1()
{
var comp = CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Index index] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[index: ^1]);
}
}", options: TestOptions.ReleaseExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void AllowNamedArgumentsForRealIndexIndexer2()
{
var comp = CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Index param] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[param: ^1]);
}
}", options: TestOptions.ReleaseExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void DontAllowIncorrectNamedArgumentsForRealIndexIndexer()
{
CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Index index] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[param: ^1]);
}
}").VerifyDiagnostics(
// (11,31): error CS1739: The best overload for 'this' does not have a parameter named 'param'
// Console.Write(new A()[param: ^1]);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "param").WithArguments("this", "param").WithLocation(11, 31));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IndexAndRangeTests : CompilingTestBase
{
private const string RangeCtorSignature = "System.Range..ctor(System.Index start, System.Index end)";
private const string RangeStartAtSignature = "System.Range System.Range.StartAt(System.Index start)";
private const string RangeEndAtSignature = "System.Range System.Range.EndAt(System.Index end)";
private const string RangeAllSignature = "System.Range System.Range.All.get";
[Fact]
public void RangeBadIndexerTypes()
{
var src = @"
using System;
public static class Program {
public static void Main() {
var a = new Span<byte>();
var b = a[""str2""];
var c = a[null];
var d = a[Main()];
var e = a[new object()];
Console.WriteLine(zzz[0]);
}
}";
var comp = CreateCompilationWithIndexAndRangeAndSpan(src);
comp.VerifyDiagnostics(
// (7,19): error CS1503: Argument 1: cannot convert from 'string' to 'int'
// var b = a["str2"];
Diagnostic(ErrorCode.ERR_BadArgType, @"""str2""").WithArguments("1", "string", "int").WithLocation(7, 19),
// (8,19): error CS1503: Argument 1: cannot convert from '<null>' to 'int'
// var c = a[null];
Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int").WithLocation(8, 19),
// (9,19): error CS1503: Argument 1: cannot convert from 'void' to 'int'
// var d = a[Main()];
Diagnostic(ErrorCode.ERR_BadArgType, "Main()").WithArguments("1", "void", "int").WithLocation(9, 19),
// (10,19): error CS1503: Argument 1: cannot convert from 'object' to 'int'
// var e = a[new object()];
Diagnostic(ErrorCode.ERR_BadArgType, "new object()").WithArguments("1", "object", "int").WithLocation(10, 19),
// (11,27): error CS0103: The name 'zzz' does not exist in the current context
// Console.WriteLine(zzz[0]);
Diagnostic(ErrorCode.ERR_NameNotInContext, "zzz").WithArguments("zzz").WithLocation(11, 27));
}
[Fact]
public void PatternIndexRangeLangVer()
{
var src = @"
using System;
struct S
{
public int Length => 0;
public int Slice(int x, int y) => 0;
}
class C
{
void M(string s, Index i, Range r)
{
_ = s[i];
_ = s[r];
_ = new S()[r];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics();
comp = CreateCompilationWithIndexAndRange(src, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (12,13): error CS8652: The feature 'index operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// _ = s[i];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "s[i]").WithArguments("index operator", "8.0").WithLocation(12, 13),
// (13,13): error CS8652: The feature 'index operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// _ = s[r];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "s[r]").WithArguments("index operator", "8.0").WithLocation(13, 13),
// (14,13): error CS8652: The feature 'index operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// _ = new S()[r];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "new S()[r]").WithArguments("index operator", "8.0").WithLocation(14, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_01()
{
var src = @"
using System;
struct S
{
public int this[int i] => 0;
public int Length => 0;
public int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i]; // 1, 2
_ = this[r]; // 3, 4
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): warning CS8656: Call to non-readonly member 'S.Length.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1, 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Length.get", "this").WithLocation(11, 13),
// (11,13): warning CS8656: Call to non-readonly member 'S.this[int].get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1, 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.this[int].get", "this").WithLocation(11, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Length.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 3, 4
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Length.get", "this").WithLocation(12, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Slice(int, int)' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 3, 4
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Slice(int, int)", "this").WithLocation(12, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_02()
{
var src = @"
using System;
struct S
{
public int this[int i] => 0;
public readonly int Length => 0;
public int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i]; // 1
_ = this[r]; // 2
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): warning CS8656: Call to non-readonly member 'S.this[int].get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.this[int].get", "this").WithLocation(11, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Slice(int, int)' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Slice(int, int)", "this").WithLocation(12, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_03()
{
var src = @"
using System;
struct S
{
public readonly int this[int i] => 0;
public int Length => 0;
public readonly int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i]; // 1
_ = this[r]; // 2
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): warning CS8656: Call to non-readonly member 'S.Length.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Length.get", "this").WithLocation(11, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Length.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Length.get", "this").WithLocation(12, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_04()
{
var src = @"
using System;
struct S
{
public readonly int this[int i] => 0;
public int Count => 0;
public readonly int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i]; // 1
_ = this[r]; // 2
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): warning CS8656: Call to non-readonly member 'S.Count.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[i]; // 1
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Count.get", "this").WithLocation(11, 13),
// (12,13): warning CS8656: Call to non-readonly member 'S.Count.get' from a 'readonly' member results in an implicit copy of 'this'.
// _ = this[r]; // 2
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "this").WithArguments("S.Count.get", "this").WithLocation(12, 13));
}
[Fact]
public void PatternIndexRangeReadOnly_05()
{
var src = @"
using System;
struct S
{
public readonly int this[int i] => 0;
public readonly int Length => 0;
public readonly int Slice(int x, int y) => 0;
readonly void M(Index i, Range r)
{
_ = this[i];
_ = this[r];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics();
}
[Fact]
public void SpanPatternRangeDelegate()
{
var src = @"
using System;
class C
{
void Throws<T>(Func<T> f) { }
public static void Main()
{
string s = ""abcd"";
Throws(() => new Span<char>(s.ToCharArray())[0..1]);
}
}";
var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (9,9): error CS0306: The type 'Span<char>' may not be used as a type argument
// Throws(() => new Span<char>(s.ToCharArray())[0..1]);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "Throws").WithArguments("System.Span<char>").WithLocation(9, 9));
}
[Fact]
public void PatternIndexNoRefIndexer()
{
var src = @"
struct S
{
public int Length => 0;
public int this[int i] => 0;
}
class C
{
void M(S s)
{
ref readonly int x = ref s[^2];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,34): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// ref readonly int x = ref s[^2];
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "s[^2]").WithArguments("S.this[int]").WithLocation(11, 34));
}
[Fact]
public void PatternRangeSpanNoReturn()
{
var src = @"
using System;
class C
{
Span<int> M()
{
Span<int> s1 = stackalloc int[10];
Span<int> s2 = s1[0..2];
return s2;
}
}";
var comp = CreateCompilationWithIndexAndRangeAndSpan(src);
comp.VerifyDiagnostics(
// (9,16): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope
// return s2;
Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(9, 16));
}
[Fact]
public void PatternIndexAndRangeLengthInaccessible()
{
var src = @"
class B
{
private int Length => 0;
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,15): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = b[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(12, 15),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangeLengthNoGetter()
{
var src = @"
class B
{
public int Length { set { } }
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,15): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = b[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(12, 15),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangeGetLengthInaccessible()
{
var src = @"
class B
{
public int Length { private get => 0; set { } }
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,15): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = b[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(12, 15),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangePatternMethodsInaccessible()
{
var src = @"
class B
{
public int Length => 0;
public int this[int i] { private get => 0; set { } }
private int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,13): error CS0271: The property or indexer 'B.this[int]' cannot be used in this context because the get accessor is inaccessible
// _ = b[^0];
Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b[^0]").WithArguments("B.this[int]").WithLocation(12, 13),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangeStaticLength()
{
var src = @"
class B
{
public static int Length => 0;
public int this[int i] => 0;
private int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[^0];
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (12,15): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = b[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(12, 15),
// (13,15): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(13, 15)
);
}
[Fact]
public void PatternIndexAndRangeStaticSlice()
{
var src = @"
class B
{
public int Length => 0;
private static int Slice(int i, int j) => 0;
}
class C
{
void M(B b)
{
_ = b[0..];
}
}";
var comp = CreateCompilationWithIndexAndRange(src);
comp.VerifyDiagnostics(
// (11,13): error CS0021: Cannot apply indexing with [] to an expression of type 'B'
// _ = b[0..];
Diagnostic(ErrorCode.ERR_BadIndexLHS, "b[0..]").WithArguments("B").WithLocation(11, 13)
);
}
[Fact]
public void PatternIndexAndRangeNoGetOffset()
{
var src = @"
namespace System
{
public struct Index
{
public Index(int value, bool fromEnd) { }
public static implicit operator Index(int value) => default;
}
public struct Range
{
public Range(Index start, Index end) { }
public Index Start => default;
public Index End => default;
}
}
class C
{
public int Length => 0;
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
void M()
{
_ = this[^0];
_ = this[0..];
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (23,13): error CS0656: Missing compiler required member 'System.Index.GetOffset'
// _ = this[^0];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "this[^0]").WithArguments("System.Index", "GetOffset").WithLocation(23, 13),
// (24,13): error CS0656: Missing compiler required member 'System.Index.GetOffset'
// _ = this[0..];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "this[0..]").WithArguments("System.Index", "GetOffset").WithLocation(24, 13)
);
}
[Theory]
[InlineData("Start")]
[InlineData("End")]
public void PatternIndexAndRangeNoStartAndEnd(string propertyName)
{
var src = @"
namespace System
{
public struct Index
{
public Index(int value, bool fromEnd) { }
public static implicit operator Index(int value) => default;
public int GetOffset(int length) => 0;
}
public struct Range
{
public Range(Index start, Index end) { }
public Index " + propertyName + @" => default;
}
}
class C
{
public int Length => 0;
public int this[int i] => 0;
public int Slice(int i, int j) => 0;
void M()
{
_ = this[^0];
_ = this[0..];
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (24,13): error CS0656: Missing compiler required member 'System.Range.get_...'
// _ = this[0..];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "this[0..]").WithArguments("System.Range", "get_" + (propertyName == "Start" ? "End" : "Start")).WithLocation(24, 13)
);
}
[Fact]
public void PatternIndexAndRangeNoOptionalParams()
{
var comp = CreateCompilationWithIndexAndRange(@"
class C
{
public int Length => 0;
public int this[int i, int j = 0] => i;
public int Slice(int i, int j, int k = 0) => i;
public void M()
{
_ = this[^0];
_ = this[0..];
}
}");
comp.VerifyDiagnostics(
// (9,18): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = this[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(9, 18),
// (10,18): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = this[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(10, 18));
}
[Fact]
public void PatternIndexAndRangeUseOriginalDefition()
{
var comp = CreateCompilationWithIndexAndRange(@"
struct S1<T>
{
public int Length => 0;
public int this[T t] => 0;
public int Slice(T t, int j) => 0;
}
struct S2<T>
{
public T Length => default;
public int this[int t] => 0;
public int Slice(int t, int j) => 0;
}
class C
{
void M()
{
var s1 = new S1<int>();
_ = s1[^0];
_ = s1[0..];
var s2 = new S2<int>();
_ = s2[^0];
_ = s2[0..];
}
}");
comp.VerifyDiagnostics(
// (19,16): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = s1[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(19, 16),
// (20,16): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = s1[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(20, 16),
// (23,16): error CS1503: Argument 1: cannot convert from 'System.Index' to 'int'
// _ = s2[^0];
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "int").WithLocation(23, 16),
// (24,16): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int'
// _ = s2[0..];
Diagnostic(ErrorCode.ERR_BadArgType, "0..").WithArguments("1", "System.Range", "int").WithLocation(24, 16));
}
[Fact]
[WorkItem(31889, "https://github.com/dotnet/roslyn/issues/31889")]
public void ArrayRangeIllegalRef()
{
var comp = CreateEmptyCompilation(@"
namespace System
{
public struct Int32 { }
public struct Boolean { }
public class ValueType { }
public class String { }
public class Object { }
public class Void { }
public struct Nullable<T> where T : struct
{
}
public struct Index
{
public Index(int value, bool fromEnd) { }
public static implicit operator Index(int value) => default;
}
public struct Range
{
public Range(Index start, Index end) { }
}
}
namespace System.Runtime.CompilerServices
{
public static class RuntimeHelpers
{
public static T[] GetSubArray<T>(T[] array, Range range) => null;
}
}
public class C {
public ref int[] M(int[] arr) {
ref int[] x = ref arr[0..2];
M(in arr[0..2]);
M(arr[0..2]);
return ref arr[0..2];
}
void M(in int[] arr) { }
}");
comp.VerifyDiagnostics(
// (32,27): error CS1510: A ref or out value must be an assignable variable
// ref int[] x = ref arr[0..2];
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "arr[0..2]").WithLocation(32, 27),
// (33,14): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// M(in arr[0..2]);
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "arr[0..2]").WithLocation(33, 14),
// (35,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref arr[0..2];
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "arr[0..2]").WithLocation(35, 20));
}
[Fact]
[WorkItem(31889, "https://github.com/dotnet/roslyn/issues/31889")]
public void ArrayRangeIllegalRefNoRange()
{
var comp = CreateCompilationWithIndex(@"
public class C {
public void M(int[] arr) {
ref int[] x = ref arr[0..2];
}
}");
comp.VerifyDiagnostics(
// (4,31): error CS0518: Predefined type 'System.Range' is not defined or imported
// ref int[] x = ref arr[0..2];
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "0..2").WithArguments("System.Range").WithLocation(4, 31));
}
[Fact]
public void ArrayRangeIndexerNoHelper()
{
var comp = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
public Range(Index start, Index end) { }
}
}
public class C {
public void M(int[] arr) {
var x = arr[0..2];
}
}");
comp.VerifyDiagnostics(
// (11,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray'
// var x = arr[0..2];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "0..2").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "GetSubArray").WithLocation(11, 21));
}
[Fact]
public void ArrayIndexIndexerNoHelper()
{
const string source = @"
class C
{
public void M(int[] arr)
{
var x = arr[^2];
}
}";
var comp = CreateCompilation(source + @"
namespace System
{
public readonly struct Index
{
public Index(int value, bool fromEnd) { }
}
}");
comp.VerifyDiagnostics(
// (6,17): error CS0656: Missing compiler required member 'System.Index.GetOffset'
// var x = arr[^2];
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "^2").WithArguments("System.Index", "GetOffset").WithLocation(6, 21));
comp = CreateCompilation(source + @"
namespace System
{
public readonly struct Index
{
public Index(int value, bool fromEnd) { }
public int GetOffset(int length) => 0;
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void StringIndexers()
{
// The string type in our standard references don't have indexers for string or range
var comp = CreateCompilationWithIndexAndRange(@"
class C
{
public void M(string s)
{
var x = s[^0];
var y = s[1..];
}
}");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(31889, "https://github.com/dotnet/roslyn/issues/31889")]
public void FromEndIllegalRef()
{
var comp = CreateCompilationWithIndex(@"
using System;
public class C {
public ref Index M() {
ref Index x = ref ^0;
M(in ^0);
M(^0);
return ref ^0;
}
void M(in int[] arr) { }
}");
comp.VerifyDiagnostics(
// (5,27): error CS1510: A ref or out value must be an assignable variable
// ref Index x = ref ^0;
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "^0").WithLocation(5, 27),
// (6,14): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// M(in ^0);
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "^0").WithLocation(6, 14),
// (7,11): error CS1503: Argument 1: cannot convert from 'System.Index' to 'in int[]'
// M(^0);
Diagnostic(ErrorCode.ERR_BadArgType, "^0").WithArguments("1", "System.Index", "in int[]").WithLocation(7, 11),
// (8,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref ^0;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "^0").WithLocation(8, 20));
}
[Fact]
[WorkItem(31889, "https://github.com/dotnet/roslyn/issues/31889")]
public void FromEndIllegalRefNoIndex()
{
var comp = CreateCompilationWithIndex(@"
public class C {
public void M() {
ref var x = ref ^0;
}
}");
comp.VerifyDiagnostics(
// (4,25): error CS1510: A ref or out value must be an assignable variable
// ref var x = ref ^0;
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "^0").WithLocation(4, 25));
}
[Fact]
public void IndexExpression_TypeNotFound()
{
var compilation = CreateCompilation(@"
class Test
{
void M(int arg)
{
var x = ^arg;
}
}").VerifyDiagnostics(
// (6,17): error CS0656: Missing compiler required member 'System.Index..ctor'
// var x = ^arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "^arg").WithArguments("System.Index", ".ctor").WithLocation(6, 17),
// (6,17): error CS0518: Predefined type 'System.Index' is not defined or imported
// var x = ^arg;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "^arg").WithArguments("System.Index").WithLocation(6, 17));
}
[Fact]
public void IndexExpression_LiftedTypeIsNotNullable()
{
var compilation = CreateCompilation(@"
namespace System
{
public class Index
{
public Index(int value, bool fromEnd) { }
}
}
class Test
{
void M(int? arg)
{
var x = ^arg;
}
}").VerifyDiagnostics(
// (13,17): error CS0453: The type 'Index' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// var x = ^arg;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "^arg").WithArguments("System.Nullable<T>", "T", "System.Index").WithLocation(13, 17));
}
[Fact]
public void IndexExpression_NullableConstructorNotFound()
{
var compilation = CreateEmptyCompilation(@"
namespace System
{
public struct Int32 { }
public struct Boolean { }
public class ValueType { }
public class String { }
public class Object { }
public class Void { }
public struct Nullable<T> where T : struct
{
}
public struct Index
{
public Index(int value, bool fromEnd) { }
}
}
class Test
{
void M(int? arg)
{
var x = ^arg;
}
}").VerifyDiagnostics(
// (22,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor'
// var x = ^arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "^arg").WithArguments("System.Nullable`1", ".ctor").WithLocation(22, 17));
}
[Fact]
public void IndexExpression_ConstructorNotFound()
{
var compilation = CreateCompilation(@"
namespace System
{
public readonly struct Index
{
}
}
class Test
{
void M(int arg)
{
var x = ^arg;
}
}").VerifyDiagnostics(
// (12,17): error CS0656: Missing compiler required member 'System.Index..ctor'
// var x = ^arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "^arg").WithArguments("System.Index", ".ctor").WithLocation(12, 17));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("System.Index", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(expression).Symbol);
}
[Fact]
public void IndexExpression_SemanticModel()
{
var compilation = CreateCompilationWithIndex(@"
class Test
{
void M(int arg)
{
var x = ^arg;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("^", expression.OperatorToken.ToFullString());
Assert.Equal("System.Index", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal("System.Index..ctor(System.Int32 value, [System.Boolean fromEnd = false])", model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void IndexExpression_Nullable_SemanticModel()
{
var compilation = CreateCompilationWithIndex(@"
class Test
{
void M(int? arg)
{
var x = ^arg;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("^", expression.OperatorToken.ToFullString());
Assert.Equal("System.Index?", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal("System.Index..ctor(System.Int32 value, [System.Boolean fromEnd = false])", model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void IndexExpression_InvalidTypes()
{
var compilation = CreateCompilationWithIndex(@"
class Test
{
void M()
{
var x = ^""string"";
var y = ^1.5;
var z = ^true;
}
}").VerifyDiagnostics(
//(6,17): error CS0029: Cannot implicitly convert type 'string' to 'int'
// var x = ^"string";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"^""string""").WithArguments("string", "int").WithLocation(6, 17),
//(7,17): error CS0029: Cannot implicitly convert type 'double' to 'int'
// var y = ^1.5;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "^1.5").WithArguments("double", "int").WithLocation(7, 17),
//(8,17): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// var z = ^true;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "^true").WithArguments("bool", "int").WithLocation(8, 17));
}
[Fact]
public void IndexExpression_NoOperatorOverloading()
{
var compilation = CreateCompilationWithIndex(@"
public class Test
{
public static Test operator ^(Test value) => default;
}").VerifyDiagnostics(
// (4,33): error CS1019: Overloadable unary operator expected
// public static Test operator ^(Test value) => default;
Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "^").WithLocation(4, 33));
}
[Fact]
public void IndexExpression_OlderLanguageVersion()
{
var expected = new[]
{
// (6,17): error CS8652: The feature 'index operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var x = ^1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "^1").WithArguments("index operator", "8.0").WithLocation(6, 17)
};
const string source = @"
class Test
{
void M()
{
var x = ^1;
}
}";
var compilation = CreateCompilationWithIndex(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected);
compilation = CreateCompilationWithIndex(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void RangeExpression_RangeNotFound()
{
var compilation = CreateCompilationWithIndex(@"
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics(
// (6,17): error CS0518: Predefined type 'System.Range' is not defined or imported
// var a = 1..2;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1..2").WithArguments("System.Range").WithLocation(6, 17),
// (7,17): error CS0518: Predefined type 'System.Range' is not defined or imported
// var b = 1..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1..").WithArguments("System.Range").WithLocation(7, 17),
// (8,17): error CS0518: Predefined type 'System.Range' is not defined or imported
// var c = ..2;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..2").WithArguments("System.Range").WithLocation(8, 17),
// (9,17): error CS0518: Predefined type 'System.Range' is not defined or imported
// var d = ..;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..").WithArguments("System.Range").WithLocation(9, 17));
}
[Fact]
public void RangeExpression_LiftedRangeNotNullable()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public class Range
{
public Range(Index start, Index end) { }
}
}
class Test
{
void M(System.Index? index)
{
var a = index..index;
}
}").VerifyDiagnostics(
// (13,17): error CS0453: The type 'Range' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// var a = index..index;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "index..index").WithArguments("System.Nullable<T>", "T", "System.Range").WithLocation(13, 17));
}
[Fact]
public void RangeExpression_LiftedIndexNotNullable()
{
var compilation = CreateCompilation(@"
namespace System
{
public class Index
{
public Index(int value, bool fromEnd) { }
public static implicit operator Index(int value) => new Index(value, fromEnd: false);
}
public readonly struct Range
{
public Range(Index start, Index end) { }
}
}
class Test
{
void M(int? index)
{
var a = index..index;
}
}").VerifyDiagnostics(
// (18,17): error CS0453: The type 'Index' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// var a = index..index;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "index").WithArguments("System.Nullable<T>", "T", "System.Index").WithLocation(18, 17),
// (18,17): error CS0029: Cannot implicitly convert type 'int?' to 'System.Index?'
// var a = index..index;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "index").WithArguments("int?", "System.Index?").WithLocation(18, 17),
// (18,24): error CS0453: The type 'Index' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
// var a = index..index;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "index").WithArguments("System.Nullable<T>", "T", "System.Index").WithLocation(18, 24),
// (18,24): error CS0029: Cannot implicitly convert type 'int?' to 'System.Index?'
// var a = index..index;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "index").WithArguments("int?", "System.Index?").WithLocation(18, 24));
}
[Fact]
public void RangeExpression_WithoutRangeCtor()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
// public Range(Index start, Index end) => default;
public static Range StartAt(Index start) => default;
public static Range EndAt(Index end) => default;
public static Range All => default;
}
}
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics(
// (16,17): error CS0656: Missing compiler required member 'System.Range..ctor'
// var a = 1..2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "1..2").WithArguments("System.Range", ".ctor").WithLocation(16, 17));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expressions = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ToArray();
Assert.Equal(4, expressions.Length);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[0]).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(expressions[0]).Symbol);
Assert.Equal("System.Int32", model.GetTypeInfo(expressions[0].RightOperand).Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(expressions[0].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range", model.GetTypeInfo(expressions[1]).Type.ToTestDisplayString());
Assert.Equal(RangeStartAtSignature, model.GetSymbolInfo(expressions[1]).Symbol.ToTestDisplayString());
Assert.Null(expressions[1].RightOperand);
Assert.Equal("System.Int32", model.GetTypeInfo(expressions[1].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range", model.GetTypeInfo(expressions[2]).Type.ToTestDisplayString());
Assert.Equal(RangeEndAtSignature, model.GetSymbolInfo(expressions[2]).Symbol.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(expressions[2].RightOperand).Type.ToTestDisplayString());
Assert.Null(expressions[2].LeftOperand);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[3]).Type.ToTestDisplayString());
Assert.Equal(RangeAllSignature, model.GetSymbolInfo(expressions[3]).Symbol.ToTestDisplayString());
Assert.Null(expressions[3].RightOperand);
Assert.Null(expressions[3].LeftOperand);
}
[Fact]
public void RangeExpression_NullableConstructorNotFound()
{
var compilation = CreateEmptyCompilation(@"
namespace System
{
public struct Int32 { }
public struct Boolean { }
public class ValueType { }
public class String { }
public class Object { }
public class Void { }
public struct Nullable<T> where T : struct
{
}
public struct Index
{
public Index(int value, bool fromEnd) { }
}
public readonly struct Range
{
public Range(Index start, Index end) { }
}
}
class Test
{
void M(System.Index? arg)
{
var x = arg..arg;
}
}").VerifyDiagnostics(
// (26,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor'
// var x = arg..arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "arg").WithArguments("System.Nullable`1", ".ctor").WithLocation(26, 17),
// (26,22): error CS0656: Missing compiler required member 'System.Nullable`1..ctor'
// var x = arg..arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "arg").WithArguments("System.Nullable`1", ".ctor").WithLocation(26, 22),
// (26,17): error CS0656: Missing compiler required member 'System.Nullable`1..ctor'
// var x = arg..arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "arg..arg").WithArguments("System.Nullable`1", ".ctor").WithLocation(26, 17));
}
[Fact]
public void RangeExpression_BooleanNotFound()
{
var compilation = CreateEmptyCompilation(@"
namespace System
{
public struct Int32 { }
public class ValueType { }
public class String { }
public class Object { }
public class Void { }
public struct Nullable<T> where T : struct
{
public Nullable(T value) { }
}
public struct Index
{
}
public readonly struct Range
{
public Range(Index start, Index end) { }
}
}
class Test
{
void M(System.Index? arg)
{
var x = arg..arg;
}
}").VerifyDiagnostics(
// (25,17): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// var x = arg..arg;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "arg..arg").WithArguments("System.Boolean").WithLocation(25, 17));
}
[Fact]
public void RangeExpression_WithoutRangeStartAt()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
public Range(Index start, Index end) { }
// public static Range StartAt(Index start) => default;
public static Range EndAt(Index end) => default;
public static Range All() => default;
}
}
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ElementAt(1);
Assert.Equal("System.Range", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void RangeExpression_WithoutRangeEndAt()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
public Range(Index start, Index end) { }
public static Range StartAt(Index start) => default;
// public static Range EndAt(Index end) => default;
public static Range All() => default;
}
}
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ElementAt(2);
Assert.Equal("System.Range", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void RangeExpression_WithoutRangeAll()
{
var compilation = CreateCompilationWithIndex(@"
namespace System
{
public readonly struct Range
{
public Range(Index start, Index end) { }
public static Range StartAt(Index start) => default;
public static Range EndAt(Index end) => default;
// public static Range All() => default;
}
}
class Test
{
void M(int arg)
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expression = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ElementAt(3);
Assert.Equal("System.Range", model.GetTypeInfo(expression).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expression).Symbol.ToTestDisplayString());
}
[Fact]
public void RangeExpression_SemanticModel()
{
var compilation = CreateCompilationWithIndexAndRange(@"
using System;
class Test
{
void M(Index start, Index end)
{
var a = start..end;
var b = start..;
var c = ..end;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expressions = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ToArray();
Assert.Equal(4, expressions.Length);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[0]).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expressions[0]).Symbol.ToTestDisplayString());
Assert.Equal("System.Index", model.GetTypeInfo(expressions[0].RightOperand).Type.ToTestDisplayString());
Assert.Equal("System.Index", model.GetTypeInfo(expressions[0].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range", model.GetTypeInfo(expressions[1]).Type.ToTestDisplayString());
Assert.Equal(RangeStartAtSignature, model.GetSymbolInfo(expressions[1]).Symbol.ToTestDisplayString());
Assert.Null(expressions[1].RightOperand);
Assert.Equal("System.Index", model.GetTypeInfo(expressions[1].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range", model.GetTypeInfo(expressions[2]).Type.ToTestDisplayString());
Assert.Equal(RangeEndAtSignature, model.GetSymbolInfo(expressions[2]).Symbol.ToTestDisplayString());
Assert.Equal("System.Index", model.GetTypeInfo(expressions[2].RightOperand).Type.ToTestDisplayString());
Assert.Null(expressions[2].LeftOperand);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[3]).Type.ToTestDisplayString());
Assert.Equal(RangeAllSignature, model.GetSymbolInfo(expressions[3]).Symbol.ToTestDisplayString());
Assert.Null(expressions[3].RightOperand);
Assert.Null(expressions[3].LeftOperand);
}
[Fact]
public void RangeExpression_Nullable_SemanticModel()
{
var compilation = CreateCompilationWithIndexAndRange(@"
using System;
class Test
{
void M(Index? start, Index? end)
{
var a = start..end;
var b = start..;
var c = ..end;
var d = ..;
}
}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var expressions = tree.GetRoot().DescendantNodes().OfType<RangeExpressionSyntax>().ToArray();
Assert.Equal(4, expressions.Length);
Assert.Equal("System.Range?", model.GetTypeInfo(expressions[0]).Type.ToTestDisplayString());
Assert.Equal(RangeCtorSignature, model.GetSymbolInfo(expressions[0]).Symbol.ToTestDisplayString());
Assert.Equal("System.Index?", model.GetTypeInfo(expressions[0].RightOperand).Type.ToTestDisplayString());
Assert.Equal("System.Index?", model.GetTypeInfo(expressions[0].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range?", model.GetTypeInfo(expressions[1]).Type.ToTestDisplayString());
Assert.Equal(RangeStartAtSignature, model.GetSymbolInfo(expressions[1]).Symbol.ToTestDisplayString());
Assert.Null(expressions[1].RightOperand);
Assert.Equal("System.Index?", model.GetTypeInfo(expressions[1].LeftOperand).Type.ToTestDisplayString());
Assert.Equal("System.Range?", model.GetTypeInfo(expressions[2]).Type.ToTestDisplayString());
Assert.Equal(RangeEndAtSignature, model.GetSymbolInfo(expressions[2]).Symbol.ToTestDisplayString());
Assert.Equal("System.Index?", model.GetTypeInfo(expressions[2].RightOperand).Type.ToTestDisplayString());
Assert.Null(expressions[2].LeftOperand);
Assert.Equal("System.Range", model.GetTypeInfo(expressions[3]).Type.ToTestDisplayString());
Assert.Equal(RangeAllSignature, model.GetSymbolInfo(expressions[3]).Symbol.ToTestDisplayString());
Assert.Null(expressions[3].RightOperand);
Assert.Null(expressions[3].LeftOperand);
}
[Fact]
public void RangeExpression_InvalidTypes()
{
var compilation = CreateCompilationWithIndexAndRange(@"
class Test
{
void M()
{
var a = 1..""string"";
var b = 1.5..;
var c = ..true;
var d = ..M();
}
}").VerifyDiagnostics(
// (6,20): error CS0029: Cannot implicitly convert type 'string' to 'System.Index'
// var a = 1.."string";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""string""").WithArguments("string", "System.Index").WithLocation(6, 20),
// (7,17): error CS0029: Cannot implicitly convert type 'double' to 'System.Index'
// var b = 1.5..;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.5").WithArguments("double", "System.Index").WithLocation(7, 17),
// (8,19): error CS0029: Cannot implicitly convert type 'bool' to 'System.Index'
// var c = ..true;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "true").WithArguments("bool", "System.Index").WithLocation(8, 19),
// (9,19): error CS0029: Cannot implicitly convert type 'void' to 'System.Index'
// var d = ..M();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "M()").WithArguments("void", "System.Index").WithLocation(9, 19));
}
[Fact]
public void RangeExpression_NoOperatorOverloading()
{
var compilation = CreateCompilationWithIndexAndRange(@"
public class Test
{
public static Test operator ..(Test value) => default;
public static Test operator ..(Test value1, Test value2) => default;
}").VerifyDiagnostics(
// (4,33): error CS1019: Overloadable unary operator expected
// public static Test operator ..(Test value) => default;
Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "..").WithLocation(4, 33),
// (5,33): error CS1020: Overloadable binary operator expected
// public static Test operator ..(Test value1, Test value2) => default;
Diagnostic(ErrorCode.ERR_OvlBinaryOperatorExpected, "..").WithLocation(5, 33));
}
[Fact]
public void RangeExpression_OlderLanguageVersion()
{
const string source = @"
class Test
{
void M()
{
var a = 1..2;
var b = 1..;
var c = ..2;
var d = ..;
}
}";
var expected = new[]
{
// (6,17): error CS8652: The feature 'range operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var a = 1..2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1..2").WithArguments("range operator", "8.0").WithLocation(6, 17),
// (7,17): error CS8652: The feature 'range operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var b = 1..;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1..").WithArguments("range operator", "8.0").WithLocation(7, 17),
// (8,17): error CS8652: The feature 'range operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var c = ..2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "..2").WithArguments("range operator", "8.0").WithLocation(8, 17),
// (9,17): error CS8652: The feature 'range operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// var d = ..;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "..").WithArguments("range operator", "8.0").WithLocation(9, 17)
};
CreateCompilationWithIndexAndRange(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected);
CreateCompilationWithIndexAndRange(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void IndexOnNonTypedNodes()
{
CreateCompilationWithIndex(@"
class Test
{
void M()
{
var a = ^M;
var b = ^null;
var c = ^default;
}
}").VerifyDiagnostics(
// (6,17): error CS0428: Cannot convert method group 'M' to non-delegate type 'int'. Did you intend to invoke the method?
// var a = ^M;
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "^M").WithArguments("M", "int").WithLocation(6, 17),
// (7,17): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// var b = ^null;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "^null").WithArguments("int").WithLocation(7, 17));
}
[Fact]
public void RangeOnNonTypedNodes()
{
CreateCompilationWithIndexAndRange(@"
class Test
{
void M()
{
var a = 0..M;
var b = 0..null;
var c = 0..default;
var d = M..0;
var e = null..0;
var f = default..0;
}
}").VerifyDiagnostics(
// (6,20): error CS0428: Cannot convert method group 'M' to non-delegate type 'Index'. Did you intend to invoke the method?
// var a = 0..M;
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "M").WithArguments("M", "System.Index").WithLocation(6, 20),
// (7,20): error CS0037: Cannot convert null to 'Index' because it is a non-nullable value type
// var b = 0..null;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("System.Index").WithLocation(7, 20),
// (10,17): error CS0428: Cannot convert method group 'M' to non-delegate type 'Index'. Did you intend to invoke the method?
// var d = M..0;
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "M").WithArguments("M", "System.Index").WithLocation(10, 17),
// (11,17): error CS0037: Cannot convert null to 'Index' because it is a non-nullable value type
// var e = null..0;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("System.Index").WithLocation(11, 17));
}
[Fact]
public void Range_OnVarOut_Error()
{
CreateCompilationWithIndexAndRange(@"
using System;
partial class Program
{
static void Main()
{
var result = y..Create(out Index y);
}
static Index Create(out Index y)
{
y = ^2;
return ^1;
}
}").VerifyDiagnostics(
// (7,22): error CS0841: Cannot use local variable 'y' before it is declared
// var result = y..Create(out Index y);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 22));
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void DontAllowNamedArgumentsForImplicitRangeIndexer()
{
CreateCompilationWithIndexAndRangeAndSpan(@"
using System;
public class C
{
public static void M(string text)
{
_ = text[startIndex: 1..^1];
_ = text[range: 1..^1];
_ = text[notEvenTheCorrectName: 1..^1];
_ = new Span<char>(text.ToCharArray())[start: 1..^1];
_ = new Span<char>(text.ToCharArray())[range: 1..^1];
_ = new Span<char>(text.ToCharArray())[notEvenTheCorrectName: 1..^1];
}
}").VerifyDiagnostics(
// (7,18): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = text[startIndex: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "startIndex").WithLocation(7, 18),
// (8,18): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = text[range: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "range").WithLocation(8, 18),
// (9,18): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = text[notEvenTheCorrectName: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "notEvenTheCorrectName").WithLocation(9, 18),
// (10,48): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[start: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "start").WithLocation(10, 48),
// (11,48): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[range: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "range").WithLocation(11, 48),
// (12,48): error CS8429: Invocation of implicit Range Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[notEvenTheCorrectName: 1..^1];
Diagnostic(ErrorCode.ERR_ImplicitRangeIndexerWithName, "notEvenTheCorrectName").WithLocation(12, 48));
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void DontAllowNamedArgumentsForImplicitIndexIndexer()
{
CreateCompilationWithIndexAndRangeAndSpan(@"
using System;
public class C
{
public static void M(string text)
{
_ = text[index: ^1];
_ = text[notEvenTheCorrectName: ^1];
_ = new Span<char>(text.ToCharArray())[index: ^1];
_ = new Span<char>(text.ToCharArray())[notEvenTheCorrectName: ^1];
}
}").VerifyDiagnostics(
// (7,18): error CS8428: Invocation of implicit Index Indexer cannot name the argument.
// _ = text[index: ^1];
Diagnostic(ErrorCode.ERR_ImplicitIndexIndexerWithName, "index").WithLocation(7, 18),
// (8,18): error CS8428: Invocation of implicit Index Indexer cannot name the argument.
// _ = text[notEvenTheCorrectName: ^1];
Diagnostic(ErrorCode.ERR_ImplicitIndexIndexerWithName, "notEvenTheCorrectName").WithLocation(8, 18),
// (9,48): error CS8428: Invocation of implicit Index Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[index: ^1];
Diagnostic(ErrorCode.ERR_ImplicitIndexIndexerWithName, "index").WithLocation(9, 48),
// (10,48): error CS8428: Invocation of implicit Index Indexer cannot name the argument.
// _ = new Span<char>(text.ToCharArray())[notEvenTheCorrectName: ^1];
Diagnostic(ErrorCode.ERR_ImplicitIndexIndexerWithName, "notEvenTheCorrectName").WithLocation(10, 48));
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void AllowNamedArgumentsForRealRangeIndexer1()
{
var comp = CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Range range] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[range: 1..^1]);
}
}", options: TestOptions.ReleaseExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void AllowNamedArgumentsForRealRangeIndexer2()
{
var comp = CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Range param] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[param: 1..^1]);
}
}", options: TestOptions.ReleaseExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void DontAllowIncorrectNamedArgumentsForRealRangeIndexer()
{
CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Range range] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[param: 1..^1]);
}
}").VerifyDiagnostics(
// (11,31): error CS1739: The best overload for 'this' does not have a parameter named 'param'
// Console.Write(new A()[param: 1..^1]);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "param").WithArguments("this", "param").WithLocation(11, 31));
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void AllowNamedArgumentsForRealIndexIndexer1()
{
var comp = CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Index index] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[index: ^1]);
}
}", options: TestOptions.ReleaseExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void AllowNamedArgumentsForRealIndexIndexer2()
{
var comp = CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Index param] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[param: ^1]);
}
}", options: TestOptions.ReleaseExe).VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact, WorkItem(39852, "https://github.com/dotnet/roslyn/issues/39852")]
public void DontAllowIncorrectNamedArgumentsForRealIndexIndexer()
{
CreateCompilationWithIndexAndRange(@"
using System;
public class A
{
public int this[Index index] => 42;
}
public class C
{
public static void Main()
{
Console.Write(new A()[param: ^1]);
}
}").VerifyDiagnostics(
// (11,31): error CS1739: The best overload for 'this' does not have a parameter named 'param'
// Console.Write(new A()[param: ^1]);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "param").WithArguments("this", "param").WithLocation(11, 31));
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.Empty.Collection.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;
namespace Roslyn.Utilities
{
internal static partial class SpecializedCollections
{
private static partial class Empty
{
internal class Collection<T> : Enumerable<T>, ICollection<T>
{
public static readonly ICollection<T> Instance = new Collection<T>();
protected Collection()
{
}
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
}
public int Count => 0;
public bool IsReadOnly => true;
public bool Remove(T item)
{
throw new NotSupportedException();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Roslyn.Utilities
{
internal static partial class SpecializedCollections
{
private static partial class Empty
{
internal class Collection<T> : Enumerable<T>, ICollection<T>
{
public static readonly ICollection<T> Instance = new Collection<T>();
protected Collection()
{
}
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
}
public int Count => 0;
public bool IsReadOnly => true;
public bool Remove(T item)
{
throw new NotSupportedException();
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/VisualStudio/VisualBasic/Impl/Options/AutomationObject/AutomationObject.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.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
<ComVisible(True)>
Partial Public Class AutomationObject
Inherits AbstractAutomationObject
Friend Sub New(workspace As Workspace)
MyBase.New(workspace, LanguageNames.VisualBasic)
End Sub
Private Overloads Function GetBooleanOption(key As PerLanguageOption2(Of Boolean)) As Boolean
Return GetOption(key)
End Function
Private Overloads Function GetBooleanOption(key As Option2(Of Boolean)) As Boolean
Return GetOption(key)
End Function
Private Overloads Sub SetBooleanOption(key As PerLanguageOption2(Of Boolean), value As Boolean)
SetOption(key, value)
End Sub
Private Overloads Sub SetBooleanOption(key As Option2(Of Boolean), value As Boolean)
SetOption(key, value)
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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
<ComVisible(True)>
Partial Public Class AutomationObject
Inherits AbstractAutomationObject
Friend Sub New(workspace As Workspace)
MyBase.New(workspace, LanguageNames.VisualBasic)
End Sub
Private Overloads Function GetBooleanOption(key As PerLanguageOption2(Of Boolean)) As Boolean
Return GetOption(key)
End Function
Private Overloads Function GetBooleanOption(key As Option2(Of Boolean)) As Boolean
Return GetOption(key)
End Function
Private Overloads Sub SetBooleanOption(key As PerLanguageOption2(Of Boolean), value As Boolean)
SetOption(key, value)
End Sub
Private Overloads Sub SetBooleanOption(key As Option2(Of Boolean), value As Boolean)
SetOption(key, value)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Tools/BuildValidator/xlf/BuildValidatorResources.ja.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="ja" original="../BuildValidatorResources.resx">
<body>
<trans-unit id="Assemblies_to_be_excluded_substring_match">
<source>Assemblies to be excluded (substring match)</source>
<target state="new">Assemblies to be excluded (substring match)</target>
<note />
</trans-unit>
<trans-unit id="Do_not_output_log_information_to_console">
<source>Do not output log information to console</source>
<target state="new">Do not output log information to console</target>
<note />
</trans-unit>
<trans-unit id="Output_debug_info_when_rebuild_is_not_equal_to_the_original">
<source>Output debug info when rebuild is not equal to the original</source>
<target state="new">Output debug info when rebuild is not equal to the original</target>
<note />
</trans-unit>
<trans-unit id="Output_verbose_log_information">
<source>Output verbose log information</source>
<target state="new">Output verbose log information</target>
<note />
</trans-unit>
<trans-unit id="Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times">
<source>Path to assemblies to rebuild (can be specified one or more times)</source>
<target state="new">Path to assemblies to rebuild (can be specified one or more times)</target>
<note />
</trans-unit>
<trans-unit id="Path_to_output_debug_info">
<source>Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</source>
<target state="new">Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</target>
<note />
</trans-unit>
<trans-unit id="Path_to_referenced_assemblies_can_be_specified_zero_or_more_times">
<source>Path to referenced assemblies (can be specified zero or more times)</source>
<target state="new">Path to referenced assemblies (can be specified zero or more times)</target>
<note />
</trans-unit>
<trans-unit id="Path_to_sources_to_use_in_rebuild">
<source>Path to sources to use in rebuild</source>
<target state="new">Path to sources to use in rebuild</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="ja" original="../BuildValidatorResources.resx">
<body>
<trans-unit id="Assemblies_to_be_excluded_substring_match">
<source>Assemblies to be excluded (substring match)</source>
<target state="new">Assemblies to be excluded (substring match)</target>
<note />
</trans-unit>
<trans-unit id="Do_not_output_log_information_to_console">
<source>Do not output log information to console</source>
<target state="new">Do not output log information to console</target>
<note />
</trans-unit>
<trans-unit id="Output_debug_info_when_rebuild_is_not_equal_to_the_original">
<source>Output debug info when rebuild is not equal to the original</source>
<target state="new">Output debug info when rebuild is not equal to the original</target>
<note />
</trans-unit>
<trans-unit id="Output_verbose_log_information">
<source>Output verbose log information</source>
<target state="new">Output verbose log information</target>
<note />
</trans-unit>
<trans-unit id="Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times">
<source>Path to assemblies to rebuild (can be specified one or more times)</source>
<target state="new">Path to assemblies to rebuild (can be specified one or more times)</target>
<note />
</trans-unit>
<trans-unit id="Path_to_output_debug_info">
<source>Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</source>
<target state="new">Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</target>
<note />
</trans-unit>
<trans-unit id="Path_to_referenced_assemblies_can_be_specified_zero_or_more_times">
<source>Path to referenced assemblies (can be specified zero or more times)</source>
<target state="new">Path to referenced assemblies (can be specified zero or more times)</target>
<note />
</trans-unit>
<trans-unit id="Path_to_sources_to_use_in_rebuild">
<source>Path to sources to use in rebuild</source>
<target state="new">Path to sources to use in rebuild</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Workspaces/VisualBasic/Portable/CodeGeneration/NamespaceGenerator.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.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module NamespaceGenerator
Public Function AddNamespaceTo(service As ICodeGenerationService,
destination As CompilationUnitSyntax,
[namespace] As INamespaceSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean),
cancellationToken As CancellationToken) As CompilationUnitSyntax
Dim declaration = GenerateNamespaceDeclaration(service, [namespace], options, cancellationToken)
If Not TypeOf declaration Is NamespaceBlockSyntax Then
Throw New ArgumentException(VBWorkspaceResources.Namespace_can_not_be_added_in_this_destination)
End If
Dim members = Insert(destination.Members, DirectCast(declaration, StatementSyntax), options, availableIndices)
Return destination.WithMembers(members)
End Function
Public Function AddNamespaceTo(service As ICodeGenerationService,
destination As NamespaceBlockSyntax,
[namespace] As INamespaceSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean),
cancellationToken As CancellationToken) As NamespaceBlockSyntax
Dim declaration = GenerateNamespaceDeclaration(service, [namespace], options, cancellationToken)
If Not TypeOf declaration Is NamespaceBlockSyntax Then
Throw New ArgumentException(VBWorkspaceResources.Namespace_can_not_be_added_in_this_destination)
End If
Dim members = Insert(destination.Members, DirectCast(declaration, StatementSyntax), options, availableIndices)
Return destination.WithMembers(members)
End Function
Public Function GenerateNamespaceDeclaration(service As ICodeGenerationService, [namespace] As INamespaceSymbol, options As CodeGenerationOptions, cancellationToken As CancellationToken) As SyntaxNode
Dim name As String = Nothing
Dim innermostNamespace As INamespaceSymbol = Nothing
options = If(options, CodeGenerationOptions.Default)
GetNameAndInnermostNamespace([namespace], options, name, innermostNamespace)
Dim declaration = GetDeclarationSyntaxWithoutMembers([namespace], innermostNamespace, name, options)
declaration = If(options.GenerateMembers,
service.AddMembers(declaration, innermostNamespace.GetMembers().AsEnumerable(), options, cancellationToken),
declaration)
Return AddFormatterAndCodeGeneratorAnnotationsTo(declaration)
End Function
Public Function UpdateCompilationUnitOrNamespaceDeclaration(service As ICodeGenerationService,
declaration As SyntaxNode,
newMembers As IList(Of ISymbol),
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As SyntaxNode
declaration = RemoveAllMembers(declaration)
declaration = service.AddMembers(declaration, newMembers, options, cancellationToken)
Return AddFormatterAndCodeGeneratorAnnotationsTo(declaration)
End Function
Private Function GetDeclarationSyntaxWithoutMembers([namespace] As INamespaceSymbol, innermostNamespace As INamespaceSymbol, name As String, options As CodeGenerationOptions) As SyntaxNode
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of SyntaxNode)([namespace], options)
If reusableSyntax Is Nothing Then
Return GenerateNamespaceDeclarationWorker(name, innermostNamespace)
End If
Return RemoveAllMembers(reusableSyntax)
End Function
Private Function RemoveAllMembers(declaration As SyntaxNode) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Return DirectCast(declaration, CompilationUnitSyntax).WithMembers(Nothing)
Case SyntaxKind.NamespaceBlock
Return DirectCast(declaration, NamespaceBlockSyntax).WithMembers(Nothing)
Case Else
Return declaration
End Select
End Function
Private Function GenerateNamespaceDeclarationWorker(name As String, [namespace] As INamespaceSymbol) As SyntaxNode
If name = String.Empty Then
Return SyntaxFactory.CompilationUnit().WithImports(GenerateImportsStatements([namespace]))
Else
Return SyntaxFactory.NamespaceBlock(
SyntaxFactory.NamespaceStatement(SyntaxFactory.ParseName(name)))
End If
End Function
Private Function GenerateImportsStatements([namespace] As INamespaceSymbol) As SyntaxList(Of ImportsStatementSyntax)
Dim statements =
CodeGenerationNamespaceInfo.GetImports([namespace]).
Select(AddressOf GenerateImportsStatement).
WhereNotNull().ToList()
Return If(statements.Count = 0, Nothing, SyntaxFactory.List(statements))
End Function
Private Function GenerateImportsStatement(import As ISymbol) As ImportsStatementSyntax
If TypeOf import Is IAliasSymbol Then
Dim [alias] = DirectCast(import, IAliasSymbol)
Dim name = GenerateName([alias].Target)
If name IsNot Nothing Then
Return SyntaxFactory.ImportsStatement(
SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(
SyntaxFactory.SimpleImportsClause(SyntaxFactory.ImportAliasClause([alias].Name.ToIdentifierToken), name)))
End If
ElseIf TypeOf import Is INamespaceOrTypeSymbol Then
Dim name = GenerateName(DirectCast(import, INamespaceOrTypeSymbol))
If name IsNot Nothing Then
Return SyntaxFactory.ImportsStatement(
SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(
SyntaxFactory.SimpleImportsClause(name)))
End If
End If
Return Nothing
End Function
Private Function GenerateName(symbol As INamespaceOrTypeSymbol) As NameSyntax
If TypeOf symbol Is ITypeSymbol Then
Return TryCast(DirectCast(symbol, ITypeSymbol).GenerateTypeSyntax(), NameSyntax)
Else
Return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))
End If
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.Threading
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module NamespaceGenerator
Public Function AddNamespaceTo(service As ICodeGenerationService,
destination As CompilationUnitSyntax,
[namespace] As INamespaceSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean),
cancellationToken As CancellationToken) As CompilationUnitSyntax
Dim declaration = GenerateNamespaceDeclaration(service, [namespace], options, cancellationToken)
If Not TypeOf declaration Is NamespaceBlockSyntax Then
Throw New ArgumentException(VBWorkspaceResources.Namespace_can_not_be_added_in_this_destination)
End If
Dim members = Insert(destination.Members, DirectCast(declaration, StatementSyntax), options, availableIndices)
Return destination.WithMembers(members)
End Function
Public Function AddNamespaceTo(service As ICodeGenerationService,
destination As NamespaceBlockSyntax,
[namespace] As INamespaceSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean),
cancellationToken As CancellationToken) As NamespaceBlockSyntax
Dim declaration = GenerateNamespaceDeclaration(service, [namespace], options, cancellationToken)
If Not TypeOf declaration Is NamespaceBlockSyntax Then
Throw New ArgumentException(VBWorkspaceResources.Namespace_can_not_be_added_in_this_destination)
End If
Dim members = Insert(destination.Members, DirectCast(declaration, StatementSyntax), options, availableIndices)
Return destination.WithMembers(members)
End Function
Public Function GenerateNamespaceDeclaration(service As ICodeGenerationService, [namespace] As INamespaceSymbol, options As CodeGenerationOptions, cancellationToken As CancellationToken) As SyntaxNode
Dim name As String = Nothing
Dim innermostNamespace As INamespaceSymbol = Nothing
options = If(options, CodeGenerationOptions.Default)
GetNameAndInnermostNamespace([namespace], options, name, innermostNamespace)
Dim declaration = GetDeclarationSyntaxWithoutMembers([namespace], innermostNamespace, name, options)
declaration = If(options.GenerateMembers,
service.AddMembers(declaration, innermostNamespace.GetMembers().AsEnumerable(), options, cancellationToken),
declaration)
Return AddFormatterAndCodeGeneratorAnnotationsTo(declaration)
End Function
Public Function UpdateCompilationUnitOrNamespaceDeclaration(service As ICodeGenerationService,
declaration As SyntaxNode,
newMembers As IList(Of ISymbol),
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As SyntaxNode
declaration = RemoveAllMembers(declaration)
declaration = service.AddMembers(declaration, newMembers, options, cancellationToken)
Return AddFormatterAndCodeGeneratorAnnotationsTo(declaration)
End Function
Private Function GetDeclarationSyntaxWithoutMembers([namespace] As INamespaceSymbol, innermostNamespace As INamespaceSymbol, name As String, options As CodeGenerationOptions) As SyntaxNode
Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of SyntaxNode)([namespace], options)
If reusableSyntax Is Nothing Then
Return GenerateNamespaceDeclarationWorker(name, innermostNamespace)
End If
Return RemoveAllMembers(reusableSyntax)
End Function
Private Function RemoveAllMembers(declaration As SyntaxNode) As SyntaxNode
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Return DirectCast(declaration, CompilationUnitSyntax).WithMembers(Nothing)
Case SyntaxKind.NamespaceBlock
Return DirectCast(declaration, NamespaceBlockSyntax).WithMembers(Nothing)
Case Else
Return declaration
End Select
End Function
Private Function GenerateNamespaceDeclarationWorker(name As String, [namespace] As INamespaceSymbol) As SyntaxNode
If name = String.Empty Then
Return SyntaxFactory.CompilationUnit().WithImports(GenerateImportsStatements([namespace]))
Else
Return SyntaxFactory.NamespaceBlock(
SyntaxFactory.NamespaceStatement(SyntaxFactory.ParseName(name)))
End If
End Function
Private Function GenerateImportsStatements([namespace] As INamespaceSymbol) As SyntaxList(Of ImportsStatementSyntax)
Dim statements =
CodeGenerationNamespaceInfo.GetImports([namespace]).
Select(AddressOf GenerateImportsStatement).
WhereNotNull().ToList()
Return If(statements.Count = 0, Nothing, SyntaxFactory.List(statements))
End Function
Private Function GenerateImportsStatement(import As ISymbol) As ImportsStatementSyntax
If TypeOf import Is IAliasSymbol Then
Dim [alias] = DirectCast(import, IAliasSymbol)
Dim name = GenerateName([alias].Target)
If name IsNot Nothing Then
Return SyntaxFactory.ImportsStatement(
SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(
SyntaxFactory.SimpleImportsClause(SyntaxFactory.ImportAliasClause([alias].Name.ToIdentifierToken), name)))
End If
ElseIf TypeOf import Is INamespaceOrTypeSymbol Then
Dim name = GenerateName(DirectCast(import, INamespaceOrTypeSymbol))
If name IsNot Nothing Then
Return SyntaxFactory.ImportsStatement(
SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(
SyntaxFactory.SimpleImportsClause(name)))
End If
End If
Return Nothing
End Function
Private Function GenerateName(symbol As INamespaceOrTypeSymbol) As NameSyntax
If TypeOf symbol Is ITypeSymbol Then
Return TryCast(DirectCast(symbol, ITypeSymbol).GenerateTypeSyntax(), NameSyntax)
Else
Return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))
End If
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,382 | remove ".editorconfig added to solution" yellow bar | fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | jmarolf | 2021-08-03T18:16:54Z | 2021-08-09T19:20:08Z | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | b9b962d3280a6e2e4f28cbdb3e5219683a3566d9 | remove ".editorconfig added to solution" yellow bar. fixes #54534
fixes [AZ#1275561](https://devdiv.visualstudio.com/DevDiv/_queries/edit/1275561) | ./src/Features/CSharp/Portable/Organizing/Organizers/ModifiersOrganizer.Comparer.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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
internal partial class ModifiersOrganizer
{
private class Comparer : IComparer<SyntaxToken>
{
// TODO(cyrusn): Allow users to specify the ordering they want
private enum Ordering
{
Accessibility,
StaticInstance,
Remainder
}
public int Compare(SyntaxToken x, SyntaxToken y)
{
if (x.Kind() == y.Kind())
{
return 0;
}
return ComparerWithState.CompareTo(x, y, s_comparers);
}
private static readonly ImmutableArray<Func<SyntaxToken, IComparable>> s_comparers =
ImmutableArray.Create<Func<SyntaxToken, IComparable>>(t => t.Kind() == SyntaxKind.PartialKeyword, t => GetOrdering(t));
private static Ordering GetOrdering(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.StaticKeyword:
return Ordering.StaticInstance;
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.PublicKeyword:
return Ordering.Accessibility;
default:
return Ordering.Remainder;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
internal partial class ModifiersOrganizer
{
private class Comparer : IComparer<SyntaxToken>
{
// TODO(cyrusn): Allow users to specify the ordering they want
private enum Ordering
{
Accessibility,
StaticInstance,
Remainder
}
public int Compare(SyntaxToken x, SyntaxToken y)
{
if (x.Kind() == y.Kind())
{
return 0;
}
return ComparerWithState.CompareTo(x, y, s_comparers);
}
private static readonly ImmutableArray<Func<SyntaxToken, IComparable>> s_comparers =
ImmutableArray.Create<Func<SyntaxToken, IComparable>>(t => t.Kind() == SyntaxKind.PartialKeyword, t => GetOrdering(t));
private static Ordering GetOrdering(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.StaticKeyword:
return Ordering.StaticInstance;
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.PublicKeyword:
return Ordering.Accessibility;
default:
return Ordering.Remainder;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
/// <summary>
/// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test.
/// </summary>
public class EditAndContinueTests : EditAndContinueTestBase
{
private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers)
{
var currentGenerationReader = readers.Last();
foreach (var typeRefHandle in currentGenerationReader.TypeReferences)
{
var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle);
yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}";
}
}
[Fact]
public void DeltaHeapsStartWithEmptyItem()
{
var source0 =
@"class C
{
static string F() { return null; }
}";
var source1 =
@"class C
{
static string F() { return ""a""; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var s = MetadataTokens.StringHandle(0);
Assert.Equal("", reader1.GetString(s));
var b = MetadataTokens.BlobHandle(0);
Assert.Equal(0, reader1.GetBlobBytes(b).Length);
var us = MetadataTokens.UserStringHandle(0);
Assert.Equal("", reader1.GetUserString(us));
}
[Fact]
public void Delta_AssemblyDefTable()
{
var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }";
var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
// AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed:
Assert.True(md0.MetadataReader.IsAssembly);
Assert.False(diff1.GetMetadata().Reader.IsAssembly);
}
[Fact]
public void SemanticErrors_MethodBody()
{
var source0 = MarkedSource(@"
class C
{
static void E()
{
int x = 1;
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void E()
{
int x = Unknown(2);
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(2);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Semantic errors are reported only for the bodies of members being emitted.
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (6,17): error CS0103: The name 'Unknown' does not exist in the current context
// int x = Unknown(2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17));
var diffGood = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffGood.EmitResult.Diagnostics.Verify();
diffGood.VerifyIL(@"C.G", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}
");
}
[Fact]
public void SemanticErrors_Declaration()
{
var source0 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(1);
}
}
");
var source1 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(2);
}
}
class Bad : Bad
{
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// All declaration errors are reported regardless of what member do we emit.
diff.EmitResult.Diagnostics.Verify(
// (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad'
// class Bad : Bad
Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7));
}
[Fact]
public void ModifyMethod()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[CompilerTrait(CompilerFeature.Tuples)]
[Fact]
public void ModifyMethod_WithTuples()
{
var source0 =
@"class C
{
static void Main() { }
static (int, int) F() { return (1, 2); }
}";
var source1 =
@"class C
{
static void Main() { }
static (int, int) F() { return (2, 3); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}";
var source3 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
Assert.Equal(4, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")),
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(3, reader2.CustomAttributes.Count);
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute
CheckEncMap(reader2,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(2, TableIndex.TypeDef),
Handle(2, TableIndex.MethodDef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(10, TableIndex.MemberRef),
Handle(11, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted
CheckEncMap(reader3,
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(12, TableIndex.MemberRef),
Handle(13, TableIndex.MemberRef),
Handle(14, TableIndex.MemberRef),
Handle(15, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes2()
{
var source0 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A"")]
static string A() { return null; }
}
";
var source1 =
@"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")]
static string A() { return null; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0_1 = compilation0.GetMember<MethodSymbol>("C.F");
var method0_2 = compilation0.GetMember<MethodSymbol>("D.A");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1_1 = compilation1.GetMember<MethodSymbol>("C.F");
var method1_2 = compilation1.GetMember<MethodSymbol>("D.A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1),
SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "A");
CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var source2 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes2()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 = source0; // Remove the attribute we just added
var source3 = source1; // Add the attribute back again
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation1.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames());
CheckAttributes(reader2,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader3,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row
CheckEncMap(reader3,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")]
[Fact]
public void PartialMethod()
{
var source =
@"partial class C
{
static partial void M1();
static partial void M2();
static partial void M3();
static partial void M1() { }
static partial void M2() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor");
var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
var methods = diff1.TestData.GetMethodsByName();
Assert.Equal(1, methods.Count);
Assert.True(methods.ContainsKey("C.M2()"));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "M2");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Method_WithAttributes_Add()
{
var source0 =
@"class C
{
static void Main() { }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_ParameterAttributes()
{
var source0 =
@"class C
{
static void Main() { }
static string F(string input, int a) { return input; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; }
static void G(string input) { }
}";
var source2 =
@"class C
{
static void Main() { }
static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; }
static void G([System.ComponentModel.Description(""input"")]string input) { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var methodF0 = compilation0.GetMember<MethodSymbol>("C.F");
var methodF1 = compilation1.GetMember<MethodSymbol>("C.F");
var methodG1 = compilation1.GetMember<MethodSymbol>("C.G");
var methodG2 = compilation2.GetMember<MethodSymbol>("C.G");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1),
SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor");
CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G
Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param
Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param),
Handle(5, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "G");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor");
CheckNames(readers, reader2.GetParameterDefNames(), "input");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(4, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(6, TableIndex.MemberRef),
Handle(5, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyDelegateInvokeMethod_AddAttributes()
{
var source0 = @"
class A : System.Attribute { }
delegate void D(int x);
";
var source1 = @"
class A : System.Attribute { }
delegate void D([A]int x);
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke");
var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke");
var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke");
var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1),
SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke");
CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param),
Handle(6, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(2, TableIndex.AssemblyRef));
}
/// <summary>
/// Add a method that requires entries in the ParameterDefs table.
/// Specifically, normal parameters or return types with attributes.
/// Add the method in the first edit, then modify the method in the second.
/// </summary>
[Fact]
public void Method_WithParameterAttributes_AddThenUpdate()
{
var source0 =
@"class A : System.Attribute { }
class C
{
}";
var source1 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => arg;
}";
var source2 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => null;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetParameterDefNames(), "", "arg");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(1, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(1, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckEncLogDefinitions(reader2,
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(2, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void Method_WithEmbeddedAttributes_AndThenUpdate()
{
var source0 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
class C
{
static void Main() { }
}
}
";
var source1 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main()
{
Id(in G());
}
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 1 }[0];
}
}";
var source2 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
}
}";
var source3 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
readonly ref readonly string?[]? F() => throw null;
}
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main");
var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id");
var g1 = compilation1.GetMember<MethodSymbol>("N.C.G");
var g2 = compilation2.GetMember<MethodSymbol>("N.C.G");
var h2 = compilation2.GetMember<MethodSymbol>("N.C.H");
var f3 = compilation3.GetMember<MethodSymbol>("N.C.F");
// Verify full metadata contains expected rows.
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, id1),
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute}");
diff1.VerifyIL("N.C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: nop
IL_0001: call ""ref readonly int N.C.G()""
IL_0006: call ""ref readonly int N.C.Id(in int)""
IL_000b: pop
IL_000c: ret
}
");
diff1.VerifyIL("N.C.Id", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
");
diff1.VerifyIL("N.C.G", @"
{
// Code size 17 (0x11)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: newarr ""int""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: stelem.i4
IL_000a: ldc.i4.0
IL_000b: ldelema ""int""
IL_0010: ret
}
");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader0 = md0.MetadataReader;
var reader1 = md1.Reader;
var readers = new List<MetadataReader>() { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute");
CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g1, g2),
SemanticEdit.Create(SemanticEditKind.Insert, null, h2)));
// synthesized member for nullable annotations added:
diff2.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
// note: NullableAttribute has 2 ctors, NullableContextAttribute has one
CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute");
CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H");
// two new TypeDefs emitted for the attributes:
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute
Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(6, TableIndex.TypeDef),
Handle(7, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(2, TableIndex.Field),
Handle(7, TableIndex.MethodDef),
Handle(8, TableIndex.MethodDef),
Handle(9, TableIndex.MethodDef),
Handle(10, TableIndex.MethodDef),
Handle(11, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(6, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(12, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3)));
// no change in synthesized members:
diff3.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
// no new type defs:
CheckNames(readers, reader3.GetTypeDefFullNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void Field_Add()
{
var source0 =
@"class C
{
string F = ""F"";
}";
var source1 =
@"class C
{
string F = ""F"";
string G = ""G"";
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetFieldDefNames(), "F");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var method1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "G");
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Accessor_Update()
{
var source0 =
@"class C
{
object P { get { return 1; } }
}";
var source1 =
@"class C
{
object P { get { return 2; } }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P");
var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetPropertyDefNames(), "P");
CheckNames(readers, reader1.GetMethodDefNames(), "get_P");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Add()
{
var source0 = @"
class C
{
}
";
var source1 = @"
class C
{
object R { get { return null; } }
}
";
var source2 = @"
class C
{
object R { get { return null; } }
object Q { get; set; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var r1 = compilation1.GetMember<PropertySymbol>("C.R");
var q2 = compilation2.GetMember<PropertySymbol>("C.Q");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetPropertyDefNames(), "R");
CheckNames(readers, reader1.GetMethodDefNames(), "get_R");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.MethodDef),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.PropertyMap),
Handle(1, TableIndex.Property),
Handle(1, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, q2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField");
CheckNames(readers, reader2.GetPropertyDefNames(), "Q");
CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(1, TableIndex.Field),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(2, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(3, TableIndex.MethodSemantics));
}
[Fact]
public void Event_Add()
{
var source0 = @"
class C
{
}";
var source1 = @"
class C
{
event System.Action E;
}";
var source2 = @"
class C
{
event System.Action E;
event System.Action G;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var e1 = compilation1.GetMember<EventSymbol>("C.E");
var g2 = compilation2.GetMember<EventSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, e1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "E");
CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(1, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(1, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.EventMap),
Handle(1, TableIndex.Event),
Handle(1, TableIndex.MethodSemantics),
Handle(2, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "G");
CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.Field),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics));
}
[WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")]
[Fact]
public void EventFields()
{
var source0 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 1;
}
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 10;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 3
.locals init (int V_0)
IL_0000: nop
IL_0001: ldsfld ""System.EventHandler C.handler""
IL_0006: ldnull
IL_0007: ldnull
IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)""
IL_000d: nop
IL_000e: ldc.i4.s 10
IL_0010: stloc.0
IL_0011: br.s IL_0013
IL_0013: ldloc.0
IL_0014: ret
}
");
}
[Fact]
public void UpdateType_AddAttributes()
{
var source0 = @"
class C
{
}";
var source1 = @"
[System.ComponentModel.Description(""C"")]
class C
{
}";
var source2 = @"
[System.ComponentModel.Description(""C"")]
[System.ObsoleteAttribute]
class C
{
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
Assert.Equal(2, reader2.CustomAttributes.Count);
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute));
}
[Fact]
public void ReplaceType()
{
var source0 = @"
class C
{
void F(int x) {}
}
";
var source1 = @"
class C
{
void F(int x, int y) { }
}";
var source2 = @"
class C
{
void F(int x, int y) { System.Console.WriteLine(1); }
}";
var source3 = @"
[System.Obsolete]
class C
{
void F(int x, int y) { System.Console.WriteLine(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var c3 = compilation3.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
var f3 = c3.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C#1");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param));
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C#2");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader2,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param));
// This update is an EnC update - even reloadable types are update in-place
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, c2, c3),
SemanticEdit.Create(SemanticEditKind.Update, f2, f3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames(), "C#2");
CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader3,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader3,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void AddNestedTypeAndMembers()
{
var source0 =
@"class A
{
class B { }
static object F()
{
return new B();
}
}";
var source1 =
@"class A
{
class B { }
class C
{
class D { }
static object F;
internal static object G()
{
return F;
}
}
static object F()
{
return C.G();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C");
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C", "D");
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor");
CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D");
Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(3, TableIndex.NestedClass));
}
/// <summary>
/// Nested types should be emitted in the
/// same order as full emit.
/// </summary>
[Fact]
public void AddNestedTypesOrder()
{
var source0 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
}";
var source1 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
class B3
{
class C3 { }
}
class B4
{
class C4 { }
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2");
Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4");
Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass));
}
[Fact]
public void AddNestedGenericType()
{
var source0 =
@"class A
{
class B<T>
{
}
static object F()
{
return null;
}
}";
var source1 =
@"class A
{
class B<T>
{
internal class C<U>
{
internal object F<V>() where V : T, new()
{
return new C<V>();
}
}
}
static object F()
{
return new B<A>.C<B<object>>().F<A>();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1");
CheckNames(readers, reader1.GetTypeDefNames(), "C`1");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.TypeSpec),
Handle(2, TableIndex.TypeSpec),
Handle(3, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(2, TableIndex.GenericParam),
Handle(3, TableIndex.GenericParam),
Handle(4, TableIndex.GenericParam),
Handle(1, TableIndex.MethodSpec),
Handle(1, TableIndex.GenericParamConstraint));
}
[Fact]
public void AddNamespace()
{
var source0 =
@"
class C
{
static void Main() { }
}";
var source1 =
@"
namespace N
{
class D { public static void F() { } }
}
class C
{
static void Main() => N.D.F();
}";
var source2 =
@"
namespace N
{
class D { public static void F() { } }
namespace M
{
class E { public static void G() { } }
}
}
class C
{
static void Main() => N.M.E.G();
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var d1 = compilation1.GetMember<NamedTypeSymbol>("N.D");
var e2 = compilation2.GetMember<NamedTypeSymbol>("N.M.E");
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, d1)));
diff1.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N.D.F()""
IL_0005: nop
IL_0006: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main1, main2),
SemanticEdit.Create(SemanticEditKind.Insert, null, e2)));
diff2.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N.M.E.G()""
IL_0005: nop
IL_0006: ret
}");
}
[Fact]
public void ModifyExplicitImplementation()
{
var source =
@"interface I
{
void M();
}
class C : I
{
void I.M() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddThenModifyExplicitImplementation()
{
var source0 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
}";
var source1 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
void I.M() { }
}";
var source2 = source1;
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(2, TableIndex.MethodImpl),
Handle(2, TableIndex.AssemblyRef));
var generation1 = diff1.NextGeneration;
var diff2 = compilation2.EmitDifference(
generation1,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetMethodDefNames(), "I.M");
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(7, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(3, TableIndex.AssemblyRef));
}
[WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")]
[Fact]
public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation()
{
var source = @"
interface I
{
void M();
}
class C : I
{
public C()
{
}
void I.M() { }
}
";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddAndModifyInterfaceMembers()
{
var source0 = @"
using System;
interface I
{
}";
var source1 = @"
using System;
interface I
{
static int X = 10;
static event Action Y;
static void M() { }
void N() { }
static int P { get => 1; set { } }
int Q { get => 1; set { } }
static event Action E { add { } remove { } }
event Action F { add { } remove { } }
interface J { }
}";
var source2 = @"
using System;
interface I
{
static int X = 2;
static event Action Y;
static I() { X--; }
static void M() { X++; }
void N() { X++; }
static int P { get => 3; set { X++; } }
int Q { get => 3; set { X++; } }
static event Action E { add { X++; } remove { X++; } }
event Action F { add { X++; } remove { X++; } }
interface J { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var x1 = compilation1.GetMember<FieldSymbol>("I.X");
var y1 = compilation1.GetMember<EventSymbol>("I.Y");
var m1 = compilation1.GetMember<MethodSymbol>("I.M");
var n1 = compilation1.GetMember<MethodSymbol>("I.N");
var p1 = compilation1.GetMember<PropertySymbol>("I.P");
var q1 = compilation1.GetMember<PropertySymbol>("I.Q");
var e1 = compilation1.GetMember<EventSymbol>("I.E");
var f1 = compilation1.GetMember<EventSymbol>("I.F");
var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J");
var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P");
var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P");
var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q");
var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q");
var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E");
var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E");
var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F");
var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F");
var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var x2 = compilation2.GetMember<FieldSymbol>("I.X");
var m2 = compilation2.GetMember<MethodSymbol>("I.M");
var n2 = compilation2.GetMember<MethodSymbol>("I.N");
var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P");
var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P");
var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q");
var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q");
var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E");
var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E");
var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F");
var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F");
var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, x1),
SemanticEdit.Create(SemanticEditKind.Insert, null, y1),
SemanticEdit.Create(SemanticEditKind.Insert, null, m1),
SemanticEdit.Create(SemanticEditKind.Insert, null, n1),
SemanticEdit.Create(SemanticEditKind.Insert, null, p1),
SemanticEdit.Create(SemanticEditKind.Insert, null, q1),
SemanticEdit.Create(SemanticEditKind.Insert, null, e1),
SemanticEdit.Create(SemanticEditKind.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Insert, null, j1),
SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader1.GetTypeDefNames(), "J");
CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y");
CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, x1, x2),
SemanticEdit.Create(SemanticEditKind.Update, m1, m2),
SemanticEdit.Create(SemanticEditKind.Update, n1, n2),
SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2),
SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2),
SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2),
SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2),
SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2),
SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2),
SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2),
SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2),
SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "X");
CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(3, TableIndex.Event, EditAndContinueOperation.Default),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
diff2.VerifyIL(@"
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: nop
IL_0001: ldsfld 0x04000001
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: stsfld 0x04000001
IL_000d: ret
}
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.3
IL_0001: ret
}
{
// Code size 20 (0x14)
.maxstack 8
IL_0000: ldc.i4.2
IL_0001: stsfld 0x04000001
IL_0006: nop
IL_0007: ldsfld 0x04000001
IL_000c: ldc.i4.1
IL_000d: sub
IL_000e: stsfld 0x04000001
IL_0013: ret
}
");
}
[Fact]
public void AddAttributeReferences()
{
var source0 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static object F1;
[A] static object P1 { get { return null; } }
[B] static event D E1;
}
delegate void D();
";
var source1 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static void M2<[A]T>() { }
[B] static object F1;
[A] static object F2;
[A] static object P1 { get { return null; } }
[B] static object P2 { get { return null; } }
[B] static event D E1;
[A] static event D E2;
}
delegate void D();
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(12, TableIndex.MethodDef),
Handle(13, TableIndex.MethodDef),
Handle(14, TableIndex.MethodDef),
Handle(15, TableIndex.MethodDef),
Handle(8, TableIndex.Param),
Handle(9, TableIndex.Param),
Handle(7, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(18, TableIndex.CustomAttribute),
Handle(19, TableIndex.CustomAttribute),
Handle(20, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(2, TableIndex.Property),
Handle(4, TableIndex.MethodSemantics),
Handle(5, TableIndex.MethodSemantics),
Handle(6, TableIndex.MethodSemantics),
Handle(2, TableIndex.GenericParam));
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)));
}
/// <summary>
/// [assembly: ...] and [module: ...] attributes should
/// not be included in delta metadata.
/// </summary>
[Fact]
public void AssemblyAndModuleAttributeReferences()
{
var source0 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
}";
var source1 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var readers = new[] { reader0, md1.Reader };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, md1.Reader.GetTypeDefNames());
CheckNames(readers, md1.Reader.GetMethodDefNames(), "M");
CheckEncLog(md1.Reader,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M
CheckEncMap(md1.Reader,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void OtherReferences()
{
var source0 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
}
}";
var source1 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
object o;
o = typeof(D);
o = F;
o = P;
E += null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C");
CheckNames(reader0, reader0.GetEventDefNames(), "E");
CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor");
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
// Emit delta metadata.
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetEventDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M");
CheckNames(readers, reader1.GetPropertyDefNames());
}
[Fact]
public void ArrayInitializer()
{
var source0 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3 };
}
}");
var source1 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3, 4 };
}
}");
var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll);
var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs"));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M"))));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL(
@"{
// Code size 25 (0x19)
.maxstack 4
IL_0000: nop
IL_0001: ldc.i4.4
IL_0002: newarr 0x0100000D
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.4
IL_0016: stelem.i4
IL_0017: stloc.0
IL_0018: ret
}");
diff1.VerifyPdb(new[] { 0x06000001 },
@"<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" />
</files>
<methods>
<method token=""0x6000001"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x19"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void PInvokeModuleRefAndImplMap()
{
var source0 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
}";
var source1 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
[DllImport(""msvcrt.dll"")]
public static extern int puts(string s);
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.ImplMap));
}
/// <summary>
/// ClassLayout and FieldLayout tables.
/// </summary>
[Fact]
public void ClassAndFieldLayout()
{
var source0 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}";
var source1 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}
[StructLayout(LayoutKind.Explicit, Pack=4)]
class B
{
[FieldOffset(0)]internal short F;
[FieldOffset(4)]internal short G;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default),
Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default),
Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.ClassLayout),
Handle(3, TableIndex.FieldLayout),
Handle(4, TableIndex.FieldLayout),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void NamespacesAndOverloads()
{
var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source:
@"class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
}
}
}");
var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2");
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var compilation1 = compilation0.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
}
}
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2])));
diff1.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
}");
var compilation2 = compilation1.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
M1(c);
}
}
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"),
compilation2.GetMember<MethodSymbol>("M.C.M2"))));
diff2.VerifyIL(
@"{
// Code size 26 (0x1a)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: call 0x06000002
IL_0008: nop
IL_0009: ldarg.0
IL_000a: ldarg.2
IL_000b: call 0x06000003
IL_0010: nop
IL_0011: ldarg.0
IL_0012: ldarg.3
IL_0013: call 0x06000007
IL_0018: nop
IL_0019: ret
}");
}
[Fact]
public void TypesAndOverloads()
{
const string source =
@"using System;
struct A<T>
{
internal class B<U> { }
}
class B { }
class C
{
static void M(A<B>.B<object> a)
{
M(a);
M((A<B>.B<B>)null);
}
static void M(A<B>.B<B> a)
{
M(a);
M((A<B>.B<object>)null);
}
static void M(A<B> a)
{
M(a);
M((A<B>?)a);
}
static void M(Nullable<A<B>> a)
{
M(a);
M(a.Value);
}
unsafe static void M(int* p)
{
M(p);
M((byte*)p);
}
unsafe static void M(byte* p)
{
M(p);
M((int*)p);
}
static void M(B[][] b)
{
M(b);
M((object[][])b);
}
static void M(object[][] b)
{
M(b);
M((B[][])b);
}
static void M(A<B[]>.B<object> b)
{
M(b);
M((A<B[, ,]>.B<object>)null);
}
static void M(A<B[, ,]>.B<object> b)
{
M(b);
M((A<B[]>.B<object>)null);
}
static void M(dynamic d)
{
M(d);
M((dynamic[])d);
}
static void M(dynamic[] d)
{
M(d);
M((dynamic)d);
}
static void M<T>(A<int>.B<T> t) where T : B
{
M(t);
M((A<double>.B<int>)null);
}
static void M<T>(A<double>.B<T> t) where T : struct
{
M(t);
M((A<int>.B<B>)null);
}
}";
var options = TestOptions.UnsafeDebugDll;
var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef });
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var n = compilation0.GetMembers("C.M").Length;
Assert.Equal(14, n);
//static void M(A<B>.B<object> a)
//{
// M(a);
// M((A<B>.B<B>)null);
//}
var compilation1 = compilation0.WithSource(source);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0])));
diff1.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B>.B<B> a)
//{
// M(a);
// M((A<B>.B<object>)null);
//}
var compilation2 = compilation1.WithSource(source);
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1])));
diff2.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000003
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000002
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B> a)
//{
// M(a);
// M((A<B>?)a);
//}
var compilation3 = compilation2.WithSource(source);
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2])));
diff3.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000004
IL_0007: nop
IL_0008: ldarg.0
IL_0009: newobj 0x0A000016
IL_000e: call 0x06000005
IL_0013: nop
IL_0014: ret
}");
//static void M(Nullable<A<B>> a)
//{
// M(a);
// M(a.Value);
//}
var compilation4 = compilation3.WithSource(source);
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3])));
diff4.VerifyIL(
@"{
// Code size 22 (0x16)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000005
IL_0007: nop
IL_0008: ldarga.s V_0
IL_000a: call 0x0A000017
IL_000f: call 0x06000004
IL_0014: nop
IL_0015: ret
}");
//unsafe static void M(int* p)
//{
// M(p);
// M((byte*)p);
//}
var compilation5 = compilation4.WithSource(source);
var diff5 = compilation5.EmitDifference(
diff4.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4])));
diff5.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000006
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000007
IL_000e: nop
IL_000f: ret
}");
//unsafe static void M(byte* p)
//{
// M(p);
// M((int*)p);
//}
var compilation6 = compilation5.WithSource(source);
var diff6 = compilation6.EmitDifference(
diff5.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5])));
diff6.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000007
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000006
IL_000e: nop
IL_000f: ret
}");
//static void M(B[][] b)
//{
// M(b);
// M((object[][])b);
//}
var compilation7 = compilation6.WithSource(source);
var diff7 = compilation7.EmitDifference(
diff6.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6])));
diff7.VerifyIL(
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000008
IL_0007: nop
IL_0008: ldarg.0
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: call 0x06000009
IL_0010: nop
IL_0011: ret
}");
//static void M(object[][] b)
//{
// M(b);
// M((B[][])b);
//}
var compilation8 = compilation7.WithSource(source);
var diff8 = compilation8.EmitDifference(
diff7.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7])));
diff8.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000009
IL_0007: nop
IL_0008: ldarg.0
IL_0009: castclass 0x1B00000A
IL_000e: call 0x06000008
IL_0013: nop
IL_0014: ret
}");
//static void M(A<B[]>.B<object> b)
//{
// M(b);
// M((A<B[,,]>.B<object>)null);
//}
var compilation9 = compilation8.WithSource(source);
var diff9 = compilation9.EmitDifference(
diff8.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8])));
diff9.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000A
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000B
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B[,,]>.B<object> b)
//{
// M(b);
// M((A<B[]>.B<object>)null);
//}
var compilation10 = compilation9.WithSource(source);
var diff10 = compilation10.EmitDifference(
diff9.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9])));
diff10.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000B
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000A
IL_000e: nop
IL_000f: ret
}");
// TODO: dynamic
#if false
//static void M(dynamic d)
//{
// M(d);
// M((dynamic[])d);
//}
previousMethod = compilation.GetMembers("C.M")[10];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(dynamic[] d)
//{
// M(d);
// M((dynamic)d);
//}
previousMethod = compilation.GetMembers("C.M")[11];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
#endif
//static void M<T>(A<int>.B<T> t) where T : B
//{
// M(t);
// M((A<double>.B<int>)null);
//}
var compilation11 = compilation10.WithSource(source);
var diff11 = compilation11.EmitDifference(
diff10.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12])));
diff11.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000005
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000006
IL_000e: nop
IL_000f: ret
}");
//static void M<T>(A<double>.B<T> t) where T : struct
//{
// M(t);
// M((A<int>.B<B>)null);
//}
var compilation12 = compilation11.WithSource(source);
var diff12 = compilation12.EmitDifference(
diff11.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13])));
diff12.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000007
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000008
IL_000e: nop
IL_000f: ret
}");
}
/// <summary>
/// Types should be retained in deleted locals
/// for correct alignment of remaining locals.
/// </summary>
[Fact]
public void DeletedValueTypeLocal()
{
var source0 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var x = new S1(1, 2);
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var source1 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.Main");
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
testData0.GetMethodData("C.Main").VerifyIL(
@"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (S1 V_0, //x
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""S1..ctor(int, int)""
IL_000a: ldloca.s V_1
IL_000c: ldc.i4.3
IL_000d: call ""S2..ctor(int)""
IL_0012: ldloc.1
IL_0013: ldfld ""int S2.C""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: nop
IL_001e: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init ([unchanged] V_0,
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_1
IL_0003: ldc.i4.3
IL_0004: call ""S2..ctor(int)""
IL_0009: ldloc.1
IL_000a: ldfld ""int S2.C""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}");
}
/// <summary>
/// Instance and static constructors synthesized for
/// PrivateImplementationDetails should not be
/// generated for delta.
/// </summary>
[Fact]
public void PrivateImplementationDetails()
{
var source =
@"class C
{
static int[] F = new int[] { 1, 2, 3 };
int[] G = new int[] { 4, 5, 6 };
int M(int index)
{
return F[index] + G[index];
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var reader0 = md0.MetadataReader;
var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames());
Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)));
}
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 22 (0x16)
.maxstack 3
.locals init ([int] V_0,
int V_1)
IL_0000: nop
IL_0001: ldsfld ""int[] C.F""
IL_0006: ldarg.1
IL_0007: ldelem.i4
IL_0008: ldarg.0
IL_0009: ldfld ""int[] C.G""
IL_000e: ldarg.1
IL_000f: ldelem.i4
IL_0010: add
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromMetadata()
{
var source0 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[0]);
}
}";
var source1 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[1]);
}
}";
var source2 =
@"class C
{
static void M()
{
int[] a = { 4, 5, 6, 7, 8, 9, 10 };
System.Console.WriteLine(a[1]);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE"));
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
methodData0.VerifyIL(
@" {
// Code size 29 (0x1d)
.maxstack 3
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ldc.i4.0
IL_0015: ldelem.i4
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
IL_001c: ret
}
");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"{
// Code size 30 (0x1e)
.maxstack 4
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.1
IL_0016: ldelem.i4
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: nop
IL_001d: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 48 (0x30)
.maxstack 4
.locals init ([unchanged] V_0,
int[] V_1) //a
IL_0000: nop
IL_0001: ldc.i4.7
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.4
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.5
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.6
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.7
IL_0016: stelem.i4
IL_0017: dup
IL_0018: ldc.i4.4
IL_0019: ldc.i4.8
IL_001a: stelem.i4
IL_001b: dup
IL_001c: ldc.i4.5
IL_001d: ldc.i4.s 9
IL_001f: stelem.i4
IL_0020: dup
IL_0021: ldc.i4.6
IL_0022: ldc.i4.s 10
IL_0024: stelem.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: ldelem.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromSource()
{
// PrivateImplementationDetails not needed initially.
var source0 =
@"class C
{
static object F1() { return null; }
static object F2() { return null; }
static object F3() { return null; }
static object F4() { return null; }
}";
var source1 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return null; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var source2 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return new[] { 13, 14, 15 }; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4"))));
diff1.VerifyIL("C.F1",
@"{
// Code size 24 (0x18)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: ldloc.0
IL_0017: ret
}");
diff1.VerifyIL("C.F4",
@"{
// Code size 25 (0x19)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.7
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.8
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.s 9
IL_0013: stelem.i4
IL_0014: stloc.0
IL_0015: br.s IL_0017
IL_0017: ldloc.0
IL_0018: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3"))));
diff2.VerifyIL("C.F1",
@"{
// Code size 49 (0x31)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: brtrue.s IL_002c
IL_0016: pop
IL_0017: ldc.i4.3
IL_0018: newarr ""int""
IL_001d: dup
IL_001e: ldc.i4.0
IL_001f: ldc.i4.s 10
IL_0021: stelem.i4
IL_0022: dup
IL_0023: ldc.i4.1
IL_0024: ldc.i4.s 11
IL_0026: stelem.i4
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: ldc.i4.s 12
IL_002b: stelem.i4
IL_002c: stloc.0
IL_002d: br.s IL_002f
IL_002f: ldloc.0
IL_0030: ret
}");
diff2.VerifyIL("C.F3",
@"{
// Code size 27 (0x1b)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.s 13
IL_000b: stelem.i4
IL_000c: dup
IL_000d: ldc.i4.1
IL_000e: ldc.i4.s 14
IL_0010: stelem.i4
IL_0011: dup
IL_0012: ldc.i4.2
IL_0013: ldc.i4.s 15
IL_0015: stelem.i4
IL_0016: stloc.0
IL_0017: br.s IL_0019
IL_0019: ldloc.0
IL_001a: ret
}");
}
/// <summary>
/// Should not generate method for string switch since
/// the CLR only allows adding private members.
/// </summary>
[WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")]
[Fact]
public void PrivateImplementationDetails_ComputeStringHash()
{
var source =
@"class C
{
static int F(string s)
{
switch (s)
{
case ""1"": return 1;
case ""2"": return 2;
case ""3"": return 3;
case ""4"": return 4;
case ""5"": return 5;
case ""6"": return 6;
case ""7"": return 7;
default: return 0;
}
}
}";
const string ComputeStringHashName = "ComputeStringHash";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.F");
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
// Should have generated call to ComputeStringHash and
// added the method to <PrivateImplementationDetails>.
var actualIL0 = methodData0.GetMethodIL();
Assert.True(actualIL0.Contains(ComputeStringHashName));
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Should not have generated call to ComputeStringHash nor
// added the method to <PrivateImplementationDetails>.
var actualIL1 = diff1.GetMethodIL("C.F");
Assert.False(actualIL1.Contains(ComputeStringHashName));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "F");
}
/// <summary>
/// Unique ids should not conflict with ids
/// from previous generation.
/// </summary>
[WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")]
public void UniqueIds()
{
var source0 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
System.Func<int> g = () => 2;
return (b ? f : g)();
}
}";
var source1 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
return f();
}
}";
var source2 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> g = () => 2;
return g();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1])));
diff1.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //f
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__5()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1])));
diff2.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //g
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__7()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
}
/// <summary>
/// Avoid adding references from method bodies
/// other than the changed methods.
/// </summary>
[Fact]
public void ReferencesInIL()
{
var source0 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.WriteLine(2); }
}";
var source1 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.Write(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.G");
var method1 = compilation1.GetMember<MethodSymbol>("C.G");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(
SemanticEditKind.Update,
method0,
method1,
GetEquivalentNodesMap(method1, method0),
preserveLocalVariables: true)));
// "Write" should be included in string table, but "WriteLine" should not.
Assert.True(diff1.MetadataDelta.IsIncluded("Write"));
Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine"));
}
/// <summary>
/// Local slots must be preserved based on signature.
/// </summary>
[Fact]
public void PreserveLocalSlots()
{
var source0 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
A<B> y = F();
object z = F();
M(x);
M(y);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" };
var source1 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
B z = F();
A<B> y = F();
object w = F();
M(w);
M(y);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source2 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source3 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object c = F();
object b = F();
M(c);
M(b);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("B.M");
var methodN = compilation0.GetMember<MethodSymbol>("B.N");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo());
#region Gen1
var method1 = compilation1.GetMember<MethodSymbol>("B.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL(
@"{
// Code size 36 (0x24)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.3
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: call 0x06000002
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: call 0x06000003
IL_001b: nop
IL_001c: ldloc.1
IL_001d: call 0x06000003
IL_0022: nop
IL_0023: ret
}");
diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x24"">
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen2
var method2 = compilation2.GetMember<MethodSymbol>("B.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL(
@"{
// Code size 30 (0x1e)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.s V_5
IL_0008: call 0x06000002
IL_000d: stloc.3
IL_000e: ldloc.s V_5
IL_0010: call 0x06000003
IL_0015: nop
IL_0016: ldloc.3
IL_0017: call 0x06000003
IL_001c: nop
IL_001d: ret
}");
diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1e"">
<local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen3
// Modify different method. (Previous generations
// have not referenced method.)
method2 = compilation2.GetMember<MethodSymbol>("B.N");
var method3 = compilation3.GetMember<MethodSymbol>("B.N");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL(
@"{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.2
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: ldloc.2
IL_000e: call 0x06000003
IL_0013: nop
IL_0014: ldloc.1
IL_0015: call 0x06000003
IL_001a: nop
IL_001b: ret
}");
diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000004"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
}
/// <summary>
/// Preserve locals for method added after initial compilation.
/// </summary>
[Fact]
public void PreserveLocalSlots_NewMethod()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void M()
{
var a = new object();
var b = string.Empty;
}
}";
var source2 =
@"class C
{
static void M()
{
var a = 1;
var b = string.Empty;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 10 (0xa)
.maxstack 1
.locals init ([object] V_0,
string V_1, //b
int V_2) //a
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldsfld ""string string.Empty""
IL_0008: stloc.1
IL_0009: ret
}");
diff2.VerifyPdb(new[] { 0x06000002 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000002"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" />
<entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Local types should be retained, even if the local is no longer
/// used by the method body, since there may be existing
/// references to that slot, in a Watch window for instance.
/// </summary>
[WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")]
[Fact]
public void PreserveLocalTypes()
{
var source0 =
@"class C
{
static void Main()
{
var x = true;
var y = x;
System.Console.WriteLine(y);
}
}";
var source1 =
@"class C
{
static void Main()
{
var x = ""A"";
var y = x;
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
.locals init ([bool] V_0,
[bool] V_1,
string V_2, //x
string V_3) //y
IL_0000: nop
IL_0001: ldstr ""A""
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: stloc.3
IL_0009: ldloc.3
IL_000a: call ""void System.Console.WriteLine(string)""
IL_000f: nop
IL_0010: ret
}");
}
/// <summary>
/// Preserve locals if SemanticEdit.PreserveLocalVariables is set.
/// </summary>
[Fact]
public void PreserveLocalVariablesFlag()
{
var source =
@"class C
{
static System.IDisposable F() { return null; }
static void M()
{
using (F()) { }
using (var x = F()) { }
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1a = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false)));
diff1a.VerifyIL("C.M", @"
{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}
");
var diff1b = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
diff1b.VerifyIL("C.M",
@"{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}");
}
[WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")]
[Fact]
public void ChangeLocalType()
{
var source0 =
@"enum E { }
class C
{
static void M1()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in one method to type added.
var source1 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in another method.
var source2 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in same method.
var source3 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(A);
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M1");
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M2");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M2",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method3 = compilation3.GetMember<MethodSymbol>("C.M2");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL("C.M2",
@"{
// Code size 18 (0x12)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[unchanged] V_2,
A V_3, //x
A V_4, //y
A V_5) //z
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldnull
IL_0007: stloc.s V_5
IL_0009: ldloc.s V_4
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Update()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 1 }</N:0>;
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md1 = diff1.GetMetadata();
AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader }));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
[Fact]
public void AnonymousTypes_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
/// <summary>
/// Reuse existing anonymous types.
/// </summary>
[WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")]
[Fact]
public void AnonymousTypes()
{
var source0 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = x.A;
var z = new { };
}
}
}";
var source1 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = new { A = x.A };
var z = new { };
}
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var m0 = compilation0.GetMember<MethodSymbol>("M.B.M");
var m1 = compilation1.GetMember<MethodSymbol>("M.B.M");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider());
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type
diff1.VerifyIL("M.B.M", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (<>f__AnonymousType1<int, int> V_0, //x
[int] V_1,
<>f__AnonymousType2 V_2, //z
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: ldc.i4.4
IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get""
IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_0014: stloc.3
IL_0015: newobj ""<>f__AnonymousType2..ctor()""
IL_001a: stloc.2
IL_001b: ret
}");
}
/// <summary>
/// Anonymous type names with module ids
/// and gaps in indices.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")]
[WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")]
public void AnonymousTypes_OtherTypeNames()
{
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
// Valid signature, although not sequential index
.class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
.field public !'<B>j__TPar' B
}
// Invalid signature, unexpected type parameter names
.class '<>f__AnonymousType1'<A, B> extends object
{
.field public !A A
.field public !B B
}
// Module id, duplicate index
.class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
}
// Module id
.class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object
{
.field public !'<B>j__TPar' B
}
.class public C extends object
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F()
{
ldnull
ret
}
}";
var source0 =
@"class C
{
static object F()
{
return 0;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 1 };
var y = new { A = x.A };
return y;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
diff1.VerifyIL("C.F",
@"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (<>f__AnonymousType2<object, int> V_0, //x
<>f__AnonymousType3<object> V_1, //y
object V_2)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: ldc.i4.1
IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get""
IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: stloc.2
IL_001b: br.s IL_001d
IL_001d: ldloc.2
IL_001e: ret
}");
}
/// <summary>
/// Update method with anonymous type that was
/// not directly referenced in previous generation.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration()
{
var source0 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x;
}
}");
var source1 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x + 1;
}
}");
var source2 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 2 }</N:2>;
return x.A;
}
}");
var source3 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 3 }</N:2>;
return y.B;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var compilation3 = compilation2.WithSource(source3.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var method0 = compilation0.GetMember<MethodSymbol>("B.G");
var method1 = compilation1.GetMember<MethodSymbol>("B.G");
var method2 = compilation2.GetMember<MethodSymbol>("B.G");
var method3 = compilation3.GetMember<MethodSymbol>("B.G");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types
diff1.VerifyIL("B.G", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (int V_0, //x
[object] V_1,
object V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: add
IL_0006: box ""int""
IL_000b: stloc.2
IL_000c: br.s IL_000e
IL_000e: ldloc.2
IL_000f: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type
diff2.VerifyIL("B.G", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
object V_5)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.2
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.3
IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get""
IL_001a: stloc.s V_5
IL_001c: br.s IL_001e
IL_001e: ldloc.s V_5
IL_0020: ret
}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types
diff3.VerifyIL("B.G", @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
[object] V_5,
object V_6)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.3
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get""
IL_001b: box ""int""
IL_0020: stloc.s V_6
IL_0022: br.s IL_0024
IL_0024: ldloc.s V_6
IL_0026: ret
}");
}
/// <summary>
/// Update another method (without directly referencing
/// anonymous type) after updating method with anonymous type.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration_2()
{
var source0 =
@"class C
{
static object F()
{
var x = new { A = 1 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x + 1;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = new { A = (object)null };
var y = new { A = 'a', B = 'b' };
return x;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch
{
"F" => testData0.GetMethodData("C.F").GetEncDebugInfo(),
"G" => testData0.GetMethodData("C.G").GetEncDebugInfo(),
_ => default,
});
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames()); // no additional types
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true)));
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
CheckNames(readers, reader3.GetTypeDefNames()); // no additional types
}
/// <summary>
/// Local from previous generation is of an anonymous
/// type not available in next generation.
/// </summary>
[Fact]
public void AnonymousTypes_AddThenDelete()
{
var source0 =
@"class C
{
object A;
static object F()
{
var x = new C();
var y = x.A;
return y;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object() };
var y = x.A;
return y;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 2 };
var y = x.A;
y = new { B = new object() }.B;
return y;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 3 };
var y = x.A;
return y;
}
}";
var source4 =
@"class C
{
static object F()
{
var x = new { B = 4, A = new object() };
var y = x.A;
return y;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var compilation4 = compilation3.WithSource(source4);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type
diff1.VerifyIL("C.F", @"
{
// Code size 27 (0x1b)
.maxstack 1
.locals init ([unchanged] V_0,
object V_1, //y
[object] V_2,
<>f__AnonymousType0<object> V_3, //x
object V_4)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get""
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: stloc.s V_4
IL_0016: br.s IL_0018
IL_0018: ldloc.s V_4
IL_001a: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
}
[Fact]
public void AnonymousTypes_DifferentCase()
{
var source0 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { A = 1, B = 2 }</N:0>;
var <N:1>y = new { a = 3, b = 4 }</N:1>;
}
}");
var source1 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { AB = 3 }</N:1>;
}
}");
var source2 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { Ab = 5 }</N:1>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var m0 = compilation0.GetMember<MethodSymbol>("C.M");
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1");
// the first two slots can't be reused since the type changed
diff1.VerifyIL("C.M",
@"{
// Code size 17 (0x11)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.3
IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_000f: stloc.3
IL_0010: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1");
// we can reuse slot for "x", it's type haven't changed
diff2.VerifyIL("C.M",
@"{
// Code size 18 (0x12)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
[unchanged] V_3,
<>f__AnonymousType4<int> V_4) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.5
IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)""
IL_000f: stloc.s V_4
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Nested1()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: ret
}
";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Nested2()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: ret
}
";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Query1()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
<N:3>select new { Value = a, Length = a.Length }</N:3></N:4>;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value</N:8>;
args = args.Concat(newArgs).ToArray();
System.Diagnostics.Debugger.Break();
result.ToString();
}
}
");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null };
for (int i = 0; i < 10; i++)
{
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby a.Length ascending, a descending
<N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>;
var linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
(total, curr) => new { Head = curr.Value, Tail = (dynamic)total });
var str = linked?.Tail?.Head;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value + value</N:8>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1) //newArgs
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>o__0#1: {<>p__0}",
"C: {<>o__0#1, <>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}",
"<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1, //newArgs
<>f__AnonymousType5<dynamic, dynamic> V_2, //list
int V_3, //i
<>f__AnonymousType5<string, dynamic> V_4, //linked
object V_5, //str
<>f__AnonymousType5<string, dynamic> V_6,
object V_7,
bool V_8)
");
}
[Fact]
public void AnonymousTypes_Dynamic1()
{
var template = @"
using System;
class C
{
public void F()
{
var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>;
Console.WriteLine(x.B + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var baselineIL0 = @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}
";
v0.VerifyIL("C.F", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
var baselineIL = @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: ldc.i4.<<VALUE>>
IL_0010: add
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ret
}
";
diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2"));
}
/// <summary>
/// Should not re-use locals if the method metadata
/// signature is unsupported.
/// </summary>
[WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")]
public void LocalType_UnsupportedSignatureContent()
{
// Equivalent to C#, but with extra local and required modifier on
// expected local. Used to generate initial (unsupported) metadata.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method private static object F()
{
ldnull
ret
}
.method private static void M1()
{
.locals init ([0] object other, [1] object modreq(int32) o)
call object C::F()
stloc.1
ldloc.1
call void C::M2(object)
ret
}
.method private static void M2(object o)
{
ret
}
}";
var source =
@"class C
{
static object F()
{
return null;
}
static void M1()
{
object o = F();
M2(o);
}
static void M2(object o)
{
}
}";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 15 (0xf)
.maxstack 1
.locals init (object V_0) //o
IL_0000: nop
IL_0001: call ""object C.F()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""void C.M2(object)""
IL_000d: nop
IL_000e: ret
}");
}
/// <summary>
/// Should not re-use locals with custom modifiers.
/// </summary>
[WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")]
public void LocalType_CustomModifiers()
{
// Equivalent method signature to C#, but
// with optional modifier on locals.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class public C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F(class [mscorlib]System.IDisposable d)
{
.locals init ([0] class C modopt(int32) c,
[1] class [mscorlib]System.IDisposable modopt(object),
[2] bool V_2,
[3] object V_3)
ldnull
ret
}
}";
var source =
@"class C
{
static object F(System.IDisposable d)
{
C c;
using (d)
{
c = (C)d;
}
return c;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
moduleMetadata0,
m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[bool] V_2,
[object] V_3,
C V_4, //c
System.IDisposable V_5,
object V_6)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: stloc.s V_5
.try
{
-IL_0004: nop
-IL_0005: ldarg.0
IL_0006: castclass ""C""
IL_000b: stloc.s V_4
-IL_000d: nop
IL_000e: leave.s IL_001d
}
finally
{
~IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.s V_5
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
IL_001c: endfinally
}
-IL_001d: ldloc.s V_4
IL_001f: stloc.s V_6
IL_0021: br.s IL_0023
-IL_0023: ldloc.s V_6
IL_0025: ret
}", methodToken: diff1.EmitResult.UpdatedMethods.Single());
}
/// <summary>
/// Temporaries for locals used within a single
/// statement should not be preserved.
/// </summary>
[Fact]
public void TemporaryLocals_Other()
{
// Use increment as an example of a compiler generated
// temporary that does not span multiple statements.
var source =
@"class C
{
int P { get; set; }
static int M()
{
var c = new C();
return c.P++;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (C V_0, //c
[int] V_1,
[int] V_2,
int V_3,
int V_4)
IL_0000: nop
IL_0001: newobj ""C..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: dup
IL_0009: callvirt ""int C.P.get""
IL_000e: stloc.3
IL_000f: ldloc.3
IL_0010: ldc.i4.1
IL_0011: add
IL_0012: callvirt ""void C.P.set""
IL_0017: nop
IL_0018: ldloc.3
IL_0019: stloc.s V_4
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_4
IL_001f: ret
}");
}
/// <summary>
/// Local names array (from PDB) may have fewer slots than method
/// signature (from metadata) when the trailing slots are unnamed.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270()
{
var source =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
testData0.GetMethodData("C.M").VerifyIL(@"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
}
/// <summary>
/// Similar to above test but with no named locals in original.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270_NoNamedLocals()
{
// Equivalent to C#, but with unnamed locals.
// Used to generate initial metadata.
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
.assembly '<<GeneratedFileName>>' { }
.class C extends object
{
.method private static class [netstandard]System.IDisposable F()
{
ldnull
ret
}
.method private static void M()
{
.locals init ([0] object, [1] object)
ret
}
}";
var source0 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
}
}";
var source1 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init ([object] V_0,
[object] V_1,
System.IDisposable V_2) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.2
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.2
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.2
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}
");
}
[Fact]
public void TemporaryLocals_ReferencedType()
{
var source =
@"class C
{
static object F()
{
return null;
}
static void M()
{
var x = new System.Collections.Generic.HashSet<int>();
x.Add(1);
}
}";
var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var modMeta = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
modMeta,
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (System.Collections.Generic.HashSet<int> V_0) //x
IL_0000: nop
IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)""
IL_000e: pop
IL_000f: ret
}
");
}
[WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")]
[WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")]
[Fact]
public void DynamicOperations()
{
var source =
@"class A
{
static object F = null;
object x = ((dynamic)F) + 1;
static A()
{
((dynamic)F).F();
}
A() { }
static void M(object o)
{
((dynamic)o).x = 1;
}
static void N(A o)
{
o.x = 1;
}
}
class B
{
static object F = null;
static object G = ((dynamic)F).F();
object x = ((dynamic)F) + 1;
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef });
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
// Source method with dynamic operations.
var methodData0 = testData0.GetMethodData("A.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("A.M");
var method1 = compilation1.GetMember<MethodSymbol>("A.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Source method with no dynamic operations.
methodData0 = testData0.GetMethodData("A.N");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A.N");
method1 = compilation1.GetMember<MethodSymbol>("A.N");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..ctor");
method1 = compilation1.GetMember<MethodSymbol>("A..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..cctor");
method1 = compilation1.GetMember<MethodSymbol>("A..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..ctor");
method1 = compilation1.GetMember<MethodSymbol>("B..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..cctor");
method1 = compilation1.GetMember<MethodSymbol>("B..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void DynamicLocals()
{
var template = @"
using System;
class C
{
public void F()
{
dynamic <N:0>x = 1</N:0>;
Console.WriteLine((int)x + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 82 (0x52)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: call ""void System.Console.WriteLine(int)""
IL_0050: nop
IL_0051: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1}",
"C.<>o__0#1: {<>p__0}");
diff1.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.1
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <>o__0#1}",
"C.<>o__0#1: {<>p__0}",
"C.<>o__0#2: {<>p__0}");
diff2.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.2
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
}
[Fact]
public void ExceptionFilters()
{
var source0 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
}
}
");
var source1 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
Console.WriteLine(1);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 90 (0x5a)
.maxstack 2
.locals init (System.IO.IOException V_0, //e
bool V_1,
System.Exception V_2, //e
bool V_3)
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: newobj ""System.InvalidOperationException..ctor()""
IL_0007: throw
}
filter
{
IL_0008: isinst ""System.IO.IOException""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0020
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: call ""bool C.G(System.Exception)""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldc.i4.0
IL_001e: cgt.un
IL_0020: endfilter
} // end filter
{ // handler
IL_0022: pop
IL_0023: nop
IL_0024: call ""void System.Console.WriteLine()""
IL_0029: nop
IL_002a: nop
IL_002b: leave.s IL_0052
}
filter
{
IL_002d: isinst ""System.Exception""
IL_0032: dup
IL_0033: brtrue.s IL_0039
IL_0035: pop
IL_0036: ldc.i4.0
IL_0037: br.s IL_0045
IL_0039: stloc.2
IL_003a: ldloc.2
IL_003b: call ""bool C.G(System.Exception)""
IL_0040: stloc.3
IL_0041: ldloc.3
IL_0042: ldc.i4.0
IL_0043: cgt.un
IL_0045: endfilter
} // end filter
{ // handler
IL_0047: pop
IL_0048: nop
IL_0049: call ""void System.Console.WriteLine()""
IL_004e: nop
IL_004f: nop
IL_0050: leave.s IL_0052
}
IL_0052: ldc.i4.1
IL_0053: call ""void System.Console.WriteLine(int)""
IL_0058: nop
IL_0059: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void MethodSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(2);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
[WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void LocalSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(null);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(x);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,16): warning CS0219: The variable 'y' is assigned but its value is never used
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"),
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
/// <summary>
/// Disallow edits that require NoPIA references.
/// </summary>
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIAReferences()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")]
public interface IA
{
void M();
int P { get; }
event Action E;
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")]
public interface IB
{
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")]
public interface IC
{
}
public struct S
{
public object F;
}";
var source0 =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
var o = default(IA);
o.M();
M2(o.P);
o.E += M1;
M2(C<IA>.F);
M2(new S());
}
static void M2(object o)
{
}
}";
var source1A = source0;
var source1B =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
M2(null);
}
static void M2(object o)
{
}
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1A = compilation0.WithSource(source1A);
var compilation1B = compilation0.WithSource(source1B);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var method1B = compilation1B.GetMember<MethodSymbol>("C.M1");
var method1A = compilation1A.GetMember<MethodSymbol>("C.M1");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C<T>.M1");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
// Disallow edits that require NoPIA references.
var diff1A = compilation1A.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true)));
diff1A.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA"));
// Allow edits that do not require NoPIA references,
// even if the previous code included references.
var diff1B = compilation1B.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true)));
diff1B.VerifyIL("C<T>.M1",
@"{
// Code size 9 (0x9)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1)
IL_0000: nop
IL_0001: ldnull
IL_0002: call ""void C<T>.M2(object)""
IL_0007: nop
IL_0008: ret
}");
using var md1 = diff1B.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
}
[WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIATypeInNamespace()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")]
namespace N
{
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")]
public interface IA
{
}
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")]
public interface IB
{
}";
var source =
@"class C<T>
{
static void M(object o)
{
M(C<N.IA>.E.X);
M(C<IB>.E.X);
}
enum E { X }
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB"));
diff1.VerifyIL("C<T>.M",
@"{
// Code size 26 (0x1a)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: box ""C<N.IA>.E""
IL_0007: call ""void C<T>.M(object)""
IL_000c: nop
IL_000d: ldc.i4.0
IL_000e: box ""C<IB>.E""
IL_0013: call ""void C<T>.M(object)""
IL_0018: nop
IL_0019: ret
}");
}
/// <summary>
/// Should use TypeDef rather than TypeRef for unrecognized
/// local of a type defined in the original assembly.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfTypeFromAssembly()
{
var source =
@"class E : System.Exception
{
}
class C
{
static void M()
{
try
{
}
catch (E e)
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeRefNames(), "Object");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (E V_0) //e
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_000a
}
catch E
{
IL_0005: stloc.0
IL_0006: nop
IL_0007: nop
IL_0008: leave.s IL_000a
}
IL_000a: ret
}");
}
/// <summary>
/// Similar to above test but with anonymous type
/// added in subsequent generation.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfAnonymousTypeFromAssembly()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source2 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
return null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var method1G = compilation1.GetMember<MethodSymbol>("C.G");
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var method2G = compilation2.GetMember<MethodSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
// Use empty LocalVariableNameProvider for original locals and
// use preserveLocalVariables: true for the edit so that existing
// locals are retained even though all are unrecognized.
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1");
CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider");
// Change method updated in generation 1.
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetTypeRefNames(), "Object");
// Change method unchanged since generation 0.
var diff2G = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true)));
}
[Fact]
public void BrokenOutputStreams()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
badStream,
ilStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
badStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[Fact]
public void BrokenPortablePdbStream()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb));
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void Main() { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))),
testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
diff1.EmitResult.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(diff1.EmitResult.Success);
}
[WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")]
[Fact]
public void BlobContainsInvalidValues()
{
var source0 =
@"class C
{
static void F()
{
string goo = ""abc"";
}
}";
var source1 =
@"class C
{
static void F()
{
float goo = 10;
}
}";
var source2 =
@"class C
{
static void F()
{
bool goo = true;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
var handle = MetadataTokens.BlobHandle(1);
byte[] value0 = reader0.GetBlobBytes(handle);
Assert.Equal("20-01-01-08", BitConverter.ToString(value0));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
byte[] value1 = reader1.GetBlobBytes(handle);
Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
byte[] value2 = reader2.GetBlobBytes(handle);
Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly1()
{
var sourceA0 = @"
public class A
{
}
";
var sourceA1 = @"
public class A
{
public void M() { System.Console.WriteLine(1);}
}
public class X {}
";
var sourceB0 = @"
public class B
{
public static void F() { }
}";
var sourceB1 = @"
public class B
{
public static void F() { new A().M(); }
}
public class Y : X { }
";
var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA");
var compilationA1 = compilationA0.WithSource(sourceA1);
var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var bytesA0 = compilationA0.EmitToArray();
var bytesB0 = compilationB0.EmitToArray();
var mdA0 = ModuleMetadata.CreateFromImage(bytesA0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider);
var mA1 = compilationA1.GetMember<MethodSymbol>("A.M");
var mX1 = compilationA1.GetMember<TypeSymbol>("X");
var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() };
var diffA1 = compilationA1.EmitDifference(
generationA0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, mA1),
SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)),
allAddedSymbols);
diffA1.EmitResult.Diagnostics.Verify();
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))),
allAddedSymbols);
diffB1.EmitResult.Diagnostics.Verify(
// (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public class X {}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14),
// (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public void M() { System.Console.WriteLine(1);}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly2()
{
var sourceA = @"
public class A
{
public void M() { }
}";
var sourceB0 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var sourceB1 = @"
public class B
{
public static void F() { var a = new A(); a.M(); }
}";
var sourceB2 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA");
var aRef = compilationA.ToMetadataReference();
var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB");
var compilationB1 = compilationB0.WithSource(sourceB1);
var compilationB2 = compilationB1.WithSource(sourceB2);
var testDataB0 = new CompilationTestData();
var bytesB0 = compilationB0.EmitToArray(testData: testDataB0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider());
var f0 = compilationB0.GetMember<MethodSymbol>("B.F");
var f1 = compilationB1.GetMember<MethodSymbol>("B.F");
var f2 = compilationB2.GetMember<MethodSymbol>("B.F");
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
diffB1.VerifyIL("B.F", @"
{
// Code size 15 (0xf)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: callvirt ""void A.M()""
IL_000d: nop
IL_000e: ret
}
");
var diffB2 = compilationB2.EmitDifference(
diffB1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true)));
diffB2.VerifyIL("B.F", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void UniqueSynthesizedNames_DynamicSiteContainer()
{
var source0 = @"
public class C
{
public static void F(dynamic d) { d.Goo(); }
}";
var source1 = @"
public class C
{
public static void F(dynamic d) { d.Bar(); }
}";
var source2 = @"
public class C
{
public static void F(dynamic d, byte b) { d.Bar(); }
public static void F(dynamic d) { d.Bar(); }
}";
var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp,
options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
diff2.EmitResult.Diagnostics.Verify();
var reader0 = md0.MetadataReader;
var reader1 = diff1.GetMetadata().Reader;
var reader2 = diff2.GetMetadata().Reader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0");
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2");
}
[WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")]
[Fact]
public void ManyGenerations()
{
var source =
@"class C
{{
static int F() {{ return {0}; }}
}}";
var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll);
var bytes0 = compilation0.EmitToArray();
var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
for (int i = 2; i <= 50; i++)
{
var compilation1 = compilation0.WithSource(String.Format(source, i));
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
compilation0 = compilation1;
method0 = method1;
generation0 = diff1.NextGeneration;
}
}
[WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")]
[Fact]
public void PdbReadingErrors()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle =>
{
throw new InvalidDataException("Bad PDB!");
});
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''.
Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14));
}
[Fact]
public void PdbReadingErrors_PassThruExceptions()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle =>
{
throw new ArgumentOutOfRangeException();
});
// the compiler should't swallow any exceptions but InvalidDataException
Assert.Throws<ArgumentOutOfRangeException>(() =>
compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))));
}
[Fact]
public void PatternVariable_TypeChange()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3, //i
bool V_4,
int V_5)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""bool""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""bool""
IL_000f: stloc.3
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.s V_4
IL_0016: ldloc.s V_4
IL_0018: brfalse.s IL_0026
IL_001a: nop
IL_001b: ldloc.3
IL_001c: brtrue.s IL_0021
IL_001e: ldc.i4.0
IL_001f: br.s IL_0022
IL_0021: ldc.i4.1
IL_0022: stloc.s V_5
IL_0024: br.s IL_002b
IL_0026: ldc.i4.0
IL_0027: stloc.s V_5
IL_0029: br.s IL_002b
IL_002b: ldloc.s V_5
IL_002d: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[bool] V_4,
[int] V_5,
int V_6, //j
bool V_7,
int V_8)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_6
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_7
IL_0017: ldloc.s V_7
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_6
IL_001e: stloc.s V_8
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_8
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_8
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_DeleteInsert()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int) { return 1; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3,
int V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: brfalse.s IL_0014
IL_000e: nop
IL_000f: ldc.i4.1
IL_0010: stloc.s V_4
IL_0012: br.s IL_0019
IL_0014: ldc.i4.0
IL_0015: stloc.s V_4
IL_0017: br.s IL_0019
IL_0019: ldloc.s V_4
IL_001b: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[int] V_4,
int V_5, //i
bool V_6,
int V_7)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_5
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_6
IL_0017: ldloc.s V_6
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_5
IL_001e: stloc.s V_7
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_7
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_7
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(bool x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; }
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { }
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.1
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.1
IL_0015: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 15 (0xf)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: call ""Base..ctor(bool)""
IL_000c: nop
IL_000d: nop
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.2
IL_0015: ret
}
");
}
[Fact]
public void PatternVariable_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>;
}");
var source1 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.1
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: stfld ""bool C.field""
IL_0010: ldarg.0
IL_0011: call ""object..ctor()""
IL_0016: nop
IL_0017: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.2
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void PatternVariable_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.1
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 7 (0x7)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ceq
IL_0006: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.2
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
}
[Fact]
public void Tuple_Parenthesized()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)""
IL_0010: ldloc.0
IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1""
IL_0016: ldloc.0
IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0021: add
IL_0022: ldloc.0
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_002d: add
IL_002e: stloc.1
IL_002f: br.s IL_0031
IL_0031: ldloc.1
IL_0032: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init ([unchanged] V_0,
[int] V_1,
System.ValueTuple<int, int, int> V_2, //x
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_2
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)""
IL_000b: ldloc.2
IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1""
IL_0011: ldloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2""
IL_0017: add
IL_0018: ldloc.2
IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3""
IL_001e: add
IL_001f: stloc.3
IL_0020: br.s IL_0022
IL_0022: ldloc.3
IL_0023: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init ([unchanged] V_0,
[int] V_1,
[unchanged] V_2,
[int] V_3,
System.ValueTuple<int, int> V_4, //x
int V_5)
IL_0000: nop
IL_0001: ldloca.s V_4
IL_0003: ldc.i4.1
IL_0004: ldc.i4.3
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.s V_4
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: ldloc.s V_4
IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0018: add
IL_0019: stloc.s V_5
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_5
IL_001f: ret
}
");
}
[Fact]
public void Tuple_Decomposition()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2, //z
int V_3)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldc.i4.3
IL_0006: stloc.2
IL_0007: ldloc.0
IL_0008: ldloc.1
IL_0009: add
IL_000a: ldloc.2
IL_000b: add
IL_000c: stloc.3
IL_000d: br.s IL_000f
IL_000f: ldloc.3
IL_0010: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.3
IL_0004: stloc.2
IL_0005: ldloc.0
IL_0006: ldloc.2
IL_0007: add
IL_0008: stloc.s V_4
IL_000a: br.s IL_000c
IL_000c: ldloc.s V_4
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
[int] V_4,
int V_5, //y
int V_6)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.s V_5
IL_0006: ldc.i4.3
IL_0007: stloc.2
IL_0008: ldloc.0
IL_0009: ldloc.s V_5
IL_000b: add
IL_000c: ldloc.2
IL_000d: add
IL_000e: stloc.s V_6
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_6
IL_0014: ret
}
");
}
[Fact]
public void ForeachStatement()
{
var source0 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x);
}
}
}");
var source1 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var source2 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //x
bool V_3, //y
double V_4, //z
System.ValueTuple<bool, double> V_5)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.0
IL_0008: ldc.i4.0
IL_0009: stloc.1
IL_000a: br.s IL_003f
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0013: dup
IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0019: stloc.s V_5
IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0020: stloc.2
IL_0021: ldloc.s V_5
IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_0028: stloc.3
IL_0029: ldloc.s V_5
IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0030: stloc.s V_4
IL_0032: nop
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
IL_003a: nop
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
IL_0045: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.G", @"
{
// Code size 78 (0x4e)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
bool V_3, //y
double V_4, //z
[unchanged] V_5,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6,
int V_7,
System.ValueTuple<bool, double> V_8)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_6
IL_0009: ldc.i4.0
IL_000a: stloc.s V_7
IL_000c: br.s IL_0045
IL_000e: ldloc.s V_6
IL_0010: ldloc.s V_7
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_001d: stloc.s V_8
IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0024: stloc.2
IL_0025: ldloc.s V_8
IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_002c: stloc.3
IL_002d: ldloc.s V_8
IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0034: stloc.s V_4
IL_0036: nop
IL_0037: ldloc.2
IL_0038: call ""void System.Console.WriteLine(int)""
IL_003d: nop
IL_003e: nop
IL_003f: ldloc.s V_7
IL_0041: ldc.i4.1
IL_0042: add
IL_0043: stloc.s V_7
IL_0045: ldloc.s V_7
IL_0047: ldloc.s V_6
IL_0049: ldlen
IL_004a: conv.i4
IL_004b: blt.s IL_000e
IL_004d: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 61 (0x3d)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
[bool] V_3,
[unchanged] V_4,
[unchanged] V_5,
[unchanged] V_6,
[int] V_7,
[unchanged] V_8,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9,
int V_10,
System.ValueTuple<bool, double> V_11) //yz
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_9
IL_0009: ldc.i4.0
IL_000a: stloc.s V_10
IL_000c: br.s IL_0034
IL_000e: ldloc.s V_9
IL_0010: ldloc.s V_10
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_001d: stloc.2
IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0023: stloc.s V_11
IL_0025: nop
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
IL_002d: nop
IL_002e: ldloc.s V_10
IL_0030: ldc.i4.1
IL_0031: add
IL_0032: stloc.s V_10
IL_0034: ldloc.s V_10
IL_0036: ldloc.s V_9
IL_0038: ldlen
IL_0039: conv.i4
IL_003a: blt.s IL_000e
IL_003c: ret
}
");
}
[Fact]
public void OutVar()
{
var source0 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; }
}");
var source1 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.2
IL_000f: br.s IL_0011
IL_0011: ldloc.2
IL_0012: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //z
[int] V_2,
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.3
IL_000f: br.s IL_0011
IL_0011: ldloc.3
IL_0012: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
[int] V_2,
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.s V_4
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_4
IL_0014: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); }
static int M(out int x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x) { }
static int M(out int x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.1
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 18 (0x12)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: call ""Base..ctor(int)""
IL_000f: nop
IL_0010: nop
IL_0011: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.2
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer_WithLambda()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InMethodBody_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method");
var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method");
var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.1
IL_0025: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff1.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
int V_2) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.2
IL_0025: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff2.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
[int] V_2,
int V_3) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.3
IL_0025: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>);
static int M(out int x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x;
static int M(out int x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 23 (0x17)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: stfld ""int C.field""
IL_000f: ldarg.0
IL_0010: call ""object..ctor()""
IL_0015: nop
IL_0016: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_1
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_2
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
}
[Fact]
public void OutVar_InQuery_WithLambda()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InSwitchExpression()
{
var source0 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i switch
{
0 => 0,
_ => 1
};
}
static object N(out int x) { x = 1; return null; }
}");
var source1 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i + N(out var x) switch
{
0 => 0,
_ => 1
};
}
static int N(out int x) { x = 1; return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.G");
var n1 = compilation1.GetMember<MethodSymbol>("Program.G");
var n2 = compilation2.GetMember<MethodSymbol>("Program.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.G(int)", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init (int V_0,
object V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000e
IL_000a: ldc.i4.0
IL_000b: stloc.0
IL_000c: br.s IL_0012
IL_000e: ldc.i4.1
IL_000f: stloc.0
IL_0010: br.s IL_0012
IL_0012: ldc.i4.1
IL_0013: brtrue.s IL_0016
IL_0015: nop
IL_0016: ldloc.0
IL_0017: box ""int""
IL_001c: stloc.1
IL_001d: br.s IL_001f
IL_001f: ldloc.1
IL_0020: ret
}
");
v0.VerifyIL("Program.N(out int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (object V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.1
IL_0003: stind.i4
IL_0004: ldnull
IL_0005: stloc.0
IL_0006: br.s IL_0008
IL_0008: ldloc.0
IL_0009: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers();
diff1.VerifyIL("Program.G(int)", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init ([int] V_0,
[object] V_1,
int V_2, //x
int V_3,
int V_4,
int V_5,
object V_6)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloca.s V_2
IL_0005: call ""int Program.N(out int)""
IL_000a: stloc.s V_5
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
IL_000f: nop
IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_0016
IL_0014: br.s IL_001b
IL_0016: ldc.i4.0
IL_0017: stloc.s V_4
IL_0019: br.s IL_0020
IL_001b: ldc.i4.1
IL_001c: stloc.s V_4
IL_001e: br.s IL_0020
IL_0020: ldc.i4.1
IL_0021: brtrue.s IL_0024
IL_0023: nop
IL_0024: ldloc.3
IL_0025: ldloc.s V_4
IL_0027: add
IL_0028: box ""int""
IL_002d: stloc.s V_6
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_6
IL_0033: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers();
diff2.VerifyIL("Program.G(int)", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[int] V_2,
[int] V_3,
[int] V_4,
[int] V_5,
[object] V_6,
int V_7,
object V_8)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000f
IL_000a: ldc.i4.0
IL_000b: stloc.s V_7
IL_000d: br.s IL_0014
IL_000f: ldc.i4.1
IL_0010: stloc.s V_7
IL_0012: br.s IL_0014
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
IL_0017: nop
IL_0018: ldloc.s V_7
IL_001a: box ""int""
IL_001f: stloc.s V_8
IL_0021: br.s IL_0023
IL_0023: ldloc.s V_8
IL_0025: ret
}
");
}
[Fact]
public void AddUsing_AmbiguousCode()
{
var source0 = MarkedSource(@"
using System.Threading;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
}");
var source1 = MarkedSource(@"
using System.Threading;
using System.Timers;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
static void G()
{
System.Console.WriteLine(new TimersDescriptionAttribute(""""));
}
}");
var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Pretend there was an update to C.E to ensure we haven't invalidated the test
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer'
// var t = new Timer(s => System.Console.WriteLine(s));
Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21));
// Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff.EmitResult.Diagnostics.Verify();
diff.VerifyIL(@"C.G", @"
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldstr """"
IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)""
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void Records_AddWellKnownMember()
{
var source0 =
@"
#nullable enable
namespace N
{
record R(int X)
{
}
}
";
var source1 =
@"
#nullable enable
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
// Verify full metadata contains expected rows.
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R");
CheckNames(reader0, reader0.GetMethodDefNames(),
/* EmbeddedAttribute */".ctor",
/* NullableAttribute */ ".ctor",
/* NullableContextAttribute */".ctor",
/* IsExternalInit */".ctor",
/* R: */
".ctor",
"get_EqualityContract",
"get_X",
"set_X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), // R.PrintMembers
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(10, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Records_RemoveWellKnownMember()
{
var source0 =
@"
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var source1 =
@"
namespace N
{
record R(int X)
{
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
}
[Fact]
public void TopLevelStatement_Update()
{
var source0 = @"
using System;
Console.WriteLine(""Hello"");
";
var source1 = @"
using System;
Console.WriteLine(""Hello World"");
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("<Program>$.<Main>$");
var method1 = compilation1.GetMember<MethodSymbol>("<Program>$.<Main>$");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<Program>$");
CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$");
CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
/// <summary>
/// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test.
/// </summary>
public class EditAndContinueTests : EditAndContinueTestBase
{
private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers)
{
var currentGenerationReader = readers.Last();
foreach (var typeRefHandle in currentGenerationReader.TypeReferences)
{
var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle);
yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}";
}
}
[Fact]
public void DeltaHeapsStartWithEmptyItem()
{
var source0 =
@"class C
{
static string F() { return null; }
}";
var source1 =
@"class C
{
static string F() { return ""a""; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var s = MetadataTokens.StringHandle(0);
Assert.Equal("", reader1.GetString(s));
var b = MetadataTokens.BlobHandle(0);
Assert.Equal(0, reader1.GetBlobBytes(b).Length);
var us = MetadataTokens.UserStringHandle(0);
Assert.Equal("", reader1.GetUserString(us));
}
[Fact]
public void Delta_AssemblyDefTable()
{
var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }";
var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
// AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed:
Assert.True(md0.MetadataReader.IsAssembly);
Assert.False(diff1.GetMetadata().Reader.IsAssembly);
}
[Fact]
public void SemanticErrors_MethodBody()
{
var source0 = MarkedSource(@"
class C
{
static void E()
{
int x = 1;
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void E()
{
int x = Unknown(2);
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(2);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Semantic errors are reported only for the bodies of members being emitted.
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (6,17): error CS0103: The name 'Unknown' does not exist in the current context
// int x = Unknown(2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17));
var diffGood = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffGood.EmitResult.Diagnostics.Verify();
diffGood.VerifyIL(@"C.G", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}
");
}
[Fact]
public void SemanticErrors_Declaration()
{
var source0 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(1);
}
}
");
var source1 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(2);
}
}
class Bad : Bad
{
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// All declaration errors are reported regardless of what member do we emit.
diff.EmitResult.Diagnostics.Verify(
// (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad'
// class Bad : Bad
Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7));
}
[Fact]
public void ModifyMethod()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[CompilerTrait(CompilerFeature.Tuples)]
[Fact]
public void ModifyMethod_WithTuples()
{
var source0 =
@"class C
{
static void Main() { }
static (int, int) F() { return (1, 2); }
}";
var source1 =
@"class C
{
static void Main() { }
static (int, int) F() { return (2, 3); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}";
var source3 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
Assert.Equal(4, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")),
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(3, reader2.CustomAttributes.Count);
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute
CheckEncMap(reader2,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(2, TableIndex.TypeDef),
Handle(2, TableIndex.MethodDef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(10, TableIndex.MemberRef),
Handle(11, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted
CheckEncMap(reader3,
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(12, TableIndex.MemberRef),
Handle(13, TableIndex.MemberRef),
Handle(14, TableIndex.MemberRef),
Handle(15, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes2()
{
var source0 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A"")]
static string A() { return null; }
}
";
var source1 =
@"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")]
static string A() { return null; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0_1 = compilation0.GetMember<MethodSymbol>("C.F");
var method0_2 = compilation0.GetMember<MethodSymbol>("D.A");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1_1 = compilation1.GetMember<MethodSymbol>("C.F");
var method1_2 = compilation1.GetMember<MethodSymbol>("D.A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1),
SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "A");
CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var source2 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes2()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 = source0; // Remove the attribute we just added
var source3 = source1; // Add the attribute back again
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation1.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames());
CheckAttributes(reader2,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader3,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row
CheckEncMap(reader3,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")]
[Fact]
public void PartialMethod()
{
var source =
@"partial class C
{
static partial void M1();
static partial void M2();
static partial void M3();
static partial void M1() { }
static partial void M2() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor");
var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
var methods = diff1.TestData.GetMethodsByName();
Assert.Equal(1, methods.Count);
Assert.True(methods.ContainsKey("C.M2()"));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "M2");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Method_WithAttributes_Add()
{
var source0 =
@"class C
{
static void Main() { }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_ParameterAttributes()
{
var source0 =
@"class C
{
static void Main() { }
static string F(string input, int a) { return input; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; }
static void G(string input) { }
}";
var source2 =
@"class C
{
static void Main() { }
static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; }
static void G([System.ComponentModel.Description(""input"")]string input) { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var methodF0 = compilation0.GetMember<MethodSymbol>("C.F");
var methodF1 = compilation1.GetMember<MethodSymbol>("C.F");
var methodG1 = compilation1.GetMember<MethodSymbol>("C.G");
var methodG2 = compilation2.GetMember<MethodSymbol>("C.G");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1),
SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor");
CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G
Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param
Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param),
Handle(5, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "G");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor");
CheckNames(readers, reader2.GetParameterDefNames(), "input");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(4, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(6, TableIndex.MemberRef),
Handle(5, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyDelegateInvokeMethod_AddAttributes()
{
var source0 = @"
class A : System.Attribute { }
delegate void D(int x);
";
var source1 = @"
class A : System.Attribute { }
delegate void D([A]int x);
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke");
var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke");
var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke");
var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1),
SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke");
CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param),
Handle(6, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(2, TableIndex.AssemblyRef));
}
/// <summary>
/// Add a method that requires entries in the ParameterDefs table.
/// Specifically, normal parameters or return types with attributes.
/// Add the method in the first edit, then modify the method in the second.
/// </summary>
[Fact]
public void Method_WithParameterAttributes_AddThenUpdate()
{
var source0 =
@"class A : System.Attribute { }
class C
{
}";
var source1 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => arg;
}";
var source2 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => null;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetParameterDefNames(), "", "arg");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(1, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(1, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckEncLogDefinitions(reader2,
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(2, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void Method_WithEmbeddedAttributes_AndThenUpdate()
{
var source0 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
class C
{
static void Main() { }
}
}
";
var source1 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main()
{
Id(in G());
}
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 1 }[0];
}
}";
var source2 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
}
}";
var source3 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
readonly ref readonly string?[]? F() => throw null;
}
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main");
var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id");
var g1 = compilation1.GetMember<MethodSymbol>("N.C.G");
var g2 = compilation2.GetMember<MethodSymbol>("N.C.G");
var h2 = compilation2.GetMember<MethodSymbol>("N.C.H");
var f3 = compilation3.GetMember<MethodSymbol>("N.C.F");
// Verify full metadata contains expected rows.
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, id1),
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute}");
diff1.VerifyIL("N.C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: nop
IL_0001: call ""ref readonly int N.C.G()""
IL_0006: call ""ref readonly int N.C.Id(in int)""
IL_000b: pop
IL_000c: ret
}
");
diff1.VerifyIL("N.C.Id", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
");
diff1.VerifyIL("N.C.G", @"
{
// Code size 17 (0x11)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: newarr ""int""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: stelem.i4
IL_000a: ldc.i4.0
IL_000b: ldelema ""int""
IL_0010: ret
}
");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader0 = md0.MetadataReader;
var reader1 = md1.Reader;
var readers = new List<MetadataReader>() { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute");
CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g1, g2),
SemanticEdit.Create(SemanticEditKind.Insert, null, h2)));
// synthesized member for nullable annotations added:
diff2.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
// note: NullableAttribute has 2 ctors, NullableContextAttribute has one
CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute");
CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H");
// two new TypeDefs emitted for the attributes:
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute
Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(6, TableIndex.TypeDef),
Handle(7, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(2, TableIndex.Field),
Handle(7, TableIndex.MethodDef),
Handle(8, TableIndex.MethodDef),
Handle(9, TableIndex.MethodDef),
Handle(10, TableIndex.MethodDef),
Handle(11, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(6, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(12, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3)));
// no change in synthesized members:
diff3.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
// no new type defs:
CheckNames(readers, reader3.GetTypeDefFullNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void Field_Add()
{
var source0 =
@"class C
{
string F = ""F"";
}";
var source1 =
@"class C
{
string F = ""F"";
string G = ""G"";
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetFieldDefNames(), "F");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var method1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "G");
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Accessor_Update()
{
var source0 =
@"class C
{
object P { get { return 1; } }
}";
var source1 =
@"class C
{
object P { get { return 2; } }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P");
var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetPropertyDefNames(), "P");
CheckNames(readers, reader1.GetMethodDefNames(), "get_P");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Add()
{
var source0 = @"
class C
{
}
";
var source1 = @"
class C
{
object R { get { return null; } }
}
";
var source2 = @"
class C
{
object R { get { return null; } }
object Q { get; set; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var r1 = compilation1.GetMember<PropertySymbol>("C.R");
var q2 = compilation2.GetMember<PropertySymbol>("C.Q");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetPropertyDefNames(), "R");
CheckNames(readers, reader1.GetMethodDefNames(), "get_R");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.MethodDef),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.PropertyMap),
Handle(1, TableIndex.Property),
Handle(1, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, q2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField");
CheckNames(readers, reader2.GetPropertyDefNames(), "Q");
CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(1, TableIndex.Field),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(2, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(3, TableIndex.MethodSemantics));
}
[Fact]
public void Event_Add()
{
var source0 = @"
class C
{
}";
var source1 = @"
class C
{
event System.Action E;
}";
var source2 = @"
class C
{
event System.Action E;
event System.Action G;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var e1 = compilation1.GetMember<EventSymbol>("C.E");
var g2 = compilation2.GetMember<EventSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, e1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "E");
CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(1, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(1, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.EventMap),
Handle(1, TableIndex.Event),
Handle(1, TableIndex.MethodSemantics),
Handle(2, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "G");
CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.Field),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics));
}
[WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")]
[Fact]
public void EventFields()
{
var source0 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 1;
}
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 10;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 3
.locals init (int V_0)
IL_0000: nop
IL_0001: ldsfld ""System.EventHandler C.handler""
IL_0006: ldnull
IL_0007: ldnull
IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)""
IL_000d: nop
IL_000e: ldc.i4.s 10
IL_0010: stloc.0
IL_0011: br.s IL_0013
IL_0013: ldloc.0
IL_0014: ret
}
");
}
[Fact]
public void UpdateType_AddAttributes()
{
var source0 = @"
class C
{
}";
var source1 = @"
[System.ComponentModel.Description(""C"")]
class C
{
}";
var source2 = @"
[System.ComponentModel.Description(""C"")]
[System.ObsoleteAttribute]
class C
{
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
Assert.Equal(2, reader2.CustomAttributes.Count);
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute));
}
[Fact]
public void ReplaceType()
{
var source0 = @"
class C
{
void F(int x) {}
}
";
var source1 = @"
class C
{
void F(int x, int y) { }
}";
var source2 = @"
class C
{
void F(int x, int y) { System.Console.WriteLine(1); }
}";
var source3 = @"
[System.Obsolete]
class C
{
void F(int x, int y) { System.Console.WriteLine(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var c3 = compilation3.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
var f3 = c3.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C#1");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param));
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C#2");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader2,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param));
// This update is an EnC update - even reloadable types are update in-place
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, c2, c3),
SemanticEdit.Create(SemanticEditKind.Update, f2, f3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames(), "C#2");
CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader3,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader3,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void ReplaceType_AsyncLambda()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
void F(int x) { Task.Run(async() => {}); }
}
";
var source1 = @"
using System.Threading.Tasks;
class C
{
void F(bool y) { Task.Run(async() => {}); }
}
";
var source2 = @"
using System.Threading.Tasks;
class C
{
void F(uint z) { Task.Run(async() => {}); }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c", "<<F>b__0_0>d");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
// A new nested type <>c is generated in C#1
CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "<>c", "<<F>b__0#1_0#1>d");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "<>c", "<<F>b__0#1_0#1>d");
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
// A new nested type <>c is generated in C#2
CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "<>c", "<<F>b__0#2_0#2>d");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "<>c", "<<F>b__0#2_0#2>d");
}
[Fact]
public void ReplaceType_AsyncLambda_InNestedType()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
class D
{
void F(int x) { Task.Run(async() => {}); }
}
}
";
var source1 = @"
using System.Threading.Tasks;
class C
{
class D
{
void F(bool y) { Task.Run(async() => {}); }
}
}
";
var source2 = @"
using System.Threading.Tasks;
class C
{
class D
{
void F(uint z) { Task.Run(async() => {}); }
}
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D", "<>c", "<<F>b__0_0>d");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
// A new nested type <>c is generated in C#1
CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "D", "<>c", "<<F>b__0#1_0#1>d");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "D", "<>c", "<<F>b__0#1_0#1>d");
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
// A new nested type <>c is generated in C#2
CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "D", "<>c", "<<F>b__0#2_0#2>d");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "D", "<>c", "<<F>b__0#2_0#2>d");
}
[Fact]
public void AddNestedTypeAndMembers()
{
var source0 =
@"class A
{
class B { }
static object F()
{
return new B();
}
}";
var source1 =
@"class A
{
class B { }
class C
{
class D { }
static object F;
internal static object G()
{
return F;
}
}
static object F()
{
return C.G();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C");
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C", "D");
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor");
CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D");
Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(3, TableIndex.NestedClass));
}
/// <summary>
/// Nested types should be emitted in the
/// same order as full emit.
/// </summary>
[Fact]
public void AddNestedTypesOrder()
{
var source0 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
}";
var source1 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
class B3
{
class C3 { }
}
class B4
{
class C4 { }
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2");
Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4");
Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass));
}
[Fact]
public void AddNestedGenericType()
{
var source0 =
@"class A
{
class B<T>
{
}
static object F()
{
return null;
}
}";
var source1 =
@"class A
{
class B<T>
{
internal class C<U>
{
internal object F<V>() where V : T, new()
{
return new C<V>();
}
}
}
static object F()
{
return new B<A>.C<B<object>>().F<A>();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1");
CheckNames(readers, reader1.GetTypeDefNames(), "C`1");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.TypeSpec),
Handle(2, TableIndex.TypeSpec),
Handle(3, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(2, TableIndex.GenericParam),
Handle(3, TableIndex.GenericParam),
Handle(4, TableIndex.GenericParam),
Handle(1, TableIndex.MethodSpec),
Handle(1, TableIndex.GenericParamConstraint));
}
[Fact]
public void AddNamespace()
{
var source0 =
@"
class C
{
static void Main() { }
}";
var source1 =
@"
namespace N
{
class D { public static void F() { } }
}
class C
{
static void Main() => N.D.F();
}";
var source2 =
@"
namespace N
{
class D { public static void F() { } }
namespace M
{
class E { public static void G() { } }
}
}
class C
{
static void Main() => N.M.E.G();
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var d1 = compilation1.GetMember<NamedTypeSymbol>("N.D");
var e2 = compilation2.GetMember<NamedTypeSymbol>("N.M.E");
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, d1)));
diff1.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N.D.F()""
IL_0005: nop
IL_0006: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main1, main2),
SemanticEdit.Create(SemanticEditKind.Insert, null, e2)));
diff2.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N.M.E.G()""
IL_0005: nop
IL_0006: ret
}");
}
[Fact]
public void ModifyExplicitImplementation()
{
var source =
@"interface I
{
void M();
}
class C : I
{
void I.M() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddThenModifyExplicitImplementation()
{
var source0 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
}";
var source1 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
void I.M() { }
}";
var source2 = source1;
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(2, TableIndex.MethodImpl),
Handle(2, TableIndex.AssemblyRef));
var generation1 = diff1.NextGeneration;
var diff2 = compilation2.EmitDifference(
generation1,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetMethodDefNames(), "I.M");
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(7, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(3, TableIndex.AssemblyRef));
}
[WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")]
[Fact]
public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation()
{
var source = @"
interface I
{
void M();
}
class C : I
{
public C()
{
}
void I.M() { }
}
";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddAndModifyInterfaceMembers()
{
var source0 = @"
using System;
interface I
{
}";
var source1 = @"
using System;
interface I
{
static int X = 10;
static event Action Y;
static void M() { }
void N() { }
static int P { get => 1; set { } }
int Q { get => 1; set { } }
static event Action E { add { } remove { } }
event Action F { add { } remove { } }
interface J { }
}";
var source2 = @"
using System;
interface I
{
static int X = 2;
static event Action Y;
static I() { X--; }
static void M() { X++; }
void N() { X++; }
static int P { get => 3; set { X++; } }
int Q { get => 3; set { X++; } }
static event Action E { add { X++; } remove { X++; } }
event Action F { add { X++; } remove { X++; } }
interface J { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var x1 = compilation1.GetMember<FieldSymbol>("I.X");
var y1 = compilation1.GetMember<EventSymbol>("I.Y");
var m1 = compilation1.GetMember<MethodSymbol>("I.M");
var n1 = compilation1.GetMember<MethodSymbol>("I.N");
var p1 = compilation1.GetMember<PropertySymbol>("I.P");
var q1 = compilation1.GetMember<PropertySymbol>("I.Q");
var e1 = compilation1.GetMember<EventSymbol>("I.E");
var f1 = compilation1.GetMember<EventSymbol>("I.F");
var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J");
var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P");
var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P");
var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q");
var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q");
var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E");
var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E");
var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F");
var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F");
var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var x2 = compilation2.GetMember<FieldSymbol>("I.X");
var m2 = compilation2.GetMember<MethodSymbol>("I.M");
var n2 = compilation2.GetMember<MethodSymbol>("I.N");
var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P");
var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P");
var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q");
var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q");
var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E");
var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E");
var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F");
var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F");
var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, x1),
SemanticEdit.Create(SemanticEditKind.Insert, null, y1),
SemanticEdit.Create(SemanticEditKind.Insert, null, m1),
SemanticEdit.Create(SemanticEditKind.Insert, null, n1),
SemanticEdit.Create(SemanticEditKind.Insert, null, p1),
SemanticEdit.Create(SemanticEditKind.Insert, null, q1),
SemanticEdit.Create(SemanticEditKind.Insert, null, e1),
SemanticEdit.Create(SemanticEditKind.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Insert, null, j1),
SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader1.GetTypeDefNames(), "J");
CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y");
CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, x1, x2),
SemanticEdit.Create(SemanticEditKind.Update, m1, m2),
SemanticEdit.Create(SemanticEditKind.Update, n1, n2),
SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2),
SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2),
SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2),
SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2),
SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2),
SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2),
SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2),
SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2),
SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "X");
CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(3, TableIndex.Event, EditAndContinueOperation.Default),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
diff2.VerifyIL(@"
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: nop
IL_0001: ldsfld 0x04000001
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: stsfld 0x04000001
IL_000d: ret
}
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.3
IL_0001: ret
}
{
// Code size 20 (0x14)
.maxstack 8
IL_0000: ldc.i4.2
IL_0001: stsfld 0x04000001
IL_0006: nop
IL_0007: ldsfld 0x04000001
IL_000c: ldc.i4.1
IL_000d: sub
IL_000e: stsfld 0x04000001
IL_0013: ret
}
");
}
[Fact]
public void AddAttributeReferences()
{
var source0 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static object F1;
[A] static object P1 { get { return null; } }
[B] static event D E1;
}
delegate void D();
";
var source1 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static void M2<[A]T>() { }
[B] static object F1;
[A] static object F2;
[A] static object P1 { get { return null; } }
[B] static object P2 { get { return null; } }
[B] static event D E1;
[A] static event D E2;
}
delegate void D();
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(12, TableIndex.MethodDef),
Handle(13, TableIndex.MethodDef),
Handle(14, TableIndex.MethodDef),
Handle(15, TableIndex.MethodDef),
Handle(8, TableIndex.Param),
Handle(9, TableIndex.Param),
Handle(7, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(18, TableIndex.CustomAttribute),
Handle(19, TableIndex.CustomAttribute),
Handle(20, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(2, TableIndex.Property),
Handle(4, TableIndex.MethodSemantics),
Handle(5, TableIndex.MethodSemantics),
Handle(6, TableIndex.MethodSemantics),
Handle(2, TableIndex.GenericParam));
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)));
}
/// <summary>
/// [assembly: ...] and [module: ...] attributes should
/// not be included in delta metadata.
/// </summary>
[Fact]
public void AssemblyAndModuleAttributeReferences()
{
var source0 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
}";
var source1 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var readers = new[] { reader0, md1.Reader };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, md1.Reader.GetTypeDefNames());
CheckNames(readers, md1.Reader.GetMethodDefNames(), "M");
CheckEncLog(md1.Reader,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M
CheckEncMap(md1.Reader,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void OtherReferences()
{
var source0 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
}
}";
var source1 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
object o;
o = typeof(D);
o = F;
o = P;
E += null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C");
CheckNames(reader0, reader0.GetEventDefNames(), "E");
CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor");
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
// Emit delta metadata.
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetEventDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M");
CheckNames(readers, reader1.GetPropertyDefNames());
}
[Fact]
public void ArrayInitializer()
{
var source0 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3 };
}
}");
var source1 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3, 4 };
}
}");
var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll);
var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs"));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M"))));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL(
@"{
// Code size 25 (0x19)
.maxstack 4
IL_0000: nop
IL_0001: ldc.i4.4
IL_0002: newarr 0x0100000D
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.4
IL_0016: stelem.i4
IL_0017: stloc.0
IL_0018: ret
}");
diff1.VerifyPdb(new[] { 0x06000001 },
@"<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" />
</files>
<methods>
<method token=""0x6000001"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x19"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void PInvokeModuleRefAndImplMap()
{
var source0 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
}";
var source1 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
[DllImport(""msvcrt.dll"")]
public static extern int puts(string s);
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.ImplMap));
}
/// <summary>
/// ClassLayout and FieldLayout tables.
/// </summary>
[Fact]
public void ClassAndFieldLayout()
{
var source0 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}";
var source1 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}
[StructLayout(LayoutKind.Explicit, Pack=4)]
class B
{
[FieldOffset(0)]internal short F;
[FieldOffset(4)]internal short G;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default),
Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default),
Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.ClassLayout),
Handle(3, TableIndex.FieldLayout),
Handle(4, TableIndex.FieldLayout),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void NamespacesAndOverloads()
{
var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source:
@"class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
}
}
}");
var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2");
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var compilation1 = compilation0.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
}
}
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2])));
diff1.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
}");
var compilation2 = compilation1.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
M1(c);
}
}
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"),
compilation2.GetMember<MethodSymbol>("M.C.M2"))));
diff2.VerifyIL(
@"{
// Code size 26 (0x1a)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: call 0x06000002
IL_0008: nop
IL_0009: ldarg.0
IL_000a: ldarg.2
IL_000b: call 0x06000003
IL_0010: nop
IL_0011: ldarg.0
IL_0012: ldarg.3
IL_0013: call 0x06000007
IL_0018: nop
IL_0019: ret
}");
}
[Fact]
public void TypesAndOverloads()
{
const string source =
@"using System;
struct A<T>
{
internal class B<U> { }
}
class B { }
class C
{
static void M(A<B>.B<object> a)
{
M(a);
M((A<B>.B<B>)null);
}
static void M(A<B>.B<B> a)
{
M(a);
M((A<B>.B<object>)null);
}
static void M(A<B> a)
{
M(a);
M((A<B>?)a);
}
static void M(Nullable<A<B>> a)
{
M(a);
M(a.Value);
}
unsafe static void M(int* p)
{
M(p);
M((byte*)p);
}
unsafe static void M(byte* p)
{
M(p);
M((int*)p);
}
static void M(B[][] b)
{
M(b);
M((object[][])b);
}
static void M(object[][] b)
{
M(b);
M((B[][])b);
}
static void M(A<B[]>.B<object> b)
{
M(b);
M((A<B[, ,]>.B<object>)null);
}
static void M(A<B[, ,]>.B<object> b)
{
M(b);
M((A<B[]>.B<object>)null);
}
static void M(dynamic d)
{
M(d);
M((dynamic[])d);
}
static void M(dynamic[] d)
{
M(d);
M((dynamic)d);
}
static void M<T>(A<int>.B<T> t) where T : B
{
M(t);
M((A<double>.B<int>)null);
}
static void M<T>(A<double>.B<T> t) where T : struct
{
M(t);
M((A<int>.B<B>)null);
}
}";
var options = TestOptions.UnsafeDebugDll;
var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef });
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var n = compilation0.GetMembers("C.M").Length;
Assert.Equal(14, n);
//static void M(A<B>.B<object> a)
//{
// M(a);
// M((A<B>.B<B>)null);
//}
var compilation1 = compilation0.WithSource(source);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0])));
diff1.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B>.B<B> a)
//{
// M(a);
// M((A<B>.B<object>)null);
//}
var compilation2 = compilation1.WithSource(source);
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1])));
diff2.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000003
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000002
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B> a)
//{
// M(a);
// M((A<B>?)a);
//}
var compilation3 = compilation2.WithSource(source);
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2])));
diff3.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000004
IL_0007: nop
IL_0008: ldarg.0
IL_0009: newobj 0x0A000016
IL_000e: call 0x06000005
IL_0013: nop
IL_0014: ret
}");
//static void M(Nullable<A<B>> a)
//{
// M(a);
// M(a.Value);
//}
var compilation4 = compilation3.WithSource(source);
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3])));
diff4.VerifyIL(
@"{
// Code size 22 (0x16)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000005
IL_0007: nop
IL_0008: ldarga.s V_0
IL_000a: call 0x0A000017
IL_000f: call 0x06000004
IL_0014: nop
IL_0015: ret
}");
//unsafe static void M(int* p)
//{
// M(p);
// M((byte*)p);
//}
var compilation5 = compilation4.WithSource(source);
var diff5 = compilation5.EmitDifference(
diff4.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4])));
diff5.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000006
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000007
IL_000e: nop
IL_000f: ret
}");
//unsafe static void M(byte* p)
//{
// M(p);
// M((int*)p);
//}
var compilation6 = compilation5.WithSource(source);
var diff6 = compilation6.EmitDifference(
diff5.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5])));
diff6.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000007
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000006
IL_000e: nop
IL_000f: ret
}");
//static void M(B[][] b)
//{
// M(b);
// M((object[][])b);
//}
var compilation7 = compilation6.WithSource(source);
var diff7 = compilation7.EmitDifference(
diff6.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6])));
diff7.VerifyIL(
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000008
IL_0007: nop
IL_0008: ldarg.0
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: call 0x06000009
IL_0010: nop
IL_0011: ret
}");
//static void M(object[][] b)
//{
// M(b);
// M((B[][])b);
//}
var compilation8 = compilation7.WithSource(source);
var diff8 = compilation8.EmitDifference(
diff7.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7])));
diff8.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000009
IL_0007: nop
IL_0008: ldarg.0
IL_0009: castclass 0x1B00000A
IL_000e: call 0x06000008
IL_0013: nop
IL_0014: ret
}");
//static void M(A<B[]>.B<object> b)
//{
// M(b);
// M((A<B[,,]>.B<object>)null);
//}
var compilation9 = compilation8.WithSource(source);
var diff9 = compilation9.EmitDifference(
diff8.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8])));
diff9.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000A
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000B
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B[,,]>.B<object> b)
//{
// M(b);
// M((A<B[]>.B<object>)null);
//}
var compilation10 = compilation9.WithSource(source);
var diff10 = compilation10.EmitDifference(
diff9.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9])));
diff10.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000B
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000A
IL_000e: nop
IL_000f: ret
}");
// TODO: dynamic
#if false
//static void M(dynamic d)
//{
// M(d);
// M((dynamic[])d);
//}
previousMethod = compilation.GetMembers("C.M")[10];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(dynamic[] d)
//{
// M(d);
// M((dynamic)d);
//}
previousMethod = compilation.GetMembers("C.M")[11];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
#endif
//static void M<T>(A<int>.B<T> t) where T : B
//{
// M(t);
// M((A<double>.B<int>)null);
//}
var compilation11 = compilation10.WithSource(source);
var diff11 = compilation11.EmitDifference(
diff10.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12])));
diff11.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000005
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000006
IL_000e: nop
IL_000f: ret
}");
//static void M<T>(A<double>.B<T> t) where T : struct
//{
// M(t);
// M((A<int>.B<B>)null);
//}
var compilation12 = compilation11.WithSource(source);
var diff12 = compilation12.EmitDifference(
diff11.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13])));
diff12.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000007
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000008
IL_000e: nop
IL_000f: ret
}");
}
/// <summary>
/// Types should be retained in deleted locals
/// for correct alignment of remaining locals.
/// </summary>
[Fact]
public void DeletedValueTypeLocal()
{
var source0 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var x = new S1(1, 2);
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var source1 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.Main");
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
testData0.GetMethodData("C.Main").VerifyIL(
@"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (S1 V_0, //x
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""S1..ctor(int, int)""
IL_000a: ldloca.s V_1
IL_000c: ldc.i4.3
IL_000d: call ""S2..ctor(int)""
IL_0012: ldloc.1
IL_0013: ldfld ""int S2.C""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: nop
IL_001e: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init ([unchanged] V_0,
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_1
IL_0003: ldc.i4.3
IL_0004: call ""S2..ctor(int)""
IL_0009: ldloc.1
IL_000a: ldfld ""int S2.C""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}");
}
/// <summary>
/// Instance and static constructors synthesized for
/// PrivateImplementationDetails should not be
/// generated for delta.
/// </summary>
[Fact]
public void PrivateImplementationDetails()
{
var source =
@"class C
{
static int[] F = new int[] { 1, 2, 3 };
int[] G = new int[] { 4, 5, 6 };
int M(int index)
{
return F[index] + G[index];
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var reader0 = md0.MetadataReader;
var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames());
Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)));
}
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 22 (0x16)
.maxstack 3
.locals init ([int] V_0,
int V_1)
IL_0000: nop
IL_0001: ldsfld ""int[] C.F""
IL_0006: ldarg.1
IL_0007: ldelem.i4
IL_0008: ldarg.0
IL_0009: ldfld ""int[] C.G""
IL_000e: ldarg.1
IL_000f: ldelem.i4
IL_0010: add
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromMetadata()
{
var source0 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[0]);
}
}";
var source1 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[1]);
}
}";
var source2 =
@"class C
{
static void M()
{
int[] a = { 4, 5, 6, 7, 8, 9, 10 };
System.Console.WriteLine(a[1]);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE"));
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
methodData0.VerifyIL(
@" {
// Code size 29 (0x1d)
.maxstack 3
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ldc.i4.0
IL_0015: ldelem.i4
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
IL_001c: ret
}
");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"{
// Code size 30 (0x1e)
.maxstack 4
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.1
IL_0016: ldelem.i4
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: nop
IL_001d: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 48 (0x30)
.maxstack 4
.locals init ([unchanged] V_0,
int[] V_1) //a
IL_0000: nop
IL_0001: ldc.i4.7
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.4
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.5
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.6
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.7
IL_0016: stelem.i4
IL_0017: dup
IL_0018: ldc.i4.4
IL_0019: ldc.i4.8
IL_001a: stelem.i4
IL_001b: dup
IL_001c: ldc.i4.5
IL_001d: ldc.i4.s 9
IL_001f: stelem.i4
IL_0020: dup
IL_0021: ldc.i4.6
IL_0022: ldc.i4.s 10
IL_0024: stelem.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: ldelem.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromSource()
{
// PrivateImplementationDetails not needed initially.
var source0 =
@"class C
{
static object F1() { return null; }
static object F2() { return null; }
static object F3() { return null; }
static object F4() { return null; }
}";
var source1 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return null; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var source2 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return new[] { 13, 14, 15 }; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4"))));
diff1.VerifyIL("C.F1",
@"{
// Code size 24 (0x18)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: ldloc.0
IL_0017: ret
}");
diff1.VerifyIL("C.F4",
@"{
// Code size 25 (0x19)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.7
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.8
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.s 9
IL_0013: stelem.i4
IL_0014: stloc.0
IL_0015: br.s IL_0017
IL_0017: ldloc.0
IL_0018: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3"))));
diff2.VerifyIL("C.F1",
@"{
// Code size 49 (0x31)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: brtrue.s IL_002c
IL_0016: pop
IL_0017: ldc.i4.3
IL_0018: newarr ""int""
IL_001d: dup
IL_001e: ldc.i4.0
IL_001f: ldc.i4.s 10
IL_0021: stelem.i4
IL_0022: dup
IL_0023: ldc.i4.1
IL_0024: ldc.i4.s 11
IL_0026: stelem.i4
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: ldc.i4.s 12
IL_002b: stelem.i4
IL_002c: stloc.0
IL_002d: br.s IL_002f
IL_002f: ldloc.0
IL_0030: ret
}");
diff2.VerifyIL("C.F3",
@"{
// Code size 27 (0x1b)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.s 13
IL_000b: stelem.i4
IL_000c: dup
IL_000d: ldc.i4.1
IL_000e: ldc.i4.s 14
IL_0010: stelem.i4
IL_0011: dup
IL_0012: ldc.i4.2
IL_0013: ldc.i4.s 15
IL_0015: stelem.i4
IL_0016: stloc.0
IL_0017: br.s IL_0019
IL_0019: ldloc.0
IL_001a: ret
}");
}
/// <summary>
/// Should not generate method for string switch since
/// the CLR only allows adding private members.
/// </summary>
[WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")]
[Fact]
public void PrivateImplementationDetails_ComputeStringHash()
{
var source =
@"class C
{
static int F(string s)
{
switch (s)
{
case ""1"": return 1;
case ""2"": return 2;
case ""3"": return 3;
case ""4"": return 4;
case ""5"": return 5;
case ""6"": return 6;
case ""7"": return 7;
default: return 0;
}
}
}";
const string ComputeStringHashName = "ComputeStringHash";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.F");
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
// Should have generated call to ComputeStringHash and
// added the method to <PrivateImplementationDetails>.
var actualIL0 = methodData0.GetMethodIL();
Assert.True(actualIL0.Contains(ComputeStringHashName));
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Should not have generated call to ComputeStringHash nor
// added the method to <PrivateImplementationDetails>.
var actualIL1 = diff1.GetMethodIL("C.F");
Assert.False(actualIL1.Contains(ComputeStringHashName));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "F");
}
/// <summary>
/// Unique ids should not conflict with ids
/// from previous generation.
/// </summary>
[WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")]
public void UniqueIds()
{
var source0 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
System.Func<int> g = () => 2;
return (b ? f : g)();
}
}";
var source1 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
return f();
}
}";
var source2 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> g = () => 2;
return g();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1])));
diff1.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //f
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__5()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1])));
diff2.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //g
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__7()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
}
/// <summary>
/// Avoid adding references from method bodies
/// other than the changed methods.
/// </summary>
[Fact]
public void ReferencesInIL()
{
var source0 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.WriteLine(2); }
}";
var source1 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.Write(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.G");
var method1 = compilation1.GetMember<MethodSymbol>("C.G");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(
SemanticEditKind.Update,
method0,
method1,
GetEquivalentNodesMap(method1, method0),
preserveLocalVariables: true)));
// "Write" should be included in string table, but "WriteLine" should not.
Assert.True(diff1.MetadataDelta.IsIncluded("Write"));
Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine"));
}
/// <summary>
/// Local slots must be preserved based on signature.
/// </summary>
[Fact]
public void PreserveLocalSlots()
{
var source0 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
A<B> y = F();
object z = F();
M(x);
M(y);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" };
var source1 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
B z = F();
A<B> y = F();
object w = F();
M(w);
M(y);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source2 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source3 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object c = F();
object b = F();
M(c);
M(b);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("B.M");
var methodN = compilation0.GetMember<MethodSymbol>("B.N");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo());
#region Gen1
var method1 = compilation1.GetMember<MethodSymbol>("B.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL(
@"{
// Code size 36 (0x24)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.3
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: call 0x06000002
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: call 0x06000003
IL_001b: nop
IL_001c: ldloc.1
IL_001d: call 0x06000003
IL_0022: nop
IL_0023: ret
}");
diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x24"">
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen2
var method2 = compilation2.GetMember<MethodSymbol>("B.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL(
@"{
// Code size 30 (0x1e)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.s V_5
IL_0008: call 0x06000002
IL_000d: stloc.3
IL_000e: ldloc.s V_5
IL_0010: call 0x06000003
IL_0015: nop
IL_0016: ldloc.3
IL_0017: call 0x06000003
IL_001c: nop
IL_001d: ret
}");
diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1e"">
<local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen3
// Modify different method. (Previous generations
// have not referenced method.)
method2 = compilation2.GetMember<MethodSymbol>("B.N");
var method3 = compilation3.GetMember<MethodSymbol>("B.N");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL(
@"{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.2
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: ldloc.2
IL_000e: call 0x06000003
IL_0013: nop
IL_0014: ldloc.1
IL_0015: call 0x06000003
IL_001a: nop
IL_001b: ret
}");
diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000004"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
}
/// <summary>
/// Preserve locals for method added after initial compilation.
/// </summary>
[Fact]
public void PreserveLocalSlots_NewMethod()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void M()
{
var a = new object();
var b = string.Empty;
}
}";
var source2 =
@"class C
{
static void M()
{
var a = 1;
var b = string.Empty;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 10 (0xa)
.maxstack 1
.locals init ([object] V_0,
string V_1, //b
int V_2) //a
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldsfld ""string string.Empty""
IL_0008: stloc.1
IL_0009: ret
}");
diff2.VerifyPdb(new[] { 0x06000002 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000002"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" />
<entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Local types should be retained, even if the local is no longer
/// used by the method body, since there may be existing
/// references to that slot, in a Watch window for instance.
/// </summary>
[WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")]
[Fact]
public void PreserveLocalTypes()
{
var source0 =
@"class C
{
static void Main()
{
var x = true;
var y = x;
System.Console.WriteLine(y);
}
}";
var source1 =
@"class C
{
static void Main()
{
var x = ""A"";
var y = x;
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
.locals init ([bool] V_0,
[bool] V_1,
string V_2, //x
string V_3) //y
IL_0000: nop
IL_0001: ldstr ""A""
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: stloc.3
IL_0009: ldloc.3
IL_000a: call ""void System.Console.WriteLine(string)""
IL_000f: nop
IL_0010: ret
}");
}
/// <summary>
/// Preserve locals if SemanticEdit.PreserveLocalVariables is set.
/// </summary>
[Fact]
public void PreserveLocalVariablesFlag()
{
var source =
@"class C
{
static System.IDisposable F() { return null; }
static void M()
{
using (F()) { }
using (var x = F()) { }
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1a = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false)));
diff1a.VerifyIL("C.M", @"
{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}
");
var diff1b = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
diff1b.VerifyIL("C.M",
@"{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}");
}
[WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")]
[Fact]
public void ChangeLocalType()
{
var source0 =
@"enum E { }
class C
{
static void M1()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in one method to type added.
var source1 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in another method.
var source2 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in same method.
var source3 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(A);
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M1");
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M2");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M2",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method3 = compilation3.GetMember<MethodSymbol>("C.M2");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL("C.M2",
@"{
// Code size 18 (0x12)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[unchanged] V_2,
A V_3, //x
A V_4, //y
A V_5) //z
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldnull
IL_0007: stloc.s V_5
IL_0009: ldloc.s V_4
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Update()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 1 }</N:0>;
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md1 = diff1.GetMetadata();
AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader }));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
[Fact]
public void AnonymousTypes_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
/// <summary>
/// Reuse existing anonymous types.
/// </summary>
[WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")]
[Fact]
public void AnonymousTypes()
{
var source0 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = x.A;
var z = new { };
}
}
}";
var source1 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = new { A = x.A };
var z = new { };
}
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var m0 = compilation0.GetMember<MethodSymbol>("M.B.M");
var m1 = compilation1.GetMember<MethodSymbol>("M.B.M");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider());
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type
diff1.VerifyIL("M.B.M", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (<>f__AnonymousType1<int, int> V_0, //x
[int] V_1,
<>f__AnonymousType2 V_2, //z
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: ldc.i4.4
IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get""
IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_0014: stloc.3
IL_0015: newobj ""<>f__AnonymousType2..ctor()""
IL_001a: stloc.2
IL_001b: ret
}");
}
/// <summary>
/// Anonymous type names with module ids
/// and gaps in indices.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")]
[WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")]
public void AnonymousTypes_OtherTypeNames()
{
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
// Valid signature, although not sequential index
.class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
.field public !'<B>j__TPar' B
}
// Invalid signature, unexpected type parameter names
.class '<>f__AnonymousType1'<A, B> extends object
{
.field public !A A
.field public !B B
}
// Module id, duplicate index
.class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
}
// Module id
.class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object
{
.field public !'<B>j__TPar' B
}
.class public C extends object
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F()
{
ldnull
ret
}
}";
var source0 =
@"class C
{
static object F()
{
return 0;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 1 };
var y = new { A = x.A };
return y;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
diff1.VerifyIL("C.F",
@"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (<>f__AnonymousType2<object, int> V_0, //x
<>f__AnonymousType3<object> V_1, //y
object V_2)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: ldc.i4.1
IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get""
IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: stloc.2
IL_001b: br.s IL_001d
IL_001d: ldloc.2
IL_001e: ret
}");
}
/// <summary>
/// Update method with anonymous type that was
/// not directly referenced in previous generation.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration()
{
var source0 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x;
}
}");
var source1 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x + 1;
}
}");
var source2 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 2 }</N:2>;
return x.A;
}
}");
var source3 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 3 }</N:2>;
return y.B;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var compilation3 = compilation2.WithSource(source3.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var method0 = compilation0.GetMember<MethodSymbol>("B.G");
var method1 = compilation1.GetMember<MethodSymbol>("B.G");
var method2 = compilation2.GetMember<MethodSymbol>("B.G");
var method3 = compilation3.GetMember<MethodSymbol>("B.G");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types
diff1.VerifyIL("B.G", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (int V_0, //x
[object] V_1,
object V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: add
IL_0006: box ""int""
IL_000b: stloc.2
IL_000c: br.s IL_000e
IL_000e: ldloc.2
IL_000f: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type
diff2.VerifyIL("B.G", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
object V_5)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.2
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.3
IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get""
IL_001a: stloc.s V_5
IL_001c: br.s IL_001e
IL_001e: ldloc.s V_5
IL_0020: ret
}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types
diff3.VerifyIL("B.G", @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
[object] V_5,
object V_6)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.3
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get""
IL_001b: box ""int""
IL_0020: stloc.s V_6
IL_0022: br.s IL_0024
IL_0024: ldloc.s V_6
IL_0026: ret
}");
}
/// <summary>
/// Update another method (without directly referencing
/// anonymous type) after updating method with anonymous type.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration_2()
{
var source0 =
@"class C
{
static object F()
{
var x = new { A = 1 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x + 1;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = new { A = (object)null };
var y = new { A = 'a', B = 'b' };
return x;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch
{
"F" => testData0.GetMethodData("C.F").GetEncDebugInfo(),
"G" => testData0.GetMethodData("C.G").GetEncDebugInfo(),
_ => default,
});
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames()); // no additional types
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true)));
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
CheckNames(readers, reader3.GetTypeDefNames()); // no additional types
}
/// <summary>
/// Local from previous generation is of an anonymous
/// type not available in next generation.
/// </summary>
[Fact]
public void AnonymousTypes_AddThenDelete()
{
var source0 =
@"class C
{
object A;
static object F()
{
var x = new C();
var y = x.A;
return y;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object() };
var y = x.A;
return y;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 2 };
var y = x.A;
y = new { B = new object() }.B;
return y;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 3 };
var y = x.A;
return y;
}
}";
var source4 =
@"class C
{
static object F()
{
var x = new { B = 4, A = new object() };
var y = x.A;
return y;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var compilation4 = compilation3.WithSource(source4);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type
diff1.VerifyIL("C.F", @"
{
// Code size 27 (0x1b)
.maxstack 1
.locals init ([unchanged] V_0,
object V_1, //y
[object] V_2,
<>f__AnonymousType0<object> V_3, //x
object V_4)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get""
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: stloc.s V_4
IL_0016: br.s IL_0018
IL_0018: ldloc.s V_4
IL_001a: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
}
[Fact]
public void AnonymousTypes_DifferentCase()
{
var source0 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { A = 1, B = 2 }</N:0>;
var <N:1>y = new { a = 3, b = 4 }</N:1>;
}
}");
var source1 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { AB = 3 }</N:1>;
}
}");
var source2 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { Ab = 5 }</N:1>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var m0 = compilation0.GetMember<MethodSymbol>("C.M");
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1");
// the first two slots can't be reused since the type changed
diff1.VerifyIL("C.M",
@"{
// Code size 17 (0x11)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.3
IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_000f: stloc.3
IL_0010: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1");
// we can reuse slot for "x", it's type haven't changed
diff2.VerifyIL("C.M",
@"{
// Code size 18 (0x12)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
[unchanged] V_3,
<>f__AnonymousType4<int> V_4) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.5
IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)""
IL_000f: stloc.s V_4
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Nested1()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: ret
}
";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Nested2()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: ret
}
";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Query1()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
<N:3>select new { Value = a, Length = a.Length }</N:3></N:4>;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value</N:8>;
args = args.Concat(newArgs).ToArray();
System.Diagnostics.Debugger.Break();
result.ToString();
}
}
");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null };
for (int i = 0; i < 10; i++)
{
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby a.Length ascending, a descending
<N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>;
var linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
(total, curr) => new { Head = curr.Value, Tail = (dynamic)total });
var str = linked?.Tail?.Head;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value + value</N:8>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1) //newArgs
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>o__0#1: {<>p__0}",
"C: {<>o__0#1, <>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}",
"<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1, //newArgs
<>f__AnonymousType5<dynamic, dynamic> V_2, //list
int V_3, //i
<>f__AnonymousType5<string, dynamic> V_4, //linked
object V_5, //str
<>f__AnonymousType5<string, dynamic> V_6,
object V_7,
bool V_8)
");
}
[Fact]
public void AnonymousTypes_Dynamic1()
{
var template = @"
using System;
class C
{
public void F()
{
var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>;
Console.WriteLine(x.B + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var baselineIL0 = @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}
";
v0.VerifyIL("C.F", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
var baselineIL = @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: ldc.i4.<<VALUE>>
IL_0010: add
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ret
}
";
diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2"));
}
/// <summary>
/// Should not re-use locals if the method metadata
/// signature is unsupported.
/// </summary>
[WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")]
public void LocalType_UnsupportedSignatureContent()
{
// Equivalent to C#, but with extra local and required modifier on
// expected local. Used to generate initial (unsupported) metadata.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method private static object F()
{
ldnull
ret
}
.method private static void M1()
{
.locals init ([0] object other, [1] object modreq(int32) o)
call object C::F()
stloc.1
ldloc.1
call void C::M2(object)
ret
}
.method private static void M2(object o)
{
ret
}
}";
var source =
@"class C
{
static object F()
{
return null;
}
static void M1()
{
object o = F();
M2(o);
}
static void M2(object o)
{
}
}";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 15 (0xf)
.maxstack 1
.locals init (object V_0) //o
IL_0000: nop
IL_0001: call ""object C.F()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""void C.M2(object)""
IL_000d: nop
IL_000e: ret
}");
}
/// <summary>
/// Should not re-use locals with custom modifiers.
/// </summary>
[WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")]
public void LocalType_CustomModifiers()
{
// Equivalent method signature to C#, but
// with optional modifier on locals.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class public C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F(class [mscorlib]System.IDisposable d)
{
.locals init ([0] class C modopt(int32) c,
[1] class [mscorlib]System.IDisposable modopt(object),
[2] bool V_2,
[3] object V_3)
ldnull
ret
}
}";
var source =
@"class C
{
static object F(System.IDisposable d)
{
C c;
using (d)
{
c = (C)d;
}
return c;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
moduleMetadata0,
m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[bool] V_2,
[object] V_3,
C V_4, //c
System.IDisposable V_5,
object V_6)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: stloc.s V_5
.try
{
-IL_0004: nop
-IL_0005: ldarg.0
IL_0006: castclass ""C""
IL_000b: stloc.s V_4
-IL_000d: nop
IL_000e: leave.s IL_001d
}
finally
{
~IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.s V_5
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
IL_001c: endfinally
}
-IL_001d: ldloc.s V_4
IL_001f: stloc.s V_6
IL_0021: br.s IL_0023
-IL_0023: ldloc.s V_6
IL_0025: ret
}", methodToken: diff1.EmitResult.UpdatedMethods.Single());
}
/// <summary>
/// Temporaries for locals used within a single
/// statement should not be preserved.
/// </summary>
[Fact]
public void TemporaryLocals_Other()
{
// Use increment as an example of a compiler generated
// temporary that does not span multiple statements.
var source =
@"class C
{
int P { get; set; }
static int M()
{
var c = new C();
return c.P++;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (C V_0, //c
[int] V_1,
[int] V_2,
int V_3,
int V_4)
IL_0000: nop
IL_0001: newobj ""C..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: dup
IL_0009: callvirt ""int C.P.get""
IL_000e: stloc.3
IL_000f: ldloc.3
IL_0010: ldc.i4.1
IL_0011: add
IL_0012: callvirt ""void C.P.set""
IL_0017: nop
IL_0018: ldloc.3
IL_0019: stloc.s V_4
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_4
IL_001f: ret
}");
}
/// <summary>
/// Local names array (from PDB) may have fewer slots than method
/// signature (from metadata) when the trailing slots are unnamed.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270()
{
var source =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
testData0.GetMethodData("C.M").VerifyIL(@"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
}
/// <summary>
/// Similar to above test but with no named locals in original.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270_NoNamedLocals()
{
// Equivalent to C#, but with unnamed locals.
// Used to generate initial metadata.
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
.assembly '<<GeneratedFileName>>' { }
.class C extends object
{
.method private static class [netstandard]System.IDisposable F()
{
ldnull
ret
}
.method private static void M()
{
.locals init ([0] object, [1] object)
ret
}
}";
var source0 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
}
}";
var source1 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init ([object] V_0,
[object] V_1,
System.IDisposable V_2) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.2
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.2
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.2
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}
");
}
[Fact]
public void TemporaryLocals_ReferencedType()
{
var source =
@"class C
{
static object F()
{
return null;
}
static void M()
{
var x = new System.Collections.Generic.HashSet<int>();
x.Add(1);
}
}";
var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var modMeta = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
modMeta,
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (System.Collections.Generic.HashSet<int> V_0) //x
IL_0000: nop
IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)""
IL_000e: pop
IL_000f: ret
}
");
}
[WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")]
[WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")]
[Fact]
public void DynamicOperations()
{
var source =
@"class A
{
static object F = null;
object x = ((dynamic)F) + 1;
static A()
{
((dynamic)F).F();
}
A() { }
static void M(object o)
{
((dynamic)o).x = 1;
}
static void N(A o)
{
o.x = 1;
}
}
class B
{
static object F = null;
static object G = ((dynamic)F).F();
object x = ((dynamic)F) + 1;
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef });
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
// Source method with dynamic operations.
var methodData0 = testData0.GetMethodData("A.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("A.M");
var method1 = compilation1.GetMember<MethodSymbol>("A.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Source method with no dynamic operations.
methodData0 = testData0.GetMethodData("A.N");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A.N");
method1 = compilation1.GetMember<MethodSymbol>("A.N");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..ctor");
method1 = compilation1.GetMember<MethodSymbol>("A..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..cctor");
method1 = compilation1.GetMember<MethodSymbol>("A..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..ctor");
method1 = compilation1.GetMember<MethodSymbol>("B..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..cctor");
method1 = compilation1.GetMember<MethodSymbol>("B..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void DynamicLocals()
{
var template = @"
using System;
class C
{
public void F()
{
dynamic <N:0>x = 1</N:0>;
Console.WriteLine((int)x + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 82 (0x52)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: call ""void System.Console.WriteLine(int)""
IL_0050: nop
IL_0051: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1}",
"C.<>o__0#1: {<>p__0}");
diff1.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.1
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <>o__0#1}",
"C.<>o__0#1: {<>p__0}",
"C.<>o__0#2: {<>p__0}");
diff2.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.2
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
}
[Fact]
public void ExceptionFilters()
{
var source0 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
}
}
");
var source1 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
Console.WriteLine(1);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 90 (0x5a)
.maxstack 2
.locals init (System.IO.IOException V_0, //e
bool V_1,
System.Exception V_2, //e
bool V_3)
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: newobj ""System.InvalidOperationException..ctor()""
IL_0007: throw
}
filter
{
IL_0008: isinst ""System.IO.IOException""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0020
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: call ""bool C.G(System.Exception)""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldc.i4.0
IL_001e: cgt.un
IL_0020: endfilter
} // end filter
{ // handler
IL_0022: pop
IL_0023: nop
IL_0024: call ""void System.Console.WriteLine()""
IL_0029: nop
IL_002a: nop
IL_002b: leave.s IL_0052
}
filter
{
IL_002d: isinst ""System.Exception""
IL_0032: dup
IL_0033: brtrue.s IL_0039
IL_0035: pop
IL_0036: ldc.i4.0
IL_0037: br.s IL_0045
IL_0039: stloc.2
IL_003a: ldloc.2
IL_003b: call ""bool C.G(System.Exception)""
IL_0040: stloc.3
IL_0041: ldloc.3
IL_0042: ldc.i4.0
IL_0043: cgt.un
IL_0045: endfilter
} // end filter
{ // handler
IL_0047: pop
IL_0048: nop
IL_0049: call ""void System.Console.WriteLine()""
IL_004e: nop
IL_004f: nop
IL_0050: leave.s IL_0052
}
IL_0052: ldc.i4.1
IL_0053: call ""void System.Console.WriteLine(int)""
IL_0058: nop
IL_0059: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void MethodSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(2);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
[WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void LocalSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(null);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(x);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,16): warning CS0219: The variable 'y' is assigned but its value is never used
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"),
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
/// <summary>
/// Disallow edits that require NoPIA references.
/// </summary>
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIAReferences()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")]
public interface IA
{
void M();
int P { get; }
event Action E;
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")]
public interface IB
{
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")]
public interface IC
{
}
public struct S
{
public object F;
}";
var source0 =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
var o = default(IA);
o.M();
M2(o.P);
o.E += M1;
M2(C<IA>.F);
M2(new S());
}
static void M2(object o)
{
}
}";
var source1A = source0;
var source1B =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
M2(null);
}
static void M2(object o)
{
}
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1A = compilation0.WithSource(source1A);
var compilation1B = compilation0.WithSource(source1B);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var method1B = compilation1B.GetMember<MethodSymbol>("C.M1");
var method1A = compilation1A.GetMember<MethodSymbol>("C.M1");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C<T>.M1");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
// Disallow edits that require NoPIA references.
var diff1A = compilation1A.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true)));
diff1A.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA"));
// Allow edits that do not require NoPIA references,
// even if the previous code included references.
var diff1B = compilation1B.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true)));
diff1B.VerifyIL("C<T>.M1",
@"{
// Code size 9 (0x9)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1)
IL_0000: nop
IL_0001: ldnull
IL_0002: call ""void C<T>.M2(object)""
IL_0007: nop
IL_0008: ret
}");
using var md1 = diff1B.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
}
[WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIATypeInNamespace()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")]
namespace N
{
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")]
public interface IA
{
}
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")]
public interface IB
{
}";
var source =
@"class C<T>
{
static void M(object o)
{
M(C<N.IA>.E.X);
M(C<IB>.E.X);
}
enum E { X }
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB"));
diff1.VerifyIL("C<T>.M",
@"{
// Code size 26 (0x1a)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: box ""C<N.IA>.E""
IL_0007: call ""void C<T>.M(object)""
IL_000c: nop
IL_000d: ldc.i4.0
IL_000e: box ""C<IB>.E""
IL_0013: call ""void C<T>.M(object)""
IL_0018: nop
IL_0019: ret
}");
}
/// <summary>
/// Should use TypeDef rather than TypeRef for unrecognized
/// local of a type defined in the original assembly.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfTypeFromAssembly()
{
var source =
@"class E : System.Exception
{
}
class C
{
static void M()
{
try
{
}
catch (E e)
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeRefNames(), "Object");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (E V_0) //e
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_000a
}
catch E
{
IL_0005: stloc.0
IL_0006: nop
IL_0007: nop
IL_0008: leave.s IL_000a
}
IL_000a: ret
}");
}
/// <summary>
/// Similar to above test but with anonymous type
/// added in subsequent generation.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfAnonymousTypeFromAssembly()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source2 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
return null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var method1G = compilation1.GetMember<MethodSymbol>("C.G");
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var method2G = compilation2.GetMember<MethodSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
// Use empty LocalVariableNameProvider for original locals and
// use preserveLocalVariables: true for the edit so that existing
// locals are retained even though all are unrecognized.
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1");
CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider");
// Change method updated in generation 1.
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetTypeRefNames(), "Object");
// Change method unchanged since generation 0.
var diff2G = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true)));
}
[Fact]
public void BrokenOutputStreams()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
badStream,
ilStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
badStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[Fact]
public void BrokenPortablePdbStream()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb));
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void Main() { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))),
testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
diff1.EmitResult.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(diff1.EmitResult.Success);
}
[WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")]
[Fact]
public void BlobContainsInvalidValues()
{
var source0 =
@"class C
{
static void F()
{
string goo = ""abc"";
}
}";
var source1 =
@"class C
{
static void F()
{
float goo = 10;
}
}";
var source2 =
@"class C
{
static void F()
{
bool goo = true;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
var handle = MetadataTokens.BlobHandle(1);
byte[] value0 = reader0.GetBlobBytes(handle);
Assert.Equal("20-01-01-08", BitConverter.ToString(value0));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
byte[] value1 = reader1.GetBlobBytes(handle);
Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
byte[] value2 = reader2.GetBlobBytes(handle);
Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly1()
{
var sourceA0 = @"
public class A
{
}
";
var sourceA1 = @"
public class A
{
public void M() { System.Console.WriteLine(1);}
}
public class X {}
";
var sourceB0 = @"
public class B
{
public static void F() { }
}";
var sourceB1 = @"
public class B
{
public static void F() { new A().M(); }
}
public class Y : X { }
";
var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA");
var compilationA1 = compilationA0.WithSource(sourceA1);
var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var bytesA0 = compilationA0.EmitToArray();
var bytesB0 = compilationB0.EmitToArray();
var mdA0 = ModuleMetadata.CreateFromImage(bytesA0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider);
var mA1 = compilationA1.GetMember<MethodSymbol>("A.M");
var mX1 = compilationA1.GetMember<TypeSymbol>("X");
var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() };
var diffA1 = compilationA1.EmitDifference(
generationA0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, mA1),
SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)),
allAddedSymbols);
diffA1.EmitResult.Diagnostics.Verify();
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))),
allAddedSymbols);
diffB1.EmitResult.Diagnostics.Verify(
// (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public class X {}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14),
// (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public void M() { System.Console.WriteLine(1);}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly2()
{
var sourceA = @"
public class A
{
public void M() { }
}";
var sourceB0 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var sourceB1 = @"
public class B
{
public static void F() { var a = new A(); a.M(); }
}";
var sourceB2 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA");
var aRef = compilationA.ToMetadataReference();
var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB");
var compilationB1 = compilationB0.WithSource(sourceB1);
var compilationB2 = compilationB1.WithSource(sourceB2);
var testDataB0 = new CompilationTestData();
var bytesB0 = compilationB0.EmitToArray(testData: testDataB0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider());
var f0 = compilationB0.GetMember<MethodSymbol>("B.F");
var f1 = compilationB1.GetMember<MethodSymbol>("B.F");
var f2 = compilationB2.GetMember<MethodSymbol>("B.F");
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
diffB1.VerifyIL("B.F", @"
{
// Code size 15 (0xf)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: callvirt ""void A.M()""
IL_000d: nop
IL_000e: ret
}
");
var diffB2 = compilationB2.EmitDifference(
diffB1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true)));
diffB2.VerifyIL("B.F", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void UniqueSynthesizedNames_DynamicSiteContainer()
{
var source0 = @"
public class C
{
public static void F(dynamic d) { d.Goo(); }
}";
var source1 = @"
public class C
{
public static void F(dynamic d) { d.Bar(); }
}";
var source2 = @"
public class C
{
public static void F(dynamic d, byte b) { d.Bar(); }
public static void F(dynamic d) { d.Bar(); }
}";
var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp,
options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
diff2.EmitResult.Diagnostics.Verify();
var reader0 = md0.MetadataReader;
var reader1 = diff1.GetMetadata().Reader;
var reader2 = diff2.GetMetadata().Reader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0");
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2");
}
[WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")]
[Fact]
public void ManyGenerations()
{
var source =
@"class C
{{
static int F() {{ return {0}; }}
}}";
var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll);
var bytes0 = compilation0.EmitToArray();
var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
for (int i = 2; i <= 50; i++)
{
var compilation1 = compilation0.WithSource(String.Format(source, i));
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
compilation0 = compilation1;
method0 = method1;
generation0 = diff1.NextGeneration;
}
}
[WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")]
[Fact]
public void PdbReadingErrors()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle =>
{
throw new InvalidDataException("Bad PDB!");
});
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''.
Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14));
}
[Fact]
public void PdbReadingErrors_PassThruExceptions()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle =>
{
throw new ArgumentOutOfRangeException();
});
// the compiler should't swallow any exceptions but InvalidDataException
Assert.Throws<ArgumentOutOfRangeException>(() =>
compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))));
}
[Fact]
public void PatternVariable_TypeChange()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3, //i
bool V_4,
int V_5)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""bool""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""bool""
IL_000f: stloc.3
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.s V_4
IL_0016: ldloc.s V_4
IL_0018: brfalse.s IL_0026
IL_001a: nop
IL_001b: ldloc.3
IL_001c: brtrue.s IL_0021
IL_001e: ldc.i4.0
IL_001f: br.s IL_0022
IL_0021: ldc.i4.1
IL_0022: stloc.s V_5
IL_0024: br.s IL_002b
IL_0026: ldc.i4.0
IL_0027: stloc.s V_5
IL_0029: br.s IL_002b
IL_002b: ldloc.s V_5
IL_002d: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[bool] V_4,
[int] V_5,
int V_6, //j
bool V_7,
int V_8)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_6
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_7
IL_0017: ldloc.s V_7
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_6
IL_001e: stloc.s V_8
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_8
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_8
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_DeleteInsert()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int) { return 1; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3,
int V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: brfalse.s IL_0014
IL_000e: nop
IL_000f: ldc.i4.1
IL_0010: stloc.s V_4
IL_0012: br.s IL_0019
IL_0014: ldc.i4.0
IL_0015: stloc.s V_4
IL_0017: br.s IL_0019
IL_0019: ldloc.s V_4
IL_001b: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[int] V_4,
int V_5, //i
bool V_6,
int V_7)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_5
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_6
IL_0017: ldloc.s V_6
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_5
IL_001e: stloc.s V_7
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_7
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_7
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(bool x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; }
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { }
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.1
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.1
IL_0015: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 15 (0xf)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: call ""Base..ctor(bool)""
IL_000c: nop
IL_000d: nop
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.2
IL_0015: ret
}
");
}
[Fact]
public void PatternVariable_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>;
}");
var source1 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.1
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: stfld ""bool C.field""
IL_0010: ldarg.0
IL_0011: call ""object..ctor()""
IL_0016: nop
IL_0017: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.2
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void PatternVariable_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.1
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 7 (0x7)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ceq
IL_0006: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.2
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
}
[Fact]
public void Tuple_Parenthesized()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)""
IL_0010: ldloc.0
IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1""
IL_0016: ldloc.0
IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0021: add
IL_0022: ldloc.0
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_002d: add
IL_002e: stloc.1
IL_002f: br.s IL_0031
IL_0031: ldloc.1
IL_0032: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init ([unchanged] V_0,
[int] V_1,
System.ValueTuple<int, int, int> V_2, //x
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_2
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)""
IL_000b: ldloc.2
IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1""
IL_0011: ldloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2""
IL_0017: add
IL_0018: ldloc.2
IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3""
IL_001e: add
IL_001f: stloc.3
IL_0020: br.s IL_0022
IL_0022: ldloc.3
IL_0023: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init ([unchanged] V_0,
[int] V_1,
[unchanged] V_2,
[int] V_3,
System.ValueTuple<int, int> V_4, //x
int V_5)
IL_0000: nop
IL_0001: ldloca.s V_4
IL_0003: ldc.i4.1
IL_0004: ldc.i4.3
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.s V_4
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: ldloc.s V_4
IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0018: add
IL_0019: stloc.s V_5
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_5
IL_001f: ret
}
");
}
[Fact]
public void Tuple_Decomposition()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2, //z
int V_3)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldc.i4.3
IL_0006: stloc.2
IL_0007: ldloc.0
IL_0008: ldloc.1
IL_0009: add
IL_000a: ldloc.2
IL_000b: add
IL_000c: stloc.3
IL_000d: br.s IL_000f
IL_000f: ldloc.3
IL_0010: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.3
IL_0004: stloc.2
IL_0005: ldloc.0
IL_0006: ldloc.2
IL_0007: add
IL_0008: stloc.s V_4
IL_000a: br.s IL_000c
IL_000c: ldloc.s V_4
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
[int] V_4,
int V_5, //y
int V_6)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.s V_5
IL_0006: ldc.i4.3
IL_0007: stloc.2
IL_0008: ldloc.0
IL_0009: ldloc.s V_5
IL_000b: add
IL_000c: ldloc.2
IL_000d: add
IL_000e: stloc.s V_6
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_6
IL_0014: ret
}
");
}
[Fact]
public void ForeachStatement()
{
var source0 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x);
}
}
}");
var source1 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var source2 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //x
bool V_3, //y
double V_4, //z
System.ValueTuple<bool, double> V_5)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.0
IL_0008: ldc.i4.0
IL_0009: stloc.1
IL_000a: br.s IL_003f
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0013: dup
IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0019: stloc.s V_5
IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0020: stloc.2
IL_0021: ldloc.s V_5
IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_0028: stloc.3
IL_0029: ldloc.s V_5
IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0030: stloc.s V_4
IL_0032: nop
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
IL_003a: nop
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
IL_0045: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.G", @"
{
// Code size 78 (0x4e)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
bool V_3, //y
double V_4, //z
[unchanged] V_5,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6,
int V_7,
System.ValueTuple<bool, double> V_8)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_6
IL_0009: ldc.i4.0
IL_000a: stloc.s V_7
IL_000c: br.s IL_0045
IL_000e: ldloc.s V_6
IL_0010: ldloc.s V_7
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_001d: stloc.s V_8
IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0024: stloc.2
IL_0025: ldloc.s V_8
IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_002c: stloc.3
IL_002d: ldloc.s V_8
IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0034: stloc.s V_4
IL_0036: nop
IL_0037: ldloc.2
IL_0038: call ""void System.Console.WriteLine(int)""
IL_003d: nop
IL_003e: nop
IL_003f: ldloc.s V_7
IL_0041: ldc.i4.1
IL_0042: add
IL_0043: stloc.s V_7
IL_0045: ldloc.s V_7
IL_0047: ldloc.s V_6
IL_0049: ldlen
IL_004a: conv.i4
IL_004b: blt.s IL_000e
IL_004d: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 61 (0x3d)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
[bool] V_3,
[unchanged] V_4,
[unchanged] V_5,
[unchanged] V_6,
[int] V_7,
[unchanged] V_8,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9,
int V_10,
System.ValueTuple<bool, double> V_11) //yz
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_9
IL_0009: ldc.i4.0
IL_000a: stloc.s V_10
IL_000c: br.s IL_0034
IL_000e: ldloc.s V_9
IL_0010: ldloc.s V_10
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_001d: stloc.2
IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0023: stloc.s V_11
IL_0025: nop
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
IL_002d: nop
IL_002e: ldloc.s V_10
IL_0030: ldc.i4.1
IL_0031: add
IL_0032: stloc.s V_10
IL_0034: ldloc.s V_10
IL_0036: ldloc.s V_9
IL_0038: ldlen
IL_0039: conv.i4
IL_003a: blt.s IL_000e
IL_003c: ret
}
");
}
[Fact]
public void OutVar()
{
var source0 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; }
}");
var source1 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.2
IL_000f: br.s IL_0011
IL_0011: ldloc.2
IL_0012: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //z
[int] V_2,
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.3
IL_000f: br.s IL_0011
IL_0011: ldloc.3
IL_0012: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
[int] V_2,
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.s V_4
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_4
IL_0014: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); }
static int M(out int x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x) { }
static int M(out int x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.1
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 18 (0x12)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: call ""Base..ctor(int)""
IL_000f: nop
IL_0010: nop
IL_0011: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.2
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer_WithLambda()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InMethodBody_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method");
var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method");
var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.1
IL_0025: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff1.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
int V_2) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.2
IL_0025: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff2.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
[int] V_2,
int V_3) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.3
IL_0025: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>);
static int M(out int x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x;
static int M(out int x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 23 (0x17)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: stfld ""int C.field""
IL_000f: ldarg.0
IL_0010: call ""object..ctor()""
IL_0015: nop
IL_0016: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_1
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_2
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
}
[Fact]
public void OutVar_InQuery_WithLambda()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InSwitchExpression()
{
var source0 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i switch
{
0 => 0,
_ => 1
};
}
static object N(out int x) { x = 1; return null; }
}");
var source1 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i + N(out var x) switch
{
0 => 0,
_ => 1
};
}
static int N(out int x) { x = 1; return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.G");
var n1 = compilation1.GetMember<MethodSymbol>("Program.G");
var n2 = compilation2.GetMember<MethodSymbol>("Program.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.G(int)", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init (int V_0,
object V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000e
IL_000a: ldc.i4.0
IL_000b: stloc.0
IL_000c: br.s IL_0012
IL_000e: ldc.i4.1
IL_000f: stloc.0
IL_0010: br.s IL_0012
IL_0012: ldc.i4.1
IL_0013: brtrue.s IL_0016
IL_0015: nop
IL_0016: ldloc.0
IL_0017: box ""int""
IL_001c: stloc.1
IL_001d: br.s IL_001f
IL_001f: ldloc.1
IL_0020: ret
}
");
v0.VerifyIL("Program.N(out int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (object V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.1
IL_0003: stind.i4
IL_0004: ldnull
IL_0005: stloc.0
IL_0006: br.s IL_0008
IL_0008: ldloc.0
IL_0009: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers();
diff1.VerifyIL("Program.G(int)", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init ([int] V_0,
[object] V_1,
int V_2, //x
int V_3,
int V_4,
int V_5,
object V_6)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloca.s V_2
IL_0005: call ""int Program.N(out int)""
IL_000a: stloc.s V_5
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
IL_000f: nop
IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_0016
IL_0014: br.s IL_001b
IL_0016: ldc.i4.0
IL_0017: stloc.s V_4
IL_0019: br.s IL_0020
IL_001b: ldc.i4.1
IL_001c: stloc.s V_4
IL_001e: br.s IL_0020
IL_0020: ldc.i4.1
IL_0021: brtrue.s IL_0024
IL_0023: nop
IL_0024: ldloc.3
IL_0025: ldloc.s V_4
IL_0027: add
IL_0028: box ""int""
IL_002d: stloc.s V_6
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_6
IL_0033: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers();
diff2.VerifyIL("Program.G(int)", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[int] V_2,
[int] V_3,
[int] V_4,
[int] V_5,
[object] V_6,
int V_7,
object V_8)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000f
IL_000a: ldc.i4.0
IL_000b: stloc.s V_7
IL_000d: br.s IL_0014
IL_000f: ldc.i4.1
IL_0010: stloc.s V_7
IL_0012: br.s IL_0014
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
IL_0017: nop
IL_0018: ldloc.s V_7
IL_001a: box ""int""
IL_001f: stloc.s V_8
IL_0021: br.s IL_0023
IL_0023: ldloc.s V_8
IL_0025: ret
}
");
}
[Fact]
public void AddUsing_AmbiguousCode()
{
var source0 = MarkedSource(@"
using System.Threading;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
}");
var source1 = MarkedSource(@"
using System.Threading;
using System.Timers;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
static void G()
{
System.Console.WriteLine(new TimersDescriptionAttribute(""""));
}
}");
var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Pretend there was an update to C.E to ensure we haven't invalidated the test
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer'
// var t = new Timer(s => System.Console.WriteLine(s));
Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21));
// Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff.EmitResult.Diagnostics.Verify();
diff.VerifyIL(@"C.G", @"
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldstr """"
IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)""
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void Records_AddWellKnownMember()
{
var source0 =
@"
#nullable enable
namespace N
{
record R(int X)
{
}
}
";
var source1 =
@"
#nullable enable
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
// Verify full metadata contains expected rows.
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R");
CheckNames(reader0, reader0.GetMethodDefNames(),
/* EmbeddedAttribute */".ctor",
/* NullableAttribute */ ".ctor",
/* NullableContextAttribute */".ctor",
/* IsExternalInit */".ctor",
/* R: */
".ctor",
"get_EqualityContract",
"get_X",
"set_X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), // R.PrintMembers
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(10, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Records_RemoveWellKnownMember()
{
var source0 =
@"
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var source1 =
@"
namespace N
{
record R(int X)
{
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
}
[Fact]
public void TopLevelStatement_Update()
{
var source0 = @"
using System;
Console.WriteLine(""Hello"");
";
var source1 = @"
using System;
Console.WriteLine(""Hello World"");
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("<Program>$.<Main>$");
var method1 = compilation1.GetMember<MethodSymbol>("<Program>$.<Main>$");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<Program>$");
CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$");
CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
}
}
| 1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/Core/Portable/Emit/EditAndContinue/DeltaMetadataWriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit
{
internal sealed class DeltaMetadataWriter : MetadataWriter
{
private readonly EmitBaseline _previousGeneration;
private readonly Guid _encId;
private readonly DefinitionMap _definitionMap;
private readonly SymbolChanges _changes;
/// <summary>
/// Type definitions containing any changes (includes added types).
/// </summary>
private readonly List<ITypeDefinition> _changedTypeDefs;
private readonly DefinitionIndex<ITypeDefinition> _typeDefs;
private readonly DefinitionIndex<IEventDefinition> _eventDefs;
private readonly DefinitionIndex<IFieldDefinition> _fieldDefs;
private readonly DefinitionIndex<IMethodDefinition> _methodDefs;
private readonly DefinitionIndex<IPropertyDefinition> _propertyDefs;
private readonly DefinitionIndex<IParameterDefinition> _parameterDefs;
private readonly Dictionary<IParameterDefinition, IMethodDefinition> _parameterDefList;
private readonly GenericParameterIndex _genericParameters;
private readonly EventOrPropertyMapIndex _eventMap;
private readonly EventOrPropertyMapIndex _propertyMap;
private readonly MethodImplIndex _methodImpls;
// For the EncLog table we need to know which things we're emitting custom attributes for so we can
// correctly map the attributes to row numbers of existing attributes for that target
private readonly Dictionary<EntityHandle, int> _customAttributeParentCounts;
// Keep track of which CustomAttributes rows are added in this and previous deltas, over what is in the
// original metadata
private readonly Dictionary<EntityHandle, ImmutableArray<int>> _customAttributesAdded;
private readonly Dictionary<IParameterDefinition, int> _existingParameterDefs;
private readonly Dictionary<MethodDefinitionHandle, int> _firstParamRowMap;
private readonly HeapOrReferenceIndex<AssemblyIdentity> _assemblyRefIndex;
private readonly HeapOrReferenceIndex<string> _moduleRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeMemberReference> _memberRefIndex;
private readonly InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference> _methodSpecIndex;
private readonly TypeReferenceIndex _typeRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeReference> _typeSpecIndex;
private readonly HeapOrReferenceIndex<BlobHandle> _standAloneSignatureIndex;
private readonly Dictionary<IMethodDefinition, AddedOrChangedMethodInfo> _addedOrChangedMethods;
public DeltaMetadataWriter(
EmitContext context,
CommonMessageProvider messageProvider,
EmitBaseline previousGeneration,
Guid encId,
DefinitionMap definitionMap,
SymbolChanges changes,
CancellationToken cancellationToken)
: base(metadata: MakeTablesBuilder(previousGeneration),
debugMetadataOpt: (context.Module.DebugInformationFormat == DebugInformationFormat.PortablePdb) ? new MetadataBuilder() : null,
dynamicAnalysisDataWriterOpt: null,
context: context,
messageProvider: messageProvider,
metadataOnly: false,
deterministic: false,
emitTestCoverageData: false,
cancellationToken: cancellationToken)
{
Debug.Assert(previousGeneration != null);
Debug.Assert(encId != default(Guid));
Debug.Assert(encId != previousGeneration.EncId);
Debug.Assert(context.Module.DebugInformationFormat != DebugInformationFormat.Embedded);
_previousGeneration = previousGeneration;
_encId = encId;
_definitionMap = definitionMap;
_changes = changes;
var sizes = previousGeneration.TableSizes;
_changedTypeDefs = new List<ITypeDefinition>();
_typeDefs = new DefinitionIndex<ITypeDefinition>(this.TryGetExistingTypeDefIndex, sizes[(int)TableIndex.TypeDef]);
_eventDefs = new DefinitionIndex<IEventDefinition>(this.TryGetExistingEventDefIndex, sizes[(int)TableIndex.Event]);
_fieldDefs = new DefinitionIndex<IFieldDefinition>(this.TryGetExistingFieldDefIndex, sizes[(int)TableIndex.Field]);
_methodDefs = new DefinitionIndex<IMethodDefinition>(this.TryGetExistingMethodDefIndex, sizes[(int)TableIndex.MethodDef]);
_propertyDefs = new DefinitionIndex<IPropertyDefinition>(this.TryGetExistingPropertyDefIndex, sizes[(int)TableIndex.Property]);
_parameterDefs = new DefinitionIndex<IParameterDefinition>(this.TryGetExistingParameterDefIndex, sizes[(int)TableIndex.Param]);
_parameterDefList = new Dictionary<IParameterDefinition, IMethodDefinition>(Cci.SymbolEquivalentEqualityComparer.Instance);
_genericParameters = new GenericParameterIndex(sizes[(int)TableIndex.GenericParam]);
_eventMap = new EventOrPropertyMapIndex(this.TryGetExistingEventMapIndex, sizes[(int)TableIndex.EventMap]);
_propertyMap = new EventOrPropertyMapIndex(this.TryGetExistingPropertyMapIndex, sizes[(int)TableIndex.PropertyMap]);
_methodImpls = new MethodImplIndex(this, sizes[(int)TableIndex.MethodImpl]);
_customAttributeParentCounts = new Dictionary<EntityHandle, int>();
_customAttributesAdded = new Dictionary<EntityHandle, ImmutableArray<int>>();
_firstParamRowMap = new Dictionary<MethodDefinitionHandle, int>();
_existingParameterDefs = new Dictionary<IParameterDefinition, int>(ReferenceEqualityComparer.Instance);
_assemblyRefIndex = new HeapOrReferenceIndex<AssemblyIdentity>(this, lastRowId: sizes[(int)TableIndex.AssemblyRef]);
_moduleRefIndex = new HeapOrReferenceIndex<string>(this, lastRowId: sizes[(int)TableIndex.ModuleRef]);
_memberRefIndex = new InstanceAndStructuralReferenceIndex<ITypeMemberReference>(this, new MemberRefComparer(this), lastRowId: sizes[(int)TableIndex.MemberRef]);
_methodSpecIndex = new InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference>(this, new MethodSpecComparer(this), lastRowId: sizes[(int)TableIndex.MethodSpec]);
_typeRefIndex = new TypeReferenceIndex(this, lastRowId: sizes[(int)TableIndex.TypeRef]);
_typeSpecIndex = new InstanceAndStructuralReferenceIndex<ITypeReference>(this, new TypeSpecComparer(this), lastRowId: sizes[(int)TableIndex.TypeSpec]);
_standAloneSignatureIndex = new HeapOrReferenceIndex<BlobHandle>(this, lastRowId: sizes[(int)TableIndex.StandAloneSig]);
_addedOrChangedMethods = new Dictionary<IMethodDefinition, AddedOrChangedMethodInfo>(Cci.SymbolEquivalentEqualityComparer.Instance);
}
private static MetadataBuilder MakeTablesBuilder(EmitBaseline previousGeneration)
{
return new MetadataBuilder(
previousGeneration.UserStringStreamLength,
previousGeneration.StringStreamLength,
previousGeneration.BlobStreamLength,
previousGeneration.GuidStreamLength);
}
private ImmutableArray<int> GetDeltaTableSizes(ImmutableArray<int> rowCounts)
{
var sizes = new int[MetadataTokens.TableCount];
rowCounts.CopyTo(sizes);
sizes[(int)TableIndex.TypeRef] = _typeRefIndex.Rows.Count;
sizes[(int)TableIndex.TypeDef] = _typeDefs.GetAdded().Count;
sizes[(int)TableIndex.Field] = _fieldDefs.GetAdded().Count;
sizes[(int)TableIndex.MethodDef] = _methodDefs.GetAdded().Count;
sizes[(int)TableIndex.Param] = _parameterDefs.GetAdded().Count;
sizes[(int)TableIndex.MemberRef] = _memberRefIndex.Rows.Count;
sizes[(int)TableIndex.StandAloneSig] = _standAloneSignatureIndex.Rows.Count;
sizes[(int)TableIndex.EventMap] = _eventMap.GetAdded().Count;
sizes[(int)TableIndex.Event] = _eventDefs.GetAdded().Count;
sizes[(int)TableIndex.PropertyMap] = _propertyMap.GetAdded().Count;
sizes[(int)TableIndex.Property] = _propertyDefs.GetAdded().Count;
sizes[(int)TableIndex.MethodImpl] = _methodImpls.GetAdded().Count;
sizes[(int)TableIndex.ModuleRef] = _moduleRefIndex.Rows.Count;
sizes[(int)TableIndex.TypeSpec] = _typeSpecIndex.Rows.Count;
sizes[(int)TableIndex.AssemblyRef] = _assemblyRefIndex.Rows.Count;
sizes[(int)TableIndex.GenericParam] = _genericParameters.GetAdded().Count;
sizes[(int)TableIndex.MethodSpec] = _methodSpecIndex.Rows.Count;
return ImmutableArray.Create(sizes);
}
internal EmitBaseline GetDelta(Compilation compilation, Guid encId, MetadataSizes metadataSizes)
{
var addedOrChangedMethodsByIndex = new Dictionary<int, AddedOrChangedMethodInfo>();
foreach (var pair in _addedOrChangedMethods)
{
addedOrChangedMethodsByIndex.Add(MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(pair.Key)), pair.Value);
}
var previousTableSizes = _previousGeneration.TableEntriesAdded;
var deltaTableSizes = GetDeltaTableSizes(metadataSizes.RowCounts);
var tableSizes = new int[MetadataTokens.TableCount];
for (int i = 0; i < tableSizes.Length; i++)
{
tableSizes[i] = previousTableSizes[i] + deltaTableSizes[i];
}
// If the previous generation is 0 (metadata) get the synthesized members from the current compilation's builder,
// otherwise members from the current compilation have already been merged into the baseline.
var synthesizedMembers = (_previousGeneration.Ordinal == 0) ? module.GetAllSynthesizedMembers() : _previousGeneration.SynthesizedMembers;
var currentGenerationOrdinal = _previousGeneration.Ordinal + 1;
var addedTypes = _typeDefs.GetAdded();
var generationOrdinals = CreateDictionary(_previousGeneration.GenerationOrdinals, SymbolEquivalentEqualityComparer.Instance);
foreach (var (addedType, _) in addedTypes)
{
if (_changes.IsReplaced(addedType))
{
generationOrdinals[addedType] = currentGenerationOrdinal;
}
}
return _previousGeneration.With(
compilation,
module,
currentGenerationOrdinal,
encId,
generationOrdinals,
typesAdded: AddRange(_previousGeneration.TypesAdded, addedTypes, comparer: SymbolEquivalentEqualityComparer.Instance),
eventsAdded: AddRange(_previousGeneration.EventsAdded, _eventDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
fieldsAdded: AddRange(_previousGeneration.FieldsAdded, _fieldDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
methodsAdded: AddRange(_previousGeneration.MethodsAdded, _methodDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
firstParamRowMap: AddRange(_previousGeneration.FirstParamRowMap, _firstParamRowMap),
propertiesAdded: AddRange(_previousGeneration.PropertiesAdded, _propertyDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
eventMapAdded: AddRange(_previousGeneration.EventMapAdded, _eventMap.GetAdded()),
propertyMapAdded: AddRange(_previousGeneration.PropertyMapAdded, _propertyMap.GetAdded()),
methodImplsAdded: AddRange(_previousGeneration.MethodImplsAdded, _methodImpls.GetAdded()),
customAttributesAdded: AddRange(_previousGeneration.CustomAttributesAdded, _customAttributesAdded),
tableEntriesAdded: ImmutableArray.Create(tableSizes),
// Blob stream is concatenated aligned.
blobStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.Blob) + _previousGeneration.BlobStreamLengthAdded,
// String stream is concatenated unaligned.
stringStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.String] + _previousGeneration.StringStreamLengthAdded,
// UserString stream is concatenated aligned.
userStringStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.UserString) + _previousGeneration.UserStringStreamLengthAdded,
// Guid stream accumulates on the GUID heap unlike other heaps, so the previous generations are already included.
guidStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.Guid],
anonymousTypeMap: ((IPEDeltaAssemblyBuilder)module).GetAnonymousTypeMap(),
synthesizedMembers: synthesizedMembers,
addedOrChangedMethods: AddRange(_previousGeneration.AddedOrChangedMethods, addedOrChangedMethodsByIndex),
debugInformationProvider: _previousGeneration.DebugInformationProvider,
localSignatureProvider: _previousGeneration.LocalSignatureProvider);
}
private static Dictionary<K, V> CreateDictionary<K, V>(IReadOnlyDictionary<K, V> dictionary, IEqualityComparer<K>? comparer)
where K : notnull
{
var result = new Dictionary<K, V>(comparer);
foreach (var pair in dictionary)
{
result.Add(pair.Key, pair.Value);
}
return result;
}
private static IReadOnlyDictionary<K, V> AddRange<K, V>(IReadOnlyDictionary<K, V> previous, IReadOnlyDictionary<K, V> current, IEqualityComparer<K>? comparer = null)
where K : notnull
{
if (previous.Count == 0)
{
return current;
}
if (current.Count == 0)
{
return previous;
}
var result = CreateDictionary(previous, comparer);
foreach (var pair in current)
{
// Use the latest symbol.
result[pair.Key] = pair.Value;
}
return result;
}
/// <summary>
/// Return tokens for all updated debuggable methods.
/// </summary>
public void GetUpdatedMethodTokens(ArrayBuilder<MethodDefinitionHandle> methods)
{
foreach (var def in _methodDefs.GetRows())
{
// The debugger tries to remap all modified methods, which requires presence of sequence points.
if (!_methodDefs.IsAddedNotChanged(def) && def.GetBody(Context)?.SequencePoints.Length > 0)
{
methods.Add(MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def)));
}
}
}
/// <summary>
/// Return tokens for all updated or added types.
/// </summary>
public void GetChangedTypeTokens(ArrayBuilder<TypeDefinitionHandle> types)
{
foreach (var def in _changedTypeDefs)
{
types.Add(MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(def)));
}
}
protected override ushort Generation
{
get { return (ushort)(_previousGeneration.Ordinal + 1); }
}
protected override Guid EncId
{
get { return _encId; }
}
protected override Guid EncBaseId
{
get { return _previousGeneration.EncId; }
}
protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def)
{
return MetadataTokens.EventDefinitionHandle(_eventDefs.GetRowId(def));
}
protected override IReadOnlyList<IEventDefinition> GetEventDefs()
{
return _eventDefs.GetRows();
}
protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def)
{
return MetadataTokens.FieldDefinitionHandle(_fieldDefs.GetRowId(def));
}
protected override IReadOnlyList<IFieldDefinition> GetFieldDefs()
{
return _fieldDefs.GetRows();
}
protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle)
{
bool result = _typeDefs.TryGetRowId(def, out int rowId);
handle = MetadataTokens.TypeDefinitionHandle(rowId);
return result;
}
protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def)
{
return MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(def));
}
protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle)
{
return _typeDefs.GetDefinition(MetadataTokens.GetRowNumber(handle));
}
protected override IReadOnlyList<ITypeDefinition> GetTypeDefs()
{
return _typeDefs.GetRows();
}
protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle)
{
bool result = _methodDefs.TryGetRowId(def, out int rowId);
handle = MetadataTokens.MethodDefinitionHandle(rowId);
return result;
}
protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def)
=> MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def));
protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle index)
=> _methodDefs.GetDefinition(MetadataTokens.GetRowNumber(index));
protected override IReadOnlyList<IMethodDefinition> GetMethodDefs()
=> _methodDefs.GetRows();
protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def)
=> MetadataTokens.PropertyDefinitionHandle(_propertyDefs.GetRowId(def));
protected override IReadOnlyList<IPropertyDefinition> GetPropertyDefs()
=> _propertyDefs.GetRows();
protected override ParameterHandle GetParameterHandle(IParameterDefinition def)
=> MetadataTokens.ParameterHandle(_parameterDefs.GetRowId(def));
protected override IReadOnlyList<IParameterDefinition> GetParameterDefs()
=> _parameterDefs.GetRows();
protected override IReadOnlyList<IGenericParameter> GetGenericParameters()
=> _genericParameters.GetRows();
// Fields are associated with the type through the EncLog table.
protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef)
=> default;
// Methods are associated with the type through the EncLog table.
protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef)
=> default;
// Parameters are associated with the method through the EncLog table.
protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef)
=> default;
protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference)
{
var identity = reference.Identity;
var versionPattern = reference.AssemblyVersionPattern;
if (versionPattern is not null)
{
RoslynDebug.AssertNotNull(_previousGeneration.InitialBaseline.LazyMetadataSymbols);
identity = _previousGeneration.InitialBaseline.LazyMetadataSymbols.AssemblyReferenceIdentityMap[identity.WithVersion(versionPattern)];
}
return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(identity));
}
protected override IReadOnlyList<AssemblyIdentity> GetAssemblyRefs()
{
return _assemblyRefIndex.Rows;
}
protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference)
{
return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<string> GetModuleRefs()
{
return _moduleRefIndex.Rows;
}
protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference)
{
return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeMemberReference> GetMemberRefs()
{
return _memberRefIndex.Rows;
}
protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference)
{
return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs()
{
return _methodSpecIndex.Rows;
}
protected override int GreatestMethodDefIndex => _methodDefs.NextRowId;
protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle)
{
int index;
bool result = _typeRefIndex.TryGetValue(reference, out index);
handle = MetadataTokens.TypeReferenceHandle(index);
return result;
}
protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference)
{
return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeRefs()
{
return _typeRefIndex.Rows;
}
protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference)
{
return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeSpecs()
{
return _typeSpecIndex.Rows;
}
protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex)
{
return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex));
}
protected override IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles()
{
return _standAloneSignatureIndex.Rows;
}
protected override void OnIndicesCreated()
{
var module = (IPEDeltaAssemblyBuilder)this.module;
module.OnCreatedIndices(this.Context.Diagnostics);
}
protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef)
{
var change = _changes.GetChange(typeDef);
switch (change)
{
case SymbolChange.Added:
_typeDefs.Add(typeDef);
_changedTypeDefs.Add(typeDef);
var typeParameters = this.GetConsolidatedTypeParameters(typeDef);
if (typeParameters != null)
{
foreach (var typeParameter in typeParameters)
{
_genericParameters.Add(typeParameter);
}
}
break;
case SymbolChange.Updated:
_typeDefs.AddUpdated(typeDef);
_changedTypeDefs.Add(typeDef);
break;
case SymbolChange.ContainsChanges:
// Members changed.
// We keep this list separately because we don't want to output duplicate typedef entries in the EnC log,
// which uses _typeDefs, but it's simpler to let the members output those rows for the updated typedefs
// with the right update type.
_changedTypeDefs.Add(typeDef);
break;
case SymbolChange.None:
// No changes to type.
return;
default:
throw ExceptionUtilities.UnexpectedValue(change);
}
int typeRowId = _typeDefs.GetRowId(typeDef);
foreach (var eventDef in typeDef.GetEvents(this.Context))
{
if (!_eventMap.Contains(typeRowId))
{
_eventMap.Add(typeRowId);
}
this.AddDefIfNecessary(_eventDefs, eventDef);
}
foreach (var fieldDef in typeDef.GetFields(this.Context))
{
this.AddDefIfNecessary(_fieldDefs, fieldDef);
}
foreach (var methodDef in typeDef.GetMethods(this.Context))
{
this.AddDefIfNecessary(_methodDefs, methodDef);
var methodChange = _changes.GetChange(methodDef);
if (methodChange == SymbolChange.Added)
{
_firstParamRowMap.Add(GetMethodDefinitionHandle(methodDef), _parameterDefs.NextRowId);
foreach (var paramDef in this.GetParametersToEmit(methodDef))
{
_parameterDefs.Add(paramDef);
_parameterDefList.Add(paramDef, methodDef);
}
}
else if (methodChange == SymbolChange.Updated)
{
// If we're re-emitting parameters for an existing method we need to find their original row numbers
// and reuse them so the EnCLog, EnCMap and CustomAttributes tables refer to the right rows
// Unfortunately we have to check the original metadata and deltas separately as nothing tracks the aggregate data
// in a way that we can use
var handle = GetMethodDefinitionHandle(methodDef);
if (_previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.MethodDef) >= MetadataTokens.GetRowNumber(handle))
{
EmitParametersFromOriginalMetadata(methodDef, handle);
}
else
{
EmitParametersFromDelta(methodDef, handle);
}
}
if (methodChange == SymbolChange.Added)
{
if (methodDef.GenericParameterCount > 0)
{
foreach (var typeParameter in methodDef.GenericParameters)
{
_genericParameters.Add(typeParameter);
}
}
}
}
foreach (var propertyDef in typeDef.GetProperties(this.Context))
{
if (!_propertyMap.Contains(typeRowId))
{
_propertyMap.Add(typeRowId);
}
this.AddDefIfNecessary(_propertyDefs, propertyDef);
}
var implementingMethods = ArrayBuilder<int>.GetInstance();
// First, visit all MethodImplementations and add to this.methodImplList.
foreach (var methodImpl in typeDef.GetExplicitImplementationOverrides(Context))
{
var methodDef = (IMethodDefinition?)methodImpl.ImplementingMethod.AsDefinition(this.Context);
RoslynDebug.AssertNotNull(methodDef);
int methodDefRowId = _methodDefs.GetRowId(methodDef);
// If there are N existing MethodImpl entries for this MethodDef,
// those will be index:1, ..., index:N, so it's sufficient to check for index:1.
var key = new MethodImplKey(methodDefRowId, index: 1);
if (!_methodImpls.Contains(key))
{
implementingMethods.Add(methodDefRowId);
this.methodImplList.Add(methodImpl);
}
}
// Next, add placeholders to this.methodImpls for items added above.
foreach (var methodDefIndex in implementingMethods)
{
int index = 1;
while (true)
{
var key = new MethodImplKey(methodDefIndex, index);
if (!_methodImpls.Contains(key))
{
_methodImpls.Add(key);
break;
}
index++;
}
}
implementingMethods.Free();
}
private void EmitParametersFromOriginalMetadata(IMethodDefinition methodDef, MethodDefinitionHandle handle)
{
var def = _previousGeneration.OriginalMetadata.MetadataReader.GetMethodDefinition(handle);
var parameters = def.GetParameters();
var paramDefinitions = this.GetParametersToEmit(methodDef);
int i = 0;
foreach (var param in parameters)
{
var paramDef = paramDefinitions[i];
_parameterDefs.AddUpdated(paramDef);
_existingParameterDefs.Add(paramDef, MetadataTokens.GetRowNumber(param));
_parameterDefList.Add(paramDef, methodDef);
i++;
}
}
private void EmitParametersFromDelta(IMethodDefinition methodDef, MethodDefinitionHandle handle)
{
var ok = _previousGeneration.FirstParamRowMap.TryGetValue(handle, out var firstRowId);
Debug.Assert(ok);
foreach (var paramDef in GetParametersToEmit(methodDef))
{
_parameterDefs.AddUpdated(paramDef);
_existingParameterDefs.Add(paramDef, firstRowId++);
_parameterDefList.Add(paramDef, methodDef);
}
}
private bool AddDefIfNecessary<T>(DefinitionIndex<T> defIndex, T def)
where T : class, IDefinition
{
switch (_changes.GetChange(def))
{
case SymbolChange.Added:
defIndex.Add(def);
return true;
case SymbolChange.Updated:
defIndex.AddUpdated(def);
return false;
case SymbolChange.ContainsChanges:
Debug.Assert(def is INestedTypeDefinition);
// Changes to members within nested type only.
return false;
default:
// No changes to member or container.
return false;
}
}
protected override ReferenceIndexer CreateReferenceVisitor()
{
return new DeltaReferenceIndexer(this);
}
protected override void ReportReferencesToAddedSymbols()
{
foreach (var typeRef in GetTypeRefs())
{
ReportReferencesToAddedSymbol(typeRef.GetInternalSymbol());
}
foreach (var memberRef in GetMemberRefs())
{
ReportReferencesToAddedSymbol(memberRef.GetInternalSymbol());
}
}
private void ReportReferencesToAddedSymbol(ISymbolInternal? symbol)
{
if (symbol != null && _changes.IsAdded(symbol.GetISymbol()))
{
Context.Diagnostics.Add(messageProvider.CreateDiagnostic(
messageProvider.ERR_EncReferenceToAddedMember,
GetSymbolLocation(symbol),
symbol.Name,
symbol.ContainingAssembly.Name));
}
}
protected override StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body)
{
StandaloneSignatureHandle localSignatureHandle;
var localVariables = body.LocalVariables;
var encInfos = ArrayBuilder<EncLocalInfo>.GetInstance();
if (localVariables.Length > 0)
{
var writer = PooledBlobBuilder.GetInstance();
var encoder = new BlobEncoder(writer).LocalVariableSignature(localVariables.Length);
foreach (ILocalDefinition local in localVariables)
{
var signature = local.Signature;
if (signature == null)
{
int start = writer.Count;
SerializeLocalVariableType(encoder.AddVariable(), local);
signature = writer.ToArray(start, writer.Count - start);
}
else
{
writer.WriteBytes(signature);
}
encInfos.Add(CreateEncLocalInfo(local, signature));
}
BlobHandle blobIndex = metadata.GetOrAddBlob(writer);
localSignatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex);
writer.Free();
}
else
{
localSignatureHandle = default;
}
var info = new AddedOrChangedMethodInfo(
body.MethodId,
encInfos.ToImmutable(),
body.LambdaDebugInfo,
body.ClosureDebugInfo,
body.StateMachineTypeName,
body.StateMachineHoistedLocalSlots,
body.StateMachineAwaiterSlots);
_addedOrChangedMethods.Add(body.MethodDefinition, info);
encInfos.Free();
return localSignatureHandle;
}
private EncLocalInfo CreateEncLocalInfo(ILocalDefinition localDef, byte[] signature)
{
if (localDef.SlotInfo.Id.IsNone)
{
return new EncLocalInfo(signature);
}
// local type is already translated, but not recursively
ITypeReference translatedType = localDef.Type;
if (translatedType.GetInternalSymbol() is ITypeSymbolInternal typeSymbol)
{
translatedType = Context.Module.EncTranslateType(typeSymbol, Context.Diagnostics);
}
return new EncLocalInfo(localDef.SlotInfo, translatedType, localDef.Constraints, signature);
}
protected override int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes)
{
// The base class will write out the actual metadata for us
var numAttributesEmitted = base.AddCustomAttributesToTable(parentHandle, attributes);
// We need to keep track of all of the things attributes could be associated with in this delta, in order to populate the EncLog and Map tables
_customAttributeParentCounts.Add(parentHandle, numAttributesEmitted);
return numAttributesEmitted;
}
public override void PopulateEncTables(ImmutableArray<int> typeSystemRowCounts)
{
Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncLog] == 0);
Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncMap] == 0);
PopulateEncLogTableRows(typeSystemRowCounts, out var customAttributeEncMapRows, out var paramEncMapRows);
PopulateEncMapTableRows(typeSystemRowCounts, customAttributeEncMapRows, paramEncMapRows);
}
private void PopulateEncLogTableRows(ImmutableArray<int> rowCounts, out List<int> customAttributeEncMapRows, out List<int> paramEncMapRows)
{
// The EncLog table is a log of all the operations needed
// to update the previous metadata. That means all
// new references must be added to the EncLog.
var previousSizes = _previousGeneration.TableSizes;
var deltaSizes = this.GetDeltaTableSizes(rowCounts);
PopulateEncLogTableRows(TableIndex.AssemblyRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ModuleRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MemberRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodSpec, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.TypeRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.TypeSpec, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.StandAloneSig, previousSizes, deltaSizes);
PopulateEncLogTableRows(_typeDefs, TableIndex.TypeDef);
PopulateEncLogTableRows(TableIndex.EventMap, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.PropertyMap, previousSizes, deltaSizes);
PopulateEncLogTableEventsOrProperties(_eventDefs, TableIndex.Event, EditAndContinueOperation.AddEvent, _eventMap, TableIndex.EventMap);
PopulateEncLogTableFieldsOrMethods(_fieldDefs, TableIndex.Field, EditAndContinueOperation.AddField);
PopulateEncLogTableFieldsOrMethods(_methodDefs, TableIndex.MethodDef, EditAndContinueOperation.AddMethod);
PopulateEncLogTableEventsOrProperties(_propertyDefs, TableIndex.Property, EditAndContinueOperation.AddProperty, _propertyMap, TableIndex.PropertyMap);
PopulateEncLogTableParameters(out paramEncMapRows);
PopulateEncLogTableRows(TableIndex.Constant, previousSizes, deltaSizes);
PopulateEncLogTableCustomAttributes(out customAttributeEncMapRows);
PopulateEncLogTableRows(TableIndex.DeclSecurity, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ClassLayout, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.FieldLayout, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodSemantics, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodImpl, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ImplMap, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.FieldRva, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.NestedClass, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.GenericParam, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.InterfaceImpl, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.GenericParamConstraint, previousSizes, deltaSizes);
}
private void PopulateEncLogTableEventsOrProperties<T>(
DefinitionIndex<T> index,
TableIndex table,
EditAndContinueOperation addCode,
EventOrPropertyMapIndex map,
TableIndex mapTable)
where T : class, ITypeDefinitionMember
{
foreach (var member in index.GetRows())
{
if (index.IsAddedNotChanged(member))
{
int typeRowId = _typeDefs.GetRowId(member.ContainingTypeDefinition);
int mapRowId = map.GetRowId(typeRowId);
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(mapTable, mapRowId),
code: addCode);
}
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(table, index.GetRowId(member)),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableFieldsOrMethods<T>(
DefinitionIndex<T> index,
TableIndex tableIndex,
EditAndContinueOperation addCode)
where T : class, ITypeDefinitionMember
{
foreach (var member in index.GetRows())
{
if (index.IsAddedNotChanged(member))
{
metadata.AddEncLogEntry(
entity: MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(member.ContainingTypeDefinition)),
code: addCode);
}
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableParameters(out List<int> paramEncMapRows)
{
paramEncMapRows = new List<int>();
var parameterFirstId = _parameterDefs.FirstRowId;
int i = 0;
foreach (var paramDef in GetParameterDefs())
{
var methodDef = _parameterDefList[paramDef];
if (_methodDefs.IsAddedNotChanged(methodDef))
{
// For parameters on new methods we emit AddParameter rows for the method too
paramEncMapRows.Add(parameterFirstId + i);
metadata.AddEncLogEntry(
entity: MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(methodDef)),
code: EditAndContinueOperation.AddParameter);
metadata.AddEncLogEntry(
entity: MetadataTokens.ParameterHandle(parameterFirstId + i),
code: EditAndContinueOperation.Default);
i++;
}
else
{
// For previously emitted parameters we just update the Param row
var param = GetParameterHandle(paramDef);
paramEncMapRows.Add(MetadataTokens.GetRowNumber(param));
metadata.AddEncLogEntry(
entity: param,
code: EditAndContinueOperation.Default);
}
}
}
/// <summary>
/// CustomAttributes point to their target via the Parent column so we cannot simply output new rows
/// in the delta or we would end up with duplicates, but we also don't want to do complex logic to determine
/// which attributes have changes, so we just emit them all.
/// This means our logic for emitting CustomAttributes is to update any existing rows, either from the original
/// compilation or subsequent deltas, and only add more if we need to. The EncLog table is the thing that tells
/// the runtime which row a CustomAttributes row is (ie, new or existing)
/// </summary>
private void PopulateEncLogTableCustomAttributes(out List<int> customAttributeEncMapRows)
{
customAttributeEncMapRows = new List<int>();
// List of attributes that need to be emitted to delete a previously emitted attribute
var deletedAttributeRows = new List<(int parentRowId, HandleKind kind)>();
var customAttributesAdded = new Dictionary<EntityHandle, ArrayBuilder<int>>();
// The data in _previousGeneration.CustomAttributesAdded is not nicely sorted, or even necessarily contiguous
// so we need to map each target onto the rows its attributes occupy so we know which rows to update
var lastRowId = _previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.CustomAttribute);
if (_previousGeneration.CustomAttributesAdded.Count > 0)
{
lastRowId = _previousGeneration.CustomAttributesAdded.SelectMany(s => s.Value).Max();
}
// Iterate through the parents we emitted custom attributes for, in parent order
foreach (var (parent, count) in _customAttributeParentCounts.OrderBy(kvp => CodedIndex.HasCustomAttribute(kvp.Key)))
{
int index = 0;
// First we try to update any existing attributes.
// GetCustomAttributes does a binary search, so is fast. We presume that the number of rows in the original metadata
// greatly outnumbers the amount of parents emitted in this delta so even with repeated searches this is still
// quicker than iterating the entire original table, even once.
var existingCustomAttributes = _previousGeneration.OriginalMetadata.MetadataReader.GetCustomAttributes(parent);
foreach (var attributeHandle in existingCustomAttributes)
{
int rowId = MetadataTokens.GetRowNumber(attributeHandle);
AddLogEntryOrDelete(rowId, parent, add: index < count, customAttributeEncMapRows);
index++;
}
// If we emitted any attributes for this parent in previous deltas then we either need to update
// them next, or delete them if necessary
if (_previousGeneration.CustomAttributesAdded.TryGetValue(parent, out var rowIds))
{
foreach (var rowId in rowIds)
{
TrackCustomAttributeAdded(rowId, parent);
AddLogEntryOrDelete(rowId, parent, add: index < count, customAttributeEncMapRows);
index++;
}
}
// Finally if there are still attributes for this parent left, they are additions new to this delta
for (int i = index; i < count; i++)
{
lastRowId++;
TrackCustomAttributeAdded(lastRowId, parent);
AddEncLogEntry(lastRowId, customAttributeEncMapRows);
}
}
// Save the attributes we've emitted, and the ones from previous deltas, for use in the next generation
foreach (var (parent, rowIds) in customAttributesAdded)
{
_customAttributesAdded.Add(parent, rowIds.ToImmutableAndFree());
}
// Add attributes and log entries for everything we've deleted
foreach (var row in deletedAttributeRows)
{
// now emit a "delete" row with a parent that is for the 0 row of the same table as the existing one
if (!MetadataTokens.TryGetTableIndex(row.kind, out var tableIndex))
{
throw new InvalidOperationException("Trying to delete a custom attribute for a parent kind that doesn't have a matching table index.");
}
metadata.AddCustomAttribute(MetadataTokens.Handle(tableIndex, 0), MetadataTokens.EntityHandle(TableIndex.MemberRef, 0), value: default);
AddEncLogEntry(row.parentRowId, customAttributeEncMapRows);
}
void AddEncLogEntry(int rowId, List<int> customAttributeEncMapRows)
{
customAttributeEncMapRows.Add(rowId);
metadata.AddEncLogEntry(
entity: MetadataTokens.CustomAttributeHandle(rowId),
code: EditAndContinueOperation.Default);
}
void AddLogEntryOrDelete(int rowId, EntityHandle parent, bool add, List<int> customAttributeEncMapRows)
{
if (add)
{
// Update this row
AddEncLogEntry(rowId, customAttributeEncMapRows);
}
else
{
// Delete this row
deletedAttributeRows.Add((rowId, parent.Kind));
}
}
void TrackCustomAttributeAdded(int nextRowId, EntityHandle parent)
{
if (!customAttributesAdded.TryGetValue(parent, out var existing))
{
existing = ArrayBuilder<int>.GetInstance();
customAttributesAdded.Add(parent, existing);
}
existing.Add(nextRowId);
}
}
private void PopulateEncLogTableRows<T>(DefinitionIndex<T> index, TableIndex tableIndex)
where T : class, IDefinition
{
foreach (var member in index.GetRows())
{
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableRows(TableIndex tableIndex, ImmutableArray<int> previousSizes, ImmutableArray<int> deltaSizes)
{
PopulateEncLogTableRows(tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]);
}
private void PopulateEncLogTableRows(TableIndex tableIndex, int firstRowId, int tokenCount)
{
for (int i = 0; i < tokenCount; i++)
{
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, firstRowId + i),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncMapTableRows(ImmutableArray<int> rowCounts, List<int> customAttributeEncMapRows, List<int> paramEncMapRows)
{
// The EncMap table maps from offset in each table in the delta
// metadata to token. As such, the EncMap is a concatenated
// list of all tokens in all tables from the delta sorted by table
// and, within each table, sorted by row.
var tokens = ArrayBuilder<EntityHandle>.GetInstance();
var previousSizes = _previousGeneration.TableSizes;
var deltaSizes = this.GetDeltaTableSizes(rowCounts);
AddReferencedTokens(tokens, TableIndex.AssemblyRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ModuleRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MemberRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodSpec, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.TypeRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.TypeSpec, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.StandAloneSig, previousSizes, deltaSizes);
AddDefinitionTokens(tokens, _typeDefs, TableIndex.TypeDef);
AddDefinitionTokens(tokens, _eventDefs, TableIndex.Event);
AddDefinitionTokens(tokens, _fieldDefs, TableIndex.Field);
AddDefinitionTokens(tokens, _methodDefs, TableIndex.MethodDef);
AddDefinitionTokens(tokens, _propertyDefs, TableIndex.Property);
AddRowNumberTokens(tokens, paramEncMapRows, TableIndex.Param);
AddReferencedTokens(tokens, TableIndex.Constant, previousSizes, deltaSizes);
AddRowNumberTokens(tokens, customAttributeEncMapRows, TableIndex.CustomAttribute);
AddReferencedTokens(tokens, TableIndex.DeclSecurity, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ClassLayout, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.FieldLayout, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.EventMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.PropertyMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodSemantics, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodImpl, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ImplMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.FieldRva, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.NestedClass, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.GenericParam, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.InterfaceImpl, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.GenericParamConstraint, previousSizes, deltaSizes);
tokens.Sort(HandleComparer.Default);
// Should not be any duplicates.
Debug.Assert(tokens.Distinct().Count() == tokens.Count);
foreach (var token in tokens)
{
metadata.AddEncMapEntry(token);
}
tokens.Free();
// Populate Portable PDB EncMap table with MethodDebugInformation mapping,
// which corresponds 1:1 to MethodDef mapping.
if (_debugMetadataOpt != null)
{
var debugTokens = ArrayBuilder<EntityHandle>.GetInstance();
AddDefinitionTokens(debugTokens, _methodDefs, TableIndex.MethodDebugInformation);
debugTokens.Sort(HandleComparer.Default);
// Should not be any duplicates.
Debug.Assert(debugTokens.Distinct().Count() == debugTokens.Count);
foreach (var token in debugTokens)
{
_debugMetadataOpt.AddEncMapEntry(token);
}
debugTokens.Free();
}
#if DEBUG
// The following tables are either represented in the EncMap
// or specifically ignored. The rest should be empty.
var handledTables = new TableIndex[]
{
TableIndex.Module,
TableIndex.TypeRef,
TableIndex.TypeDef,
TableIndex.Field,
TableIndex.MethodDef,
TableIndex.Param,
TableIndex.MemberRef,
TableIndex.Constant,
TableIndex.CustomAttribute,
TableIndex.DeclSecurity,
TableIndex.ClassLayout,
TableIndex.FieldLayout,
TableIndex.StandAloneSig,
TableIndex.EventMap,
TableIndex.Event,
TableIndex.PropertyMap,
TableIndex.Property,
TableIndex.MethodSemantics,
TableIndex.MethodImpl,
TableIndex.ModuleRef,
TableIndex.TypeSpec,
TableIndex.ImplMap,
// FieldRva is not needed since we only emit fields with explicit mapping
// for <PrivateImplementationDetails> and that class is not used in ENC.
// If we need FieldRva in the future, we'll need a corresponding test.
// (See EditAndContinueTests.FieldRva that was deleted in this change.)
//TableIndex.FieldRva,
TableIndex.EncLog,
TableIndex.EncMap,
TableIndex.Assembly,
TableIndex.AssemblyRef,
TableIndex.MethodSpec,
TableIndex.NestedClass,
TableIndex.GenericParam,
TableIndex.InterfaceImpl,
TableIndex.GenericParamConstraint,
};
for (int i = 0; i < rowCounts.Length; i++)
{
if (handledTables.Contains((TableIndex)i))
{
continue;
}
Debug.Assert(rowCounts[i] == 0);
}
#endif
}
private static void AddReferencedTokens(
ArrayBuilder<EntityHandle> builder,
TableIndex tableIndex,
ImmutableArray<int> previousSizes,
ImmutableArray<int> deltaSizes)
{
AddReferencedTokens(builder, tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]);
}
private static void AddReferencedTokens(ArrayBuilder<EntityHandle> builder, TableIndex tableIndex, int firstRowId, int nTokens)
{
for (int i = 0; i < nTokens; i++)
{
builder.Add(MetadataTokens.Handle(tableIndex, firstRowId + i));
}
}
private static void AddDefinitionTokens<T>(ArrayBuilder<EntityHandle> tokens, DefinitionIndex<T> index, TableIndex tableIndex)
where T : class, IDefinition
{
foreach (var member in index.GetRows())
{
tokens.Add(MetadataTokens.Handle(tableIndex, index.GetRowId(member)));
}
}
private static void AddRowNumberTokens(ArrayBuilder<EntityHandle> tokens, IEnumerable<int> rowNumbers, TableIndex tableIndex)
{
foreach (var row in rowNumbers)
{
tokens.Add(MetadataTokens.Handle(tableIndex, row));
}
}
protected override void PopulateEventMapTableRows()
{
foreach (var typeId in _eventMap.GetRows())
{
metadata.AddEventMap(
declaringType: MetadataTokens.TypeDefinitionHandle(typeId),
eventList: MetadataTokens.EventDefinitionHandle(_eventMap.GetRowId(typeId)));
}
}
protected override void PopulatePropertyMapTableRows()
{
foreach (var typeId in _propertyMap.GetRows())
{
metadata.AddPropertyMap(
declaringType: MetadataTokens.TypeDefinitionHandle(typeId),
propertyList: MetadataTokens.PropertyDefinitionHandle(_propertyMap.GetRowId(typeId)));
}
}
private abstract class DefinitionIndexBase<T>
where T : notnull
{
protected readonly Dictionary<T, int> added; // Definitions added in this generation.
protected readonly List<T> rows; // Rows in this generation, containing adds and updates.
private readonly int _firstRowId; // First row in this generation.
private bool _frozen;
public DefinitionIndexBase(int lastRowId, IEqualityComparer<T>? comparer = null)
{
this.added = new Dictionary<T, int>(comparer);
this.rows = new List<T>();
_firstRowId = lastRowId + 1;
}
public abstract bool TryGetRowId(T item, out int rowId);
public int GetRowId(T item)
{
bool containsItem = TryGetRowId(item, out int rowId);
// Fails if we are attempting to make a change that should have been reported as rude,
// e.g. the corresponding definitions type don't match, etc.
Debug.Assert(containsItem);
Debug.Assert(rowId > 0);
return rowId;
}
public bool Contains(T item)
=> TryGetRowId(item, out _);
// A method rather than a property since it freezes the table.
public IReadOnlyDictionary<T, int> GetAdded()
{
this.Freeze();
return this.added;
}
// A method rather than a property since it freezes the table.
public IReadOnlyList<T> GetRows()
{
this.Freeze();
return this.rows;
}
public int FirstRowId
{
get { return _firstRowId; }
}
public int NextRowId
{
get { return this.added.Count + _firstRowId; }
}
public bool IsFrozen
{
get { return _frozen; }
}
protected virtual void OnFrozen()
{
#if DEBUG
// Verify the rows are sorted.
int prev = 0;
foreach (var row in this.rows)
{
int next = this.added[row];
Debug.Assert(prev < next);
prev = next;
}
#endif
}
private void Freeze()
{
if (!_frozen)
{
_frozen = true;
this.OnFrozen();
}
}
}
private sealed class DefinitionIndex<T> : DefinitionIndexBase<T> where T : class, IDefinition
{
public delegate bool TryGetExistingIndex(T item, out int index);
private readonly TryGetExistingIndex _tryGetExistingIndex;
// Map of row id to def for all defs. This could be an array indexed
// by row id but the array could be large and sparsely populated
// if there are many defs in the previous generation but few
// references to those defs in the current generation.
private readonly Dictionary<int, T> _map;
public DefinitionIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
_tryGetExistingIndex = tryGetExistingIndex;
_map = new Dictionary<int, T>();
}
public override bool TryGetRowId(T item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_tryGetExistingIndex(item, out index))
{
#if DEBUG
Debug.Assert(!_map.TryGetValue(index, out var other) || ((object)other == (object)item));
#endif
_map[index] = item;
return true;
}
return false;
}
public T GetDefinition(int rowId)
=> _map[rowId];
public void Add(T item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
_map[index] = item;
this.rows.Add(item);
}
/// <summary>
/// Add an item from a previous generation
/// that has been updated in this generation.
/// </summary>
public void AddUpdated(T item)
{
Debug.Assert(!this.IsFrozen);
this.rows.Add(item);
}
public bool IsAddedNotChanged(T item)
=> added.ContainsKey(item);
protected override void OnFrozen()
=> rows.Sort((x, y) => GetRowId(x).CompareTo(GetRowId(y)));
}
private bool TryGetExistingTypeDefIndex(ITypeDefinition item, out int index)
{
if (_previousGeneration.TypesAdded.TryGetValue(item, out index))
{
return true;
}
TypeDefinitionHandle handle;
if (_definitionMap.TryGetTypeHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingEventDefIndex(IEventDefinition item, out int index)
{
if (_previousGeneration.EventsAdded.TryGetValue(item, out index))
{
return true;
}
EventDefinitionHandle handle;
if (_definitionMap.TryGetEventHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingFieldDefIndex(IFieldDefinition item, out int index)
{
if (_previousGeneration.FieldsAdded.TryGetValue(item, out index))
{
return true;
}
FieldDefinitionHandle handle;
if (_definitionMap.TryGetFieldHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingMethodDefIndex(IMethodDefinition item, out int index)
{
if (_previousGeneration.MethodsAdded.TryGetValue(item, out index))
{
return true;
}
MethodDefinitionHandle handle;
if (_definitionMap.TryGetMethodHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingPropertyDefIndex(IPropertyDefinition item, out int index)
{
if (_previousGeneration.PropertiesAdded.TryGetValue(item, out index))
{
return true;
}
PropertyDefinitionHandle handle;
if (_definitionMap.TryGetPropertyHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingParameterDefIndex(IParameterDefinition item, out int index)
{
return _existingParameterDefs.TryGetValue(item, out index);
}
private bool TryGetExistingEventMapIndex(int item, out int index)
{
if (_previousGeneration.EventMapAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.TypeToEventMap.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private bool TryGetExistingPropertyMapIndex(int item, out int index)
{
if (_previousGeneration.PropertyMapAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.TypeToPropertyMap.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private bool TryGetExistingMethodImplIndex(MethodImplKey item, out int index)
{
if (_previousGeneration.MethodImplsAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.MethodImpls.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private sealed class GenericParameterIndex : DefinitionIndexBase<IGenericParameter>
{
public GenericParameterIndex(int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
}
public override bool TryGetRowId(IGenericParameter item, out int index)
{
return this.added.TryGetValue(item, out index);
}
public void Add(IGenericParameter item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class EventOrPropertyMapIndex : DefinitionIndexBase<int>
{
public delegate bool TryGetExistingIndex(int item, out int index);
private readonly TryGetExistingIndex _tryGetExistingIndex;
public EventOrPropertyMapIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId)
: base(lastRowId)
{
_tryGetExistingIndex = tryGetExistingIndex;
}
public override bool TryGetRowId(int item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_tryGetExistingIndex(item, out index))
{
return true;
}
index = 0;
return false;
}
public void Add(int item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class MethodImplIndex : DefinitionIndexBase<MethodImplKey>
{
private readonly DeltaMetadataWriter _writer;
public MethodImplIndex(DeltaMetadataWriter writer, int lastRowId)
: base(lastRowId)
{
_writer = writer;
}
public override bool TryGetRowId(MethodImplKey item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_writer.TryGetExistingMethodImplIndex(item, out index))
{
return true;
}
index = 0;
return false;
}
public void Add(MethodImplKey item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class DeltaReferenceIndexer : ReferenceIndexer
{
private readonly SymbolChanges _changes;
public DeltaReferenceIndexer(DeltaMetadataWriter writer)
: base(writer)
{
_changes = writer._changes;
}
public override void Visit(CommonPEModuleBuilder module)
{
Visit(module.GetTopLevelTypeDefinitions(metadataWriter.Context));
}
public override void Visit(IEventDefinition eventDefinition)
{
Debug.Assert(this.ShouldVisit(eventDefinition));
base.Visit(eventDefinition);
}
public override void Visit(IFieldDefinition fieldDefinition)
{
Debug.Assert(this.ShouldVisit(fieldDefinition));
base.Visit(fieldDefinition);
}
public override void Visit(ILocalDefinition localDefinition)
{
if (localDefinition.Signature == null)
{
base.Visit(localDefinition);
}
}
public override void Visit(IMethodDefinition method)
{
Debug.Assert(this.ShouldVisit(method));
base.Visit(method);
}
public override void Visit(Cci.MethodImplementation methodImplementation)
{
// Unless the implementing method was added,
// the method implementation already exists.
var methodDef = (IMethodDefinition?)methodImplementation.ImplementingMethod.AsDefinition(this.Context);
RoslynDebug.AssertNotNull(methodDef);
if (_changes.GetChange(methodDef) == SymbolChange.Added)
{
base.Visit(methodImplementation);
}
}
public override void Visit(INamespaceTypeDefinition namespaceTypeDefinition)
{
Debug.Assert(this.ShouldVisit(namespaceTypeDefinition));
base.Visit(namespaceTypeDefinition);
}
public override void Visit(INestedTypeDefinition nestedTypeDefinition)
{
Debug.Assert(this.ShouldVisit(nestedTypeDefinition));
base.Visit(nestedTypeDefinition);
}
public override void Visit(IPropertyDefinition propertyDefinition)
{
Debug.Assert(this.ShouldVisit(propertyDefinition));
base.Visit(propertyDefinition);
}
public override void Visit(ITypeDefinition typeDefinition)
{
if (this.ShouldVisit(typeDefinition))
{
base.Visit(typeDefinition);
}
}
public override void Visit(ITypeDefinitionMember typeMember)
{
if (this.ShouldVisit(typeMember))
{
base.Visit(typeMember);
}
}
private bool ShouldVisit(IDefinition def)
{
return _changes.GetChange(def) != SymbolChange.None;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit
{
internal sealed class DeltaMetadataWriter : MetadataWriter
{
private readonly EmitBaseline _previousGeneration;
private readonly Guid _encId;
private readonly DefinitionMap _definitionMap;
private readonly SymbolChanges _changes;
/// <summary>
/// Type definitions containing any changes (includes added types).
/// </summary>
private readonly List<ITypeDefinition> _changedTypeDefs;
private readonly DefinitionIndex<ITypeDefinition> _typeDefs;
private readonly DefinitionIndex<IEventDefinition> _eventDefs;
private readonly DefinitionIndex<IFieldDefinition> _fieldDefs;
private readonly DefinitionIndex<IMethodDefinition> _methodDefs;
private readonly DefinitionIndex<IPropertyDefinition> _propertyDefs;
private readonly DefinitionIndex<IParameterDefinition> _parameterDefs;
private readonly Dictionary<IParameterDefinition, IMethodDefinition> _parameterDefList;
private readonly GenericParameterIndex _genericParameters;
private readonly EventOrPropertyMapIndex _eventMap;
private readonly EventOrPropertyMapIndex _propertyMap;
private readonly MethodImplIndex _methodImpls;
// For the EncLog table we need to know which things we're emitting custom attributes for so we can
// correctly map the attributes to row numbers of existing attributes for that target
private readonly Dictionary<EntityHandle, int> _customAttributeParentCounts;
// Keep track of which CustomAttributes rows are added in this and previous deltas, over what is in the
// original metadata
private readonly Dictionary<EntityHandle, ImmutableArray<int>> _customAttributesAdded;
private readonly Dictionary<IParameterDefinition, int> _existingParameterDefs;
private readonly Dictionary<MethodDefinitionHandle, int> _firstParamRowMap;
private readonly HeapOrReferenceIndex<AssemblyIdentity> _assemblyRefIndex;
private readonly HeapOrReferenceIndex<string> _moduleRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeMemberReference> _memberRefIndex;
private readonly InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference> _methodSpecIndex;
private readonly TypeReferenceIndex _typeRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeReference> _typeSpecIndex;
private readonly HeapOrReferenceIndex<BlobHandle> _standAloneSignatureIndex;
private readonly Dictionary<IMethodDefinition, AddedOrChangedMethodInfo> _addedOrChangedMethods;
public DeltaMetadataWriter(
EmitContext context,
CommonMessageProvider messageProvider,
EmitBaseline previousGeneration,
Guid encId,
DefinitionMap definitionMap,
SymbolChanges changes,
CancellationToken cancellationToken)
: base(metadata: MakeTablesBuilder(previousGeneration),
debugMetadataOpt: (context.Module.DebugInformationFormat == DebugInformationFormat.PortablePdb) ? new MetadataBuilder() : null,
dynamicAnalysisDataWriterOpt: null,
context: context,
messageProvider: messageProvider,
metadataOnly: false,
deterministic: false,
emitTestCoverageData: false,
cancellationToken: cancellationToken)
{
Debug.Assert(previousGeneration != null);
Debug.Assert(encId != default(Guid));
Debug.Assert(encId != previousGeneration.EncId);
Debug.Assert(context.Module.DebugInformationFormat != DebugInformationFormat.Embedded);
_previousGeneration = previousGeneration;
_encId = encId;
_definitionMap = definitionMap;
_changes = changes;
var sizes = previousGeneration.TableSizes;
_changedTypeDefs = new List<ITypeDefinition>();
_typeDefs = new DefinitionIndex<ITypeDefinition>(this.TryGetExistingTypeDefIndex, sizes[(int)TableIndex.TypeDef]);
_eventDefs = new DefinitionIndex<IEventDefinition>(this.TryGetExistingEventDefIndex, sizes[(int)TableIndex.Event]);
_fieldDefs = new DefinitionIndex<IFieldDefinition>(this.TryGetExistingFieldDefIndex, sizes[(int)TableIndex.Field]);
_methodDefs = new DefinitionIndex<IMethodDefinition>(this.TryGetExistingMethodDefIndex, sizes[(int)TableIndex.MethodDef]);
_propertyDefs = new DefinitionIndex<IPropertyDefinition>(this.TryGetExistingPropertyDefIndex, sizes[(int)TableIndex.Property]);
_parameterDefs = new DefinitionIndex<IParameterDefinition>(this.TryGetExistingParameterDefIndex, sizes[(int)TableIndex.Param]);
_parameterDefList = new Dictionary<IParameterDefinition, IMethodDefinition>(Cci.SymbolEquivalentEqualityComparer.Instance);
_genericParameters = new GenericParameterIndex(sizes[(int)TableIndex.GenericParam]);
_eventMap = new EventOrPropertyMapIndex(this.TryGetExistingEventMapIndex, sizes[(int)TableIndex.EventMap]);
_propertyMap = new EventOrPropertyMapIndex(this.TryGetExistingPropertyMapIndex, sizes[(int)TableIndex.PropertyMap]);
_methodImpls = new MethodImplIndex(this, sizes[(int)TableIndex.MethodImpl]);
_customAttributeParentCounts = new Dictionary<EntityHandle, int>();
_customAttributesAdded = new Dictionary<EntityHandle, ImmutableArray<int>>();
_firstParamRowMap = new Dictionary<MethodDefinitionHandle, int>();
_existingParameterDefs = new Dictionary<IParameterDefinition, int>(ReferenceEqualityComparer.Instance);
_assemblyRefIndex = new HeapOrReferenceIndex<AssemblyIdentity>(this, lastRowId: sizes[(int)TableIndex.AssemblyRef]);
_moduleRefIndex = new HeapOrReferenceIndex<string>(this, lastRowId: sizes[(int)TableIndex.ModuleRef]);
_memberRefIndex = new InstanceAndStructuralReferenceIndex<ITypeMemberReference>(this, new MemberRefComparer(this), lastRowId: sizes[(int)TableIndex.MemberRef]);
_methodSpecIndex = new InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference>(this, new MethodSpecComparer(this), lastRowId: sizes[(int)TableIndex.MethodSpec]);
_typeRefIndex = new TypeReferenceIndex(this, lastRowId: sizes[(int)TableIndex.TypeRef]);
_typeSpecIndex = new InstanceAndStructuralReferenceIndex<ITypeReference>(this, new TypeSpecComparer(this), lastRowId: sizes[(int)TableIndex.TypeSpec]);
_standAloneSignatureIndex = new HeapOrReferenceIndex<BlobHandle>(this, lastRowId: sizes[(int)TableIndex.StandAloneSig]);
_addedOrChangedMethods = new Dictionary<IMethodDefinition, AddedOrChangedMethodInfo>(Cci.SymbolEquivalentEqualityComparer.Instance);
}
private static MetadataBuilder MakeTablesBuilder(EmitBaseline previousGeneration)
{
return new MetadataBuilder(
previousGeneration.UserStringStreamLength,
previousGeneration.StringStreamLength,
previousGeneration.BlobStreamLength,
previousGeneration.GuidStreamLength);
}
private ImmutableArray<int> GetDeltaTableSizes(ImmutableArray<int> rowCounts)
{
var sizes = new int[MetadataTokens.TableCount];
rowCounts.CopyTo(sizes);
sizes[(int)TableIndex.TypeRef] = _typeRefIndex.Rows.Count;
sizes[(int)TableIndex.TypeDef] = _typeDefs.GetAdded().Count;
sizes[(int)TableIndex.Field] = _fieldDefs.GetAdded().Count;
sizes[(int)TableIndex.MethodDef] = _methodDefs.GetAdded().Count;
sizes[(int)TableIndex.Param] = _parameterDefs.GetAdded().Count;
sizes[(int)TableIndex.MemberRef] = _memberRefIndex.Rows.Count;
sizes[(int)TableIndex.StandAloneSig] = _standAloneSignatureIndex.Rows.Count;
sizes[(int)TableIndex.EventMap] = _eventMap.GetAdded().Count;
sizes[(int)TableIndex.Event] = _eventDefs.GetAdded().Count;
sizes[(int)TableIndex.PropertyMap] = _propertyMap.GetAdded().Count;
sizes[(int)TableIndex.Property] = _propertyDefs.GetAdded().Count;
sizes[(int)TableIndex.MethodImpl] = _methodImpls.GetAdded().Count;
sizes[(int)TableIndex.ModuleRef] = _moduleRefIndex.Rows.Count;
sizes[(int)TableIndex.TypeSpec] = _typeSpecIndex.Rows.Count;
sizes[(int)TableIndex.AssemblyRef] = _assemblyRefIndex.Rows.Count;
sizes[(int)TableIndex.GenericParam] = _genericParameters.GetAdded().Count;
sizes[(int)TableIndex.MethodSpec] = _methodSpecIndex.Rows.Count;
return ImmutableArray.Create(sizes);
}
internal EmitBaseline GetDelta(Compilation compilation, Guid encId, MetadataSizes metadataSizes)
{
var addedOrChangedMethodsByIndex = new Dictionary<int, AddedOrChangedMethodInfo>();
foreach (var pair in _addedOrChangedMethods)
{
addedOrChangedMethodsByIndex.Add(MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(pair.Key)), pair.Value);
}
var previousTableSizes = _previousGeneration.TableEntriesAdded;
var deltaTableSizes = GetDeltaTableSizes(metadataSizes.RowCounts);
var tableSizes = new int[MetadataTokens.TableCount];
for (int i = 0; i < tableSizes.Length; i++)
{
tableSizes[i] = previousTableSizes[i] + deltaTableSizes[i];
}
// If the previous generation is 0 (metadata) get the synthesized members from the current compilation's builder,
// otherwise members from the current compilation have already been merged into the baseline.
var synthesizedMembers = (_previousGeneration.Ordinal == 0) ? module.GetAllSynthesizedMembers() : _previousGeneration.SynthesizedMembers;
var currentGenerationOrdinal = _previousGeneration.Ordinal + 1;
var addedTypes = _typeDefs.GetAdded();
var generationOrdinals = CreateDictionary(_previousGeneration.GenerationOrdinals, SymbolEquivalentEqualityComparer.Instance);
foreach (var (addedType, _) in addedTypes)
{
if (_changes.IsReplaced(addedType))
{
generationOrdinals[addedType] = currentGenerationOrdinal;
}
}
return _previousGeneration.With(
compilation,
module,
currentGenerationOrdinal,
encId,
generationOrdinals,
typesAdded: AddRange(_previousGeneration.TypesAdded, addedTypes, comparer: SymbolEquivalentEqualityComparer.Instance),
eventsAdded: AddRange(_previousGeneration.EventsAdded, _eventDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
fieldsAdded: AddRange(_previousGeneration.FieldsAdded, _fieldDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
methodsAdded: AddRange(_previousGeneration.MethodsAdded, _methodDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
firstParamRowMap: AddRange(_previousGeneration.FirstParamRowMap, _firstParamRowMap),
propertiesAdded: AddRange(_previousGeneration.PropertiesAdded, _propertyDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
eventMapAdded: AddRange(_previousGeneration.EventMapAdded, _eventMap.GetAdded()),
propertyMapAdded: AddRange(_previousGeneration.PropertyMapAdded, _propertyMap.GetAdded()),
methodImplsAdded: AddRange(_previousGeneration.MethodImplsAdded, _methodImpls.GetAdded()),
customAttributesAdded: AddRange(_previousGeneration.CustomAttributesAdded, _customAttributesAdded),
tableEntriesAdded: ImmutableArray.Create(tableSizes),
// Blob stream is concatenated aligned.
blobStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.Blob) + _previousGeneration.BlobStreamLengthAdded,
// String stream is concatenated unaligned.
stringStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.String] + _previousGeneration.StringStreamLengthAdded,
// UserString stream is concatenated aligned.
userStringStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.UserString) + _previousGeneration.UserStringStreamLengthAdded,
// Guid stream accumulates on the GUID heap unlike other heaps, so the previous generations are already included.
guidStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.Guid],
anonymousTypeMap: ((IPEDeltaAssemblyBuilder)module).GetAnonymousTypeMap(),
synthesizedMembers: synthesizedMembers,
addedOrChangedMethods: AddRange(_previousGeneration.AddedOrChangedMethods, addedOrChangedMethodsByIndex),
debugInformationProvider: _previousGeneration.DebugInformationProvider,
localSignatureProvider: _previousGeneration.LocalSignatureProvider);
}
private static Dictionary<K, V> CreateDictionary<K, V>(IReadOnlyDictionary<K, V> dictionary, IEqualityComparer<K>? comparer)
where K : notnull
{
var result = new Dictionary<K, V>(comparer);
foreach (var pair in dictionary)
{
result.Add(pair.Key, pair.Value);
}
return result;
}
private static IReadOnlyDictionary<K, V> AddRange<K, V>(IReadOnlyDictionary<K, V> previous, IReadOnlyDictionary<K, V> current, IEqualityComparer<K>? comparer = null)
where K : notnull
{
if (previous.Count == 0)
{
return current;
}
if (current.Count == 0)
{
return previous;
}
var result = CreateDictionary(previous, comparer);
foreach (var pair in current)
{
// Use the latest symbol.
result[pair.Key] = pair.Value;
}
return result;
}
/// <summary>
/// Return tokens for all updated debuggable methods.
/// </summary>
public void GetUpdatedMethodTokens(ArrayBuilder<MethodDefinitionHandle> methods)
{
foreach (var def in _methodDefs.GetRows())
{
// The debugger tries to remap all modified methods, which requires presence of sequence points.
if (!_methodDefs.IsAddedNotChanged(def) && def.GetBody(Context)?.SequencePoints.Length > 0)
{
methods.Add(MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def)));
}
}
}
/// <summary>
/// Return tokens for all updated or added types.
/// </summary>
public void GetChangedTypeTokens(ArrayBuilder<TypeDefinitionHandle> types)
{
foreach (var def in _changedTypeDefs)
{
types.Add(GetTypeDefinitionHandle(def));
}
}
protected override ushort Generation
{
get { return (ushort)(_previousGeneration.Ordinal + 1); }
}
protected override Guid EncId
{
get { return _encId; }
}
protected override Guid EncBaseId
{
get { return _previousGeneration.EncId; }
}
protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def)
{
return MetadataTokens.EventDefinitionHandle(_eventDefs.GetRowId(def));
}
protected override IReadOnlyList<IEventDefinition> GetEventDefs()
{
return _eventDefs.GetRows();
}
protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def)
{
return MetadataTokens.FieldDefinitionHandle(_fieldDefs.GetRowId(def));
}
protected override IReadOnlyList<IFieldDefinition> GetFieldDefs()
{
return _fieldDefs.GetRows();
}
protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle)
{
bool result = _typeDefs.TryGetRowId(def, out int rowId);
handle = MetadataTokens.TypeDefinitionHandle(rowId);
return result;
}
protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def)
{
return MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(def));
}
protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle)
{
return _typeDefs.GetDefinition(MetadataTokens.GetRowNumber(handle));
}
protected override IReadOnlyList<ITypeDefinition> GetTypeDefs()
{
return _typeDefs.GetRows();
}
protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle)
{
bool result = _methodDefs.TryGetRowId(def, out int rowId);
handle = MetadataTokens.MethodDefinitionHandle(rowId);
return result;
}
protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def)
=> MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def));
protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle index)
=> _methodDefs.GetDefinition(MetadataTokens.GetRowNumber(index));
protected override IReadOnlyList<IMethodDefinition> GetMethodDefs()
=> _methodDefs.GetRows();
protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def)
=> MetadataTokens.PropertyDefinitionHandle(_propertyDefs.GetRowId(def));
protected override IReadOnlyList<IPropertyDefinition> GetPropertyDefs()
=> _propertyDefs.GetRows();
protected override ParameterHandle GetParameterHandle(IParameterDefinition def)
=> MetadataTokens.ParameterHandle(_parameterDefs.GetRowId(def));
protected override IReadOnlyList<IParameterDefinition> GetParameterDefs()
=> _parameterDefs.GetRows();
protected override IReadOnlyList<IGenericParameter> GetGenericParameters()
=> _genericParameters.GetRows();
// Fields are associated with the type through the EncLog table.
protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef)
=> default;
// Methods are associated with the type through the EncLog table.
protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef)
=> default;
// Parameters are associated with the method through the EncLog table.
protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef)
=> default;
protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference)
{
var identity = reference.Identity;
var versionPattern = reference.AssemblyVersionPattern;
if (versionPattern is not null)
{
RoslynDebug.AssertNotNull(_previousGeneration.InitialBaseline.LazyMetadataSymbols);
identity = _previousGeneration.InitialBaseline.LazyMetadataSymbols.AssemblyReferenceIdentityMap[identity.WithVersion(versionPattern)];
}
return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(identity));
}
protected override IReadOnlyList<AssemblyIdentity> GetAssemblyRefs()
{
return _assemblyRefIndex.Rows;
}
protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference)
{
return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<string> GetModuleRefs()
{
return _moduleRefIndex.Rows;
}
protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference)
{
return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeMemberReference> GetMemberRefs()
{
return _memberRefIndex.Rows;
}
protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference)
{
return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs()
{
return _methodSpecIndex.Rows;
}
protected override int GreatestMethodDefIndex => _methodDefs.NextRowId;
protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle)
{
int index;
bool result = _typeRefIndex.TryGetValue(reference, out index);
handle = MetadataTokens.TypeReferenceHandle(index);
return result;
}
protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference)
{
return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeRefs()
{
return _typeRefIndex.Rows;
}
protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference)
{
return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeSpecs()
{
return _typeSpecIndex.Rows;
}
protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex)
{
return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex));
}
protected override IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles()
{
return _standAloneSignatureIndex.Rows;
}
protected override void OnIndicesCreated()
{
var module = (IPEDeltaAssemblyBuilder)this.module;
module.OnCreatedIndices(this.Context.Diagnostics);
}
protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef)
{
var change = _changes.GetChange(typeDef);
switch (change)
{
case SymbolChange.Added:
_typeDefs.Add(typeDef);
_changedTypeDefs.Add(typeDef);
var typeParameters = this.GetConsolidatedTypeParameters(typeDef);
if (typeParameters != null)
{
foreach (var typeParameter in typeParameters)
{
_genericParameters.Add(typeParameter);
}
}
break;
case SymbolChange.Updated:
_typeDefs.AddUpdated(typeDef);
_changedTypeDefs.Add(typeDef);
break;
case SymbolChange.ContainsChanges:
// Members changed.
// We keep this list separately because we don't want to output duplicate typedef entries in the EnC log,
// which uses _typeDefs, but it's simpler to let the members output those rows for the updated typedefs
// with the right update type.
_changedTypeDefs.Add(typeDef);
break;
case SymbolChange.None:
// No changes to type.
return;
default:
throw ExceptionUtilities.UnexpectedValue(change);
}
int typeRowId = _typeDefs.GetRowId(typeDef);
foreach (var eventDef in typeDef.GetEvents(this.Context))
{
if (!_eventMap.Contains(typeRowId))
{
_eventMap.Add(typeRowId);
}
this.AddDefIfNecessary(_eventDefs, eventDef);
}
foreach (var fieldDef in typeDef.GetFields(this.Context))
{
this.AddDefIfNecessary(_fieldDefs, fieldDef);
}
foreach (var methodDef in typeDef.GetMethods(this.Context))
{
this.AddDefIfNecessary(_methodDefs, methodDef);
var methodChange = _changes.GetChange(methodDef);
if (methodChange == SymbolChange.Added)
{
_firstParamRowMap.Add(GetMethodDefinitionHandle(methodDef), _parameterDefs.NextRowId);
foreach (var paramDef in this.GetParametersToEmit(methodDef))
{
_parameterDefs.Add(paramDef);
_parameterDefList.Add(paramDef, methodDef);
}
}
else if (methodChange == SymbolChange.Updated)
{
// If we're re-emitting parameters for an existing method we need to find their original row numbers
// and reuse them so the EnCLog, EnCMap and CustomAttributes tables refer to the right rows
// Unfortunately we have to check the original metadata and deltas separately as nothing tracks the aggregate data
// in a way that we can use
var handle = GetMethodDefinitionHandle(methodDef);
if (_previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.MethodDef) >= MetadataTokens.GetRowNumber(handle))
{
EmitParametersFromOriginalMetadata(methodDef, handle);
}
else
{
EmitParametersFromDelta(methodDef, handle);
}
}
if (methodChange == SymbolChange.Added)
{
if (methodDef.GenericParameterCount > 0)
{
foreach (var typeParameter in methodDef.GenericParameters)
{
_genericParameters.Add(typeParameter);
}
}
}
}
foreach (var propertyDef in typeDef.GetProperties(this.Context))
{
if (!_propertyMap.Contains(typeRowId))
{
_propertyMap.Add(typeRowId);
}
this.AddDefIfNecessary(_propertyDefs, propertyDef);
}
var implementingMethods = ArrayBuilder<int>.GetInstance();
// First, visit all MethodImplementations and add to this.methodImplList.
foreach (var methodImpl in typeDef.GetExplicitImplementationOverrides(Context))
{
var methodDef = (IMethodDefinition?)methodImpl.ImplementingMethod.AsDefinition(this.Context);
RoslynDebug.AssertNotNull(methodDef);
int methodDefRowId = _methodDefs.GetRowId(methodDef);
// If there are N existing MethodImpl entries for this MethodDef,
// those will be index:1, ..., index:N, so it's sufficient to check for index:1.
var key = new MethodImplKey(methodDefRowId, index: 1);
if (!_methodImpls.Contains(key))
{
implementingMethods.Add(methodDefRowId);
this.methodImplList.Add(methodImpl);
}
}
// Next, add placeholders to this.methodImpls for items added above.
foreach (var methodDefIndex in implementingMethods)
{
int index = 1;
while (true)
{
var key = new MethodImplKey(methodDefIndex, index);
if (!_methodImpls.Contains(key))
{
_methodImpls.Add(key);
break;
}
index++;
}
}
implementingMethods.Free();
}
private void EmitParametersFromOriginalMetadata(IMethodDefinition methodDef, MethodDefinitionHandle handle)
{
var def = _previousGeneration.OriginalMetadata.MetadataReader.GetMethodDefinition(handle);
var parameters = def.GetParameters();
var paramDefinitions = this.GetParametersToEmit(methodDef);
int i = 0;
foreach (var param in parameters)
{
var paramDef = paramDefinitions[i];
_parameterDefs.AddUpdated(paramDef);
_existingParameterDefs.Add(paramDef, MetadataTokens.GetRowNumber(param));
_parameterDefList.Add(paramDef, methodDef);
i++;
}
}
private void EmitParametersFromDelta(IMethodDefinition methodDef, MethodDefinitionHandle handle)
{
var ok = _previousGeneration.FirstParamRowMap.TryGetValue(handle, out var firstRowId);
Debug.Assert(ok);
foreach (var paramDef in GetParametersToEmit(methodDef))
{
_parameterDefs.AddUpdated(paramDef);
_existingParameterDefs.Add(paramDef, firstRowId++);
_parameterDefList.Add(paramDef, methodDef);
}
}
private bool AddDefIfNecessary<T>(DefinitionIndex<T> defIndex, T def)
where T : class, IDefinition
{
switch (_changes.GetChange(def))
{
case SymbolChange.Added:
defIndex.Add(def);
return true;
case SymbolChange.Updated:
defIndex.AddUpdated(def);
return false;
case SymbolChange.ContainsChanges:
Debug.Assert(def is INestedTypeDefinition);
// Changes to members within nested type only.
return false;
default:
// No changes to member or container.
return false;
}
}
protected override ReferenceIndexer CreateReferenceVisitor()
{
return new DeltaReferenceIndexer(this);
}
protected override void ReportReferencesToAddedSymbols()
{
foreach (var typeRef in GetTypeRefs())
{
ReportReferencesToAddedSymbol(typeRef.GetInternalSymbol());
}
foreach (var memberRef in GetMemberRefs())
{
ReportReferencesToAddedSymbol(memberRef.GetInternalSymbol());
}
}
private void ReportReferencesToAddedSymbol(ISymbolInternal? symbol)
{
if (symbol != null && _changes.IsAdded(symbol.GetISymbol()))
{
Context.Diagnostics.Add(messageProvider.CreateDiagnostic(
messageProvider.ERR_EncReferenceToAddedMember,
GetSymbolLocation(symbol),
symbol.Name,
symbol.ContainingAssembly.Name));
}
}
protected override StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body)
{
StandaloneSignatureHandle localSignatureHandle;
var localVariables = body.LocalVariables;
var encInfos = ArrayBuilder<EncLocalInfo>.GetInstance();
if (localVariables.Length > 0)
{
var writer = PooledBlobBuilder.GetInstance();
var encoder = new BlobEncoder(writer).LocalVariableSignature(localVariables.Length);
foreach (ILocalDefinition local in localVariables)
{
var signature = local.Signature;
if (signature == null)
{
int start = writer.Count;
SerializeLocalVariableType(encoder.AddVariable(), local);
signature = writer.ToArray(start, writer.Count - start);
}
else
{
writer.WriteBytes(signature);
}
encInfos.Add(CreateEncLocalInfo(local, signature));
}
BlobHandle blobIndex = metadata.GetOrAddBlob(writer);
localSignatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex);
writer.Free();
}
else
{
localSignatureHandle = default;
}
var info = new AddedOrChangedMethodInfo(
body.MethodId,
encInfos.ToImmutable(),
body.LambdaDebugInfo,
body.ClosureDebugInfo,
body.StateMachineTypeName,
body.StateMachineHoistedLocalSlots,
body.StateMachineAwaiterSlots);
_addedOrChangedMethods.Add(body.MethodDefinition, info);
encInfos.Free();
return localSignatureHandle;
}
private EncLocalInfo CreateEncLocalInfo(ILocalDefinition localDef, byte[] signature)
{
if (localDef.SlotInfo.Id.IsNone)
{
return new EncLocalInfo(signature);
}
// local type is already translated, but not recursively
ITypeReference translatedType = localDef.Type;
if (translatedType.GetInternalSymbol() is ITypeSymbolInternal typeSymbol)
{
translatedType = Context.Module.EncTranslateType(typeSymbol, Context.Diagnostics);
}
return new EncLocalInfo(localDef.SlotInfo, translatedType, localDef.Constraints, signature);
}
protected override int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes)
{
// The base class will write out the actual metadata for us
var numAttributesEmitted = base.AddCustomAttributesToTable(parentHandle, attributes);
// We need to keep track of all of the things attributes could be associated with in this delta, in order to populate the EncLog and Map tables
_customAttributeParentCounts.Add(parentHandle, numAttributesEmitted);
return numAttributesEmitted;
}
public override void PopulateEncTables(ImmutableArray<int> typeSystemRowCounts)
{
Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncLog] == 0);
Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncMap] == 0);
PopulateEncLogTableRows(typeSystemRowCounts, out var customAttributeEncMapRows, out var paramEncMapRows);
PopulateEncMapTableRows(typeSystemRowCounts, customAttributeEncMapRows, paramEncMapRows);
}
private void PopulateEncLogTableRows(ImmutableArray<int> rowCounts, out List<int> customAttributeEncMapRows, out List<int> paramEncMapRows)
{
// The EncLog table is a log of all the operations needed
// to update the previous metadata. That means all
// new references must be added to the EncLog.
var previousSizes = _previousGeneration.TableSizes;
var deltaSizes = this.GetDeltaTableSizes(rowCounts);
PopulateEncLogTableRows(TableIndex.AssemblyRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ModuleRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MemberRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodSpec, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.TypeRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.TypeSpec, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.StandAloneSig, previousSizes, deltaSizes);
PopulateEncLogTableRows(_typeDefs, TableIndex.TypeDef);
PopulateEncLogTableRows(TableIndex.EventMap, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.PropertyMap, previousSizes, deltaSizes);
PopulateEncLogTableEventsOrProperties(_eventDefs, TableIndex.Event, EditAndContinueOperation.AddEvent, _eventMap, TableIndex.EventMap);
PopulateEncLogTableFieldsOrMethods(_fieldDefs, TableIndex.Field, EditAndContinueOperation.AddField);
PopulateEncLogTableFieldsOrMethods(_methodDefs, TableIndex.MethodDef, EditAndContinueOperation.AddMethod);
PopulateEncLogTableEventsOrProperties(_propertyDefs, TableIndex.Property, EditAndContinueOperation.AddProperty, _propertyMap, TableIndex.PropertyMap);
PopulateEncLogTableParameters(out paramEncMapRows);
PopulateEncLogTableRows(TableIndex.Constant, previousSizes, deltaSizes);
PopulateEncLogTableCustomAttributes(out customAttributeEncMapRows);
PopulateEncLogTableRows(TableIndex.DeclSecurity, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ClassLayout, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.FieldLayout, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodSemantics, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodImpl, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ImplMap, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.FieldRva, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.NestedClass, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.GenericParam, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.InterfaceImpl, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.GenericParamConstraint, previousSizes, deltaSizes);
}
private void PopulateEncLogTableEventsOrProperties<T>(
DefinitionIndex<T> index,
TableIndex table,
EditAndContinueOperation addCode,
EventOrPropertyMapIndex map,
TableIndex mapTable)
where T : class, ITypeDefinitionMember
{
foreach (var member in index.GetRows())
{
if (index.IsAddedNotChanged(member))
{
int typeRowId = MetadataTokens.GetRowNumber(GetTypeDefinitionHandle(member.ContainingTypeDefinition));
int mapRowId = map.GetRowId(typeRowId);
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(mapTable, mapRowId),
code: addCode);
}
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(table, index.GetRowId(member)),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableFieldsOrMethods<T>(
DefinitionIndex<T> index,
TableIndex tableIndex,
EditAndContinueOperation addCode)
where T : class, ITypeDefinitionMember
{
foreach (var member in index.GetRows())
{
if (index.IsAddedNotChanged(member))
{
metadata.AddEncLogEntry(
entity: GetTypeDefinitionHandle(member.ContainingTypeDefinition),
code: addCode);
}
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableParameters(out List<int> paramEncMapRows)
{
paramEncMapRows = new List<int>();
var parameterFirstId = _parameterDefs.FirstRowId;
int i = 0;
foreach (var paramDef in GetParameterDefs())
{
var methodDef = _parameterDefList[paramDef];
if (_methodDefs.IsAddedNotChanged(methodDef))
{
// For parameters on new methods we emit AddParameter rows for the method too
paramEncMapRows.Add(parameterFirstId + i);
metadata.AddEncLogEntry(
entity: MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(methodDef)),
code: EditAndContinueOperation.AddParameter);
metadata.AddEncLogEntry(
entity: MetadataTokens.ParameterHandle(parameterFirstId + i),
code: EditAndContinueOperation.Default);
i++;
}
else
{
// For previously emitted parameters we just update the Param row
var param = GetParameterHandle(paramDef);
paramEncMapRows.Add(MetadataTokens.GetRowNumber(param));
metadata.AddEncLogEntry(
entity: param,
code: EditAndContinueOperation.Default);
}
}
}
/// <summary>
/// CustomAttributes point to their target via the Parent column so we cannot simply output new rows
/// in the delta or we would end up with duplicates, but we also don't want to do complex logic to determine
/// which attributes have changes, so we just emit them all.
/// This means our logic for emitting CustomAttributes is to update any existing rows, either from the original
/// compilation or subsequent deltas, and only add more if we need to. The EncLog table is the thing that tells
/// the runtime which row a CustomAttributes row is (ie, new or existing)
/// </summary>
private void PopulateEncLogTableCustomAttributes(out List<int> customAttributeEncMapRows)
{
customAttributeEncMapRows = new List<int>();
// List of attributes that need to be emitted to delete a previously emitted attribute
var deletedAttributeRows = new List<(int parentRowId, HandleKind kind)>();
var customAttributesAdded = new Dictionary<EntityHandle, ArrayBuilder<int>>();
// The data in _previousGeneration.CustomAttributesAdded is not nicely sorted, or even necessarily contiguous
// so we need to map each target onto the rows its attributes occupy so we know which rows to update
var lastRowId = _previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.CustomAttribute);
if (_previousGeneration.CustomAttributesAdded.Count > 0)
{
lastRowId = _previousGeneration.CustomAttributesAdded.SelectMany(s => s.Value).Max();
}
// Iterate through the parents we emitted custom attributes for, in parent order
foreach (var (parent, count) in _customAttributeParentCounts.OrderBy(kvp => CodedIndex.HasCustomAttribute(kvp.Key)))
{
int index = 0;
// First we try to update any existing attributes.
// GetCustomAttributes does a binary search, so is fast. We presume that the number of rows in the original metadata
// greatly outnumbers the amount of parents emitted in this delta so even with repeated searches this is still
// quicker than iterating the entire original table, even once.
var existingCustomAttributes = _previousGeneration.OriginalMetadata.MetadataReader.GetCustomAttributes(parent);
foreach (var attributeHandle in existingCustomAttributes)
{
int rowId = MetadataTokens.GetRowNumber(attributeHandle);
AddLogEntryOrDelete(rowId, parent, add: index < count, customAttributeEncMapRows);
index++;
}
// If we emitted any attributes for this parent in previous deltas then we either need to update
// them next, or delete them if necessary
if (_previousGeneration.CustomAttributesAdded.TryGetValue(parent, out var rowIds))
{
foreach (var rowId in rowIds)
{
TrackCustomAttributeAdded(rowId, parent);
AddLogEntryOrDelete(rowId, parent, add: index < count, customAttributeEncMapRows);
index++;
}
}
// Finally if there are still attributes for this parent left, they are additions new to this delta
for (int i = index; i < count; i++)
{
lastRowId++;
TrackCustomAttributeAdded(lastRowId, parent);
AddEncLogEntry(lastRowId, customAttributeEncMapRows);
}
}
// Save the attributes we've emitted, and the ones from previous deltas, for use in the next generation
foreach (var (parent, rowIds) in customAttributesAdded)
{
_customAttributesAdded.Add(parent, rowIds.ToImmutableAndFree());
}
// Add attributes and log entries for everything we've deleted
foreach (var row in deletedAttributeRows)
{
// now emit a "delete" row with a parent that is for the 0 row of the same table as the existing one
if (!MetadataTokens.TryGetTableIndex(row.kind, out var tableIndex))
{
throw new InvalidOperationException("Trying to delete a custom attribute for a parent kind that doesn't have a matching table index.");
}
metadata.AddCustomAttribute(MetadataTokens.Handle(tableIndex, 0), MetadataTokens.EntityHandle(TableIndex.MemberRef, 0), value: default);
AddEncLogEntry(row.parentRowId, customAttributeEncMapRows);
}
void AddEncLogEntry(int rowId, List<int> customAttributeEncMapRows)
{
customAttributeEncMapRows.Add(rowId);
metadata.AddEncLogEntry(
entity: MetadataTokens.CustomAttributeHandle(rowId),
code: EditAndContinueOperation.Default);
}
void AddLogEntryOrDelete(int rowId, EntityHandle parent, bool add, List<int> customAttributeEncMapRows)
{
if (add)
{
// Update this row
AddEncLogEntry(rowId, customAttributeEncMapRows);
}
else
{
// Delete this row
deletedAttributeRows.Add((rowId, parent.Kind));
}
}
void TrackCustomAttributeAdded(int nextRowId, EntityHandle parent)
{
if (!customAttributesAdded.TryGetValue(parent, out var existing))
{
existing = ArrayBuilder<int>.GetInstance();
customAttributesAdded.Add(parent, existing);
}
existing.Add(nextRowId);
}
}
private void PopulateEncLogTableRows<T>(DefinitionIndex<T> index, TableIndex tableIndex)
where T : class, IDefinition
{
foreach (var member in index.GetRows())
{
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableRows(TableIndex tableIndex, ImmutableArray<int> previousSizes, ImmutableArray<int> deltaSizes)
{
PopulateEncLogTableRows(tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]);
}
private void PopulateEncLogTableRows(TableIndex tableIndex, int firstRowId, int tokenCount)
{
for (int i = 0; i < tokenCount; i++)
{
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, firstRowId + i),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncMapTableRows(ImmutableArray<int> rowCounts, List<int> customAttributeEncMapRows, List<int> paramEncMapRows)
{
// The EncMap table maps from offset in each table in the delta
// metadata to token. As such, the EncMap is a concatenated
// list of all tokens in all tables from the delta sorted by table
// and, within each table, sorted by row.
var tokens = ArrayBuilder<EntityHandle>.GetInstance();
var previousSizes = _previousGeneration.TableSizes;
var deltaSizes = this.GetDeltaTableSizes(rowCounts);
AddReferencedTokens(tokens, TableIndex.AssemblyRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ModuleRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MemberRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodSpec, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.TypeRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.TypeSpec, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.StandAloneSig, previousSizes, deltaSizes);
AddDefinitionTokens(tokens, _typeDefs, TableIndex.TypeDef);
AddDefinitionTokens(tokens, _eventDefs, TableIndex.Event);
AddDefinitionTokens(tokens, _fieldDefs, TableIndex.Field);
AddDefinitionTokens(tokens, _methodDefs, TableIndex.MethodDef);
AddDefinitionTokens(tokens, _propertyDefs, TableIndex.Property);
AddRowNumberTokens(tokens, paramEncMapRows, TableIndex.Param);
AddReferencedTokens(tokens, TableIndex.Constant, previousSizes, deltaSizes);
AddRowNumberTokens(tokens, customAttributeEncMapRows, TableIndex.CustomAttribute);
AddReferencedTokens(tokens, TableIndex.DeclSecurity, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ClassLayout, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.FieldLayout, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.EventMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.PropertyMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodSemantics, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodImpl, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ImplMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.FieldRva, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.NestedClass, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.GenericParam, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.InterfaceImpl, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.GenericParamConstraint, previousSizes, deltaSizes);
tokens.Sort(HandleComparer.Default);
// Should not be any duplicates.
Debug.Assert(tokens.Distinct().Count() == tokens.Count);
foreach (var token in tokens)
{
metadata.AddEncMapEntry(token);
}
tokens.Free();
// Populate Portable PDB EncMap table with MethodDebugInformation mapping,
// which corresponds 1:1 to MethodDef mapping.
if (_debugMetadataOpt != null)
{
var debugTokens = ArrayBuilder<EntityHandle>.GetInstance();
AddDefinitionTokens(debugTokens, _methodDefs, TableIndex.MethodDebugInformation);
debugTokens.Sort(HandleComparer.Default);
// Should not be any duplicates.
Debug.Assert(debugTokens.Distinct().Count() == debugTokens.Count);
foreach (var token in debugTokens)
{
_debugMetadataOpt.AddEncMapEntry(token);
}
debugTokens.Free();
}
#if DEBUG
// The following tables are either represented in the EncMap
// or specifically ignored. The rest should be empty.
var handledTables = new TableIndex[]
{
TableIndex.Module,
TableIndex.TypeRef,
TableIndex.TypeDef,
TableIndex.Field,
TableIndex.MethodDef,
TableIndex.Param,
TableIndex.MemberRef,
TableIndex.Constant,
TableIndex.CustomAttribute,
TableIndex.DeclSecurity,
TableIndex.ClassLayout,
TableIndex.FieldLayout,
TableIndex.StandAloneSig,
TableIndex.EventMap,
TableIndex.Event,
TableIndex.PropertyMap,
TableIndex.Property,
TableIndex.MethodSemantics,
TableIndex.MethodImpl,
TableIndex.ModuleRef,
TableIndex.TypeSpec,
TableIndex.ImplMap,
// FieldRva is not needed since we only emit fields with explicit mapping
// for <PrivateImplementationDetails> and that class is not used in ENC.
// If we need FieldRva in the future, we'll need a corresponding test.
// (See EditAndContinueTests.FieldRva that was deleted in this change.)
//TableIndex.FieldRva,
TableIndex.EncLog,
TableIndex.EncMap,
TableIndex.Assembly,
TableIndex.AssemblyRef,
TableIndex.MethodSpec,
TableIndex.NestedClass,
TableIndex.GenericParam,
TableIndex.InterfaceImpl,
TableIndex.GenericParamConstraint,
};
for (int i = 0; i < rowCounts.Length; i++)
{
if (handledTables.Contains((TableIndex)i))
{
continue;
}
Debug.Assert(rowCounts[i] == 0);
}
#endif
}
private static void AddReferencedTokens(
ArrayBuilder<EntityHandle> builder,
TableIndex tableIndex,
ImmutableArray<int> previousSizes,
ImmutableArray<int> deltaSizes)
{
AddReferencedTokens(builder, tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]);
}
private static void AddReferencedTokens(ArrayBuilder<EntityHandle> builder, TableIndex tableIndex, int firstRowId, int nTokens)
{
for (int i = 0; i < nTokens; i++)
{
builder.Add(MetadataTokens.Handle(tableIndex, firstRowId + i));
}
}
private static void AddDefinitionTokens<T>(ArrayBuilder<EntityHandle> tokens, DefinitionIndex<T> index, TableIndex tableIndex)
where T : class, IDefinition
{
foreach (var member in index.GetRows())
{
tokens.Add(MetadataTokens.Handle(tableIndex, index.GetRowId(member)));
}
}
private static void AddRowNumberTokens(ArrayBuilder<EntityHandle> tokens, IEnumerable<int> rowNumbers, TableIndex tableIndex)
{
foreach (var row in rowNumbers)
{
tokens.Add(MetadataTokens.Handle(tableIndex, row));
}
}
protected override void PopulateEventMapTableRows()
{
foreach (var typeId in _eventMap.GetRows())
{
metadata.AddEventMap(
declaringType: MetadataTokens.TypeDefinitionHandle(typeId),
eventList: MetadataTokens.EventDefinitionHandle(_eventMap.GetRowId(typeId)));
}
}
protected override void PopulatePropertyMapTableRows()
{
foreach (var typeId in _propertyMap.GetRows())
{
metadata.AddPropertyMap(
declaringType: MetadataTokens.TypeDefinitionHandle(typeId),
propertyList: MetadataTokens.PropertyDefinitionHandle(_propertyMap.GetRowId(typeId)));
}
}
private abstract class DefinitionIndexBase<T>
where T : notnull
{
protected readonly Dictionary<T, int> added; // Definitions added in this generation.
protected readonly List<T> rows; // Rows in this generation, containing adds and updates.
private readonly int _firstRowId; // First row in this generation.
private bool _frozen;
public DefinitionIndexBase(int lastRowId, IEqualityComparer<T>? comparer = null)
{
this.added = new Dictionary<T, int>(comparer);
this.rows = new List<T>();
_firstRowId = lastRowId + 1;
}
public abstract bool TryGetRowId(T item, out int rowId);
public int GetRowId(T item)
{
bool containsItem = TryGetRowId(item, out int rowId);
// Fails if we are attempting to make a change that should have been reported as rude,
// e.g. the corresponding definitions type don't match, etc.
Debug.Assert(containsItem);
Debug.Assert(rowId > 0);
return rowId;
}
public bool Contains(T item)
=> TryGetRowId(item, out _);
// A method rather than a property since it freezes the table.
public IReadOnlyDictionary<T, int> GetAdded()
{
this.Freeze();
return this.added;
}
// A method rather than a property since it freezes the table.
public IReadOnlyList<T> GetRows()
{
this.Freeze();
return this.rows;
}
public int FirstRowId
{
get { return _firstRowId; }
}
public int NextRowId
{
get { return this.added.Count + _firstRowId; }
}
public bool IsFrozen
{
get { return _frozen; }
}
protected virtual void OnFrozen()
{
#if DEBUG
// Verify the rows are sorted.
int prev = 0;
foreach (var row in this.rows)
{
int next = this.added[row];
Debug.Assert(prev < next);
prev = next;
}
#endif
}
private void Freeze()
{
if (!_frozen)
{
_frozen = true;
this.OnFrozen();
}
}
}
private sealed class DefinitionIndex<T> : DefinitionIndexBase<T> where T : class, IDefinition
{
public delegate bool TryGetExistingIndex(T item, out int index);
private readonly TryGetExistingIndex _tryGetExistingIndex;
// Map of row id to def for all defs. This could be an array indexed
// by row id but the array could be large and sparsely populated
// if there are many defs in the previous generation but few
// references to those defs in the current generation.
private readonly Dictionary<int, T> _map;
public DefinitionIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
_tryGetExistingIndex = tryGetExistingIndex;
_map = new Dictionary<int, T>();
}
public override bool TryGetRowId(T item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_tryGetExistingIndex(item, out index))
{
#if DEBUG
Debug.Assert(!_map.TryGetValue(index, out var other) || ((object)other == (object)item));
#endif
_map[index] = item;
return true;
}
return false;
}
public T GetDefinition(int rowId)
=> _map[rowId];
public void Add(T item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
_map[index] = item;
this.rows.Add(item);
}
/// <summary>
/// Add an item from a previous generation
/// that has been updated in this generation.
/// </summary>
public void AddUpdated(T item)
{
Debug.Assert(!this.IsFrozen);
this.rows.Add(item);
}
public bool IsAddedNotChanged(T item)
=> added.ContainsKey(item);
protected override void OnFrozen()
=> rows.Sort((x, y) => GetRowId(x).CompareTo(GetRowId(y)));
}
private bool TryGetExistingTypeDefIndex(ITypeDefinition item, out int index)
{
if (_previousGeneration.TypesAdded.TryGetValue(item, out index))
{
return true;
}
TypeDefinitionHandle handle;
if (_definitionMap.TryGetTypeHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingEventDefIndex(IEventDefinition item, out int index)
{
if (_previousGeneration.EventsAdded.TryGetValue(item, out index))
{
return true;
}
EventDefinitionHandle handle;
if (_definitionMap.TryGetEventHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingFieldDefIndex(IFieldDefinition item, out int index)
{
if (_previousGeneration.FieldsAdded.TryGetValue(item, out index))
{
return true;
}
FieldDefinitionHandle handle;
if (_definitionMap.TryGetFieldHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingMethodDefIndex(IMethodDefinition item, out int index)
{
if (_previousGeneration.MethodsAdded.TryGetValue(item, out index))
{
return true;
}
MethodDefinitionHandle handle;
if (_definitionMap.TryGetMethodHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingPropertyDefIndex(IPropertyDefinition item, out int index)
{
if (_previousGeneration.PropertiesAdded.TryGetValue(item, out index))
{
return true;
}
PropertyDefinitionHandle handle;
if (_definitionMap.TryGetPropertyHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingParameterDefIndex(IParameterDefinition item, out int index)
{
return _existingParameterDefs.TryGetValue(item, out index);
}
private bool TryGetExistingEventMapIndex(int item, out int index)
{
if (_previousGeneration.EventMapAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.TypeToEventMap.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private bool TryGetExistingPropertyMapIndex(int item, out int index)
{
if (_previousGeneration.PropertyMapAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.TypeToPropertyMap.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private bool TryGetExistingMethodImplIndex(MethodImplKey item, out int index)
{
if (_previousGeneration.MethodImplsAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.MethodImpls.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private sealed class GenericParameterIndex : DefinitionIndexBase<IGenericParameter>
{
public GenericParameterIndex(int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
}
public override bool TryGetRowId(IGenericParameter item, out int index)
{
return this.added.TryGetValue(item, out index);
}
public void Add(IGenericParameter item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class EventOrPropertyMapIndex : DefinitionIndexBase<int>
{
public delegate bool TryGetExistingIndex(int item, out int index);
private readonly TryGetExistingIndex _tryGetExistingIndex;
public EventOrPropertyMapIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId)
: base(lastRowId)
{
_tryGetExistingIndex = tryGetExistingIndex;
}
public override bool TryGetRowId(int item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_tryGetExistingIndex(item, out index))
{
return true;
}
index = 0;
return false;
}
public void Add(int item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class MethodImplIndex : DefinitionIndexBase<MethodImplKey>
{
private readonly DeltaMetadataWriter _writer;
public MethodImplIndex(DeltaMetadataWriter writer, int lastRowId)
: base(lastRowId)
{
_writer = writer;
}
public override bool TryGetRowId(MethodImplKey item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_writer.TryGetExistingMethodImplIndex(item, out index))
{
return true;
}
index = 0;
return false;
}
public void Add(MethodImplKey item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class DeltaReferenceIndexer : ReferenceIndexer
{
private readonly SymbolChanges _changes;
public DeltaReferenceIndexer(DeltaMetadataWriter writer)
: base(writer)
{
_changes = writer._changes;
}
public override void Visit(CommonPEModuleBuilder module)
{
Visit(module.GetTopLevelTypeDefinitions(metadataWriter.Context));
}
public override void Visit(IEventDefinition eventDefinition)
{
Debug.Assert(this.ShouldVisit(eventDefinition));
base.Visit(eventDefinition);
}
public override void Visit(IFieldDefinition fieldDefinition)
{
Debug.Assert(this.ShouldVisit(fieldDefinition));
base.Visit(fieldDefinition);
}
public override void Visit(ILocalDefinition localDefinition)
{
if (localDefinition.Signature == null)
{
base.Visit(localDefinition);
}
}
public override void Visit(IMethodDefinition method)
{
Debug.Assert(this.ShouldVisit(method));
base.Visit(method);
}
public override void Visit(Cci.MethodImplementation methodImplementation)
{
// Unless the implementing method was added,
// the method implementation already exists.
var methodDef = (IMethodDefinition?)methodImplementation.ImplementingMethod.AsDefinition(this.Context);
RoslynDebug.AssertNotNull(methodDef);
if (_changes.GetChange(methodDef) == SymbolChange.Added)
{
base.Visit(methodImplementation);
}
}
public override void Visit(INamespaceTypeDefinition namespaceTypeDefinition)
{
Debug.Assert(this.ShouldVisit(namespaceTypeDefinition));
base.Visit(namespaceTypeDefinition);
}
public override void Visit(INestedTypeDefinition nestedTypeDefinition)
{
Debug.Assert(this.ShouldVisit(nestedTypeDefinition));
base.Visit(nestedTypeDefinition);
}
public override void Visit(IPropertyDefinition propertyDefinition)
{
Debug.Assert(this.ShouldVisit(propertyDefinition));
base.Visit(propertyDefinition);
}
public override void Visit(ITypeDefinition typeDefinition)
{
if (this.ShouldVisit(typeDefinition))
{
base.Visit(typeDefinition);
}
}
public override void Visit(ITypeDefinitionMember typeMember)
{
if (this.ShouldVisit(typeMember))
{
base.Visit(typeMember);
}
}
private bool ShouldVisit(IDefinition def)
{
return _changes.GetChange(def) != SymbolChange.None;
}
}
}
}
| 1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/Core/Portable/Emit/EditAndContinue/SymbolChanges.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.Cci;
using Roslyn.Utilities;
using System.Collections.Generic;
using System.Diagnostics;
using System;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit
{
internal abstract class SymbolChanges
{
/// <summary>
/// Maps definitions being emitted to the corresponding definitions defined in the previous generation (metadata or source).
/// </summary>
private readonly DefinitionMap _definitionMap;
/// <summary>
/// Contains all symbols explicitly updated/added to the source and
/// their containing types and namespaces.
/// </summary>
private readonly IReadOnlyDictionary<ISymbol, SymbolChange> _changes;
/// <summary>
/// A set of symbols whose name emitted to metadata must include a "#{generation}" suffix to avoid naming collisions with existing types.
/// Populated based on semantic edits with <see cref="SemanticEditKind.Replace"/>.
/// </summary>
private readonly ISet<ISymbol> _replacedSymbols;
private readonly Func<ISymbol, bool> _isAddedSymbol;
protected SymbolChanges(DefinitionMap definitionMap, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol)
{
_definitionMap = definitionMap;
_isAddedSymbol = isAddedSymbol;
CalculateChanges(edits, out _changes, out _replacedSymbols);
}
public DefinitionMap DefinitionMap => _definitionMap;
public bool IsReplaced(IDefinition definition)
{
var symbol = definition.GetInternalSymbol();
return symbol is not null && _replacedSymbols.Contains(symbol.GetISymbol());
}
/// <summary>
/// True if the symbol is a source symbol added during EnC session.
/// The symbol may be declared in any source compilation in the current solution.
/// </summary>
public bool IsAdded(ISymbol symbol)
{
return _isAddedSymbol(symbol);
}
/// <summary>
/// Returns true if the symbol or some child symbol has changed and needs to be compiled.
/// </summary>
public bool RequiresCompilation(ISymbol symbol)
{
return this.GetChange(symbol) != SymbolChange.None;
}
public SymbolChange GetChange(IDefinition def)
{
var symbol = def.GetInternalSymbol();
if (symbol is ISynthesizedMethodBodyImplementationSymbol synthesizedDef)
{
RoslynDebug.Assert(synthesizedDef.Method != null);
var generator = synthesizedDef.Method;
ISymbolInternal synthesizedSymbol = synthesizedDef;
var change = GetChange((IDefinition)generator.GetCciAdapter());
switch (change)
{
case SymbolChange.Updated:
// The generator has been updated. Some synthesized members should be reused, others updated or added.
// The container of the synthesized symbol doesn't exist, we need to add the symbol.
// This may happen e.g. for members of a state machine type when a non-iterator method is changed to an iterator.
if (!_definitionMap.DefinitionExists((IDefinition)synthesizedSymbol.ContainingType.GetCciAdapter()))
{
return SymbolChange.Added;
}
if (!_definitionMap.DefinitionExists(def))
{
// A method was changed to a method containing a lambda, to an iterator, or to an async method.
// The state machine or closure class has been added.
return SymbolChange.Added;
}
// The existing symbol should be reused when the generator is updated,
// not updated since it's form doesn't depend on the content of the generator.
// For example, when an iterator method changes all methods that implement IEnumerable
// but MoveNext can be reused as they are.
if (!synthesizedDef.HasMethodBodyDependency)
{
return SymbolChange.None;
}
// If the type produced from the method body existed before then its members are updated.
if (synthesizedSymbol.Kind == SymbolKind.NamedType)
{
return SymbolChange.ContainsChanges;
}
if (synthesizedSymbol.Kind == SymbolKind.Method)
{
// The method body might have been updated.
return SymbolChange.Updated;
}
return SymbolChange.None;
case SymbolChange.Added:
// The method has been added - add the synthesized member as well, unless they already exist.
if (!_definitionMap.DefinitionExists(def))
{
return SymbolChange.Added;
}
// If the existing member is a type we need to add new members into it.
// An example is a shared static display class - an added method with static lambda will contribute
// the lambda and cache fields into the shared display class.
if (synthesizedSymbol.Kind == SymbolKind.NamedType)
{
return SymbolChange.ContainsChanges;
}
// Update method.
// An example is a constructor a shared display class - an added method with lambda will contribute
// cache field initialization code into the constructor.
if (synthesizedSymbol.Kind == SymbolKind.Method)
{
return SymbolChange.Updated;
}
// Otherwise, there is nothing to do.
// For example, a static lambda display class cache field.
return SymbolChange.None;
default:
// The method had to change, otherwise the synthesized symbol wouldn't be generated
throw ExceptionUtilities.UnexpectedValue(change);
}
}
if (symbol is object)
{
return GetChange(symbol.GetISymbol());
}
// If the def existed in the previous generation, the def is unchanged
// (although it may contain changed defs); otherwise, it was added.
if (_definitionMap.DefinitionExists(def))
{
return (def is ITypeDefinition) ? SymbolChange.ContainsChanges : SymbolChange.None;
}
return SymbolChange.Added;
}
private SymbolChange GetChange(ISymbol symbol)
{
if (_changes.TryGetValue(symbol, out var change))
{
return change;
}
// Calculate change based on change to container.
var container = GetContainingSymbol(symbol);
if (container == null)
{
return SymbolChange.None;
}
var containerChange = GetChange(container);
switch (containerChange)
{
case SymbolChange.Added:
// If container is added then all its members have been added.
return SymbolChange.Added;
case SymbolChange.None:
// If container has no changes then none of its members have any changes.
return SymbolChange.None;
case SymbolChange.Updated:
case SymbolChange.ContainsChanges:
var adapter = GetISymbolInternalOrNull(symbol)?.GetCciAdapter();
if (adapter is IDefinition definition)
{
// If the definition did not exist in the previous generation, it was added.
return _definitionMap.DefinitionExists(definition) ? SymbolChange.None : SymbolChange.Added;
}
if (adapter is INamespace @namespace)
{
// If the namespace did not exist in the previous generation, it was added.
// Otherwise the namespace may contain changes.
return _definitionMap.NamespaceExists(@namespace) ? SymbolChange.ContainsChanges : SymbolChange.Added;
}
return SymbolChange.None;
default:
throw ExceptionUtilities.UnexpectedValue(containerChange);
}
}
protected abstract ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol);
public IEnumerable<INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context)
{
foreach (var symbol in _changes.Keys)
{
var namespaceTypeDef = (GetISymbolInternalOrNull(symbol)?.GetCciAdapter() as ITypeDefinition)?.AsNamespaceTypeDefinition(context);
if (namespaceTypeDef != null)
{
yield return namespaceTypeDef;
}
}
}
/// <summary>
/// Calculate the set of changes up to top-level types. The result
/// will be used as a filter when traversing the module.
///
/// Note that these changes only include user-defined source symbols, not synthesized symbols since those will be
/// generated during lowering of the changed user-defined symbols.
/// </summary>
private static void CalculateChanges(IEnumerable<SemanticEdit> edits, out IReadOnlyDictionary<ISymbol, SymbolChange> changes, out ISet<ISymbol> replaceSymbols)
{
var changesBuilder = new Dictionary<ISymbol, SymbolChange>();
HashSet<ISymbol>? lazyReplaceSymbolsBuilder = null;
foreach (var edit in edits)
{
SymbolChange change;
switch (edit.Kind)
{
case SemanticEditKind.Update:
change = SymbolChange.Updated;
break;
case SemanticEditKind.Insert:
change = SymbolChange.Added;
break;
case SemanticEditKind.Replace:
Debug.Assert(edit.NewSymbol != null);
(lazyReplaceSymbolsBuilder ??= new HashSet<ISymbol>()).Add(edit.NewSymbol);
change = SymbolChange.Added;
break;
case SemanticEditKind.Delete:
// No work to do.
continue;
default:
throw ExceptionUtilities.UnexpectedValue(edit.Kind);
}
var member = edit.NewSymbol;
RoslynDebug.AssertNotNull(member);
// Partial methods are supplied as implementations but recorded
// internally as definitions since definitions are used in emit.
if (member.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)member;
// Partial methods should be implementations, not definitions.
Debug.Assert(method.PartialImplementationPart == null);
Debug.Assert((edit.OldSymbol == null) || (((IMethodSymbol)edit.OldSymbol).PartialImplementationPart == null));
var definitionPart = method.PartialDefinitionPart;
if (definitionPart != null)
{
member = definitionPart;
}
}
AddContainingTypesAndNamespaces(changesBuilder, member);
changesBuilder.Add(member, change);
}
changes = changesBuilder;
replaceSymbols = lazyReplaceSymbolsBuilder ?? SpecializedCollections.EmptySet<ISymbol>();
}
private static void AddContainingTypesAndNamespaces(Dictionary<ISymbol, SymbolChange> changes, ISymbol symbol)
{
while (true)
{
var containingSymbol = GetContainingSymbol(symbol);
if (containingSymbol == null || changes.ContainsKey(containingSymbol))
{
return;
}
var change = containingSymbol.Kind is SymbolKind.Property or SymbolKind.Event ?
SymbolChange.Updated : SymbolChange.ContainsChanges;
changes.Add(containingSymbol, change);
symbol = containingSymbol;
}
}
/// <summary>
/// Return the symbol that contains this symbol as far
/// as changes are concerned. For instance, an auto property
/// is considered the containing symbol for the backing
/// field and the accessor methods. By default, the containing
/// symbol is simply Symbol.ContainingSymbol.
/// </summary>
private static ISymbol? GetContainingSymbol(ISymbol symbol)
{
// This approach of walking up the symbol hierarchy towards the
// root, rather than walking down to the leaf symbols, seems
// unreliable. It may be better to walk down using the usual
// emit traversal, but prune the traversal to those types and
// members that are known to contain changes.
switch (symbol.Kind)
{
case SymbolKind.Field:
{
var associated = ((IFieldSymbol)symbol).AssociatedSymbol;
if (associated != null)
{
return associated;
}
}
break;
case SymbolKind.Method:
{
var associated = ((IMethodSymbol)symbol).AssociatedSymbol;
if (associated != null)
{
return associated;
}
}
break;
}
symbol = symbol.ContainingSymbol;
if (symbol != null)
{
switch (symbol.Kind)
{
case SymbolKind.NetModule:
case SymbolKind.Assembly:
// These symbols are never part of the changes collection.
return null;
}
}
return 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.
using Microsoft.Cci;
using Roslyn.Utilities;
using System.Collections.Generic;
using System.Diagnostics;
using System;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit
{
internal abstract class SymbolChanges
{
/// <summary>
/// Maps definitions being emitted to the corresponding definitions defined in the previous generation (metadata or source).
/// </summary>
private readonly DefinitionMap _definitionMap;
/// <summary>
/// Contains all symbols explicitly updated/added to the source and
/// their containing types and namespaces.
/// </summary>
private readonly IReadOnlyDictionary<ISymbol, SymbolChange> _changes;
/// <summary>
/// A set of symbols whose name emitted to metadata must include a "#{generation}" suffix to avoid naming collisions with existing types.
/// Populated based on semantic edits with <see cref="SemanticEditKind.Replace"/>.
/// </summary>
private readonly ISet<ISymbol> _replacedSymbols;
private readonly Func<ISymbol, bool> _isAddedSymbol;
protected SymbolChanges(DefinitionMap definitionMap, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol)
{
_definitionMap = definitionMap;
_isAddedSymbol = isAddedSymbol;
CalculateChanges(edits, out _changes, out _replacedSymbols);
}
public DefinitionMap DefinitionMap => _definitionMap;
public bool IsReplaced(IDefinition definition)
{
var symbol = definition.GetInternalSymbol();
return symbol is not null && _replacedSymbols.Contains(symbol.GetISymbol());
}
/// <summary>
/// True if the symbol is a source symbol added during EnC session.
/// The symbol may be declared in any source compilation in the current solution.
/// </summary>
public bool IsAdded(ISymbol symbol)
{
return _isAddedSymbol(symbol);
}
/// <summary>
/// Returns true if the symbol or some child symbol has changed and needs to be compiled.
/// </summary>
public bool RequiresCompilation(ISymbol symbol)
{
return this.GetChange(symbol) != SymbolChange.None;
}
private bool DefinitionExistsInPreviousGeneration(ISymbolInternal symbol)
{
var definition = (IDefinition)symbol.GetCciAdapter();
if (!_definitionMap.DefinitionExists(definition))
{
return false;
}
// Definition map does not consider types that are being replaced,
// hence we need to check - type that is being replaced is not considered
// existing in the previous generation.
var current = symbol.GetISymbol();
do
{
if (_replacedSymbols.Contains(current))
{
return false;
}
current = current.ContainingType;
}
while (current is not null);
return true;
}
public SymbolChange GetChange(IDefinition def)
{
var symbol = def.GetInternalSymbol();
if (symbol is ISynthesizedMethodBodyImplementationSymbol synthesizedSymbol)
{
RoslynDebug.Assert(synthesizedSymbol.Method != null);
var generatorChange = GetChange((IDefinition)synthesizedSymbol.Method.GetCciAdapter());
switch (generatorChange)
{
case SymbolChange.Updated:
// The generator has been updated. Some synthesized members should be reused, others updated or added.
// The container of the synthesized symbol doesn't exist, we need to add the symbol.
// This may happen e.g. for members of a state machine type when a non-iterator method is changed to an iterator.
if (!DefinitionExistsInPreviousGeneration(synthesizedSymbol.ContainingType))
{
return SymbolChange.Added;
}
if (!DefinitionExistsInPreviousGeneration(synthesizedSymbol))
{
// A method was changed to a method containing a lambda, to an iterator, or to an async method.
// The state machine or closure class has been added.
return SymbolChange.Added;
}
// The existing symbol should be reused when the generator is updated,
// not updated since it's form doesn't depend on the content of the generator.
// For example, when an iterator method changes all methods that implement IEnumerable
// but MoveNext can be reused as they are.
if (!synthesizedSymbol.HasMethodBodyDependency)
{
return SymbolChange.None;
}
// If the type produced from the method body existed before then its members are updated.
if (synthesizedSymbol.Kind == SymbolKind.NamedType)
{
return SymbolChange.ContainsChanges;
}
if (synthesizedSymbol.Kind == SymbolKind.Method)
{
// The method body might have been updated.
return SymbolChange.Updated;
}
return SymbolChange.None;
case SymbolChange.Added:
// The method has been added - add the synthesized member as well, unless it already exists.
if (!DefinitionExistsInPreviousGeneration(synthesizedSymbol))
{
return SymbolChange.Added;
}
// If the existing member is a type we need to add new members into it.
// An example is a shared static display class - an added method with static lambda will contribute
// the lambda and cache fields into the shared display class.
if (synthesizedSymbol.Kind == SymbolKind.NamedType)
{
return SymbolChange.ContainsChanges;
}
// Update method.
// An example is a constructor a shared display class - an added method with lambda will contribute
// cache field initialization code into the constructor.
if (synthesizedSymbol.Kind == SymbolKind.Method)
{
return SymbolChange.Updated;
}
// Otherwise, there is nothing to do.
// For example, a static lambda display class cache field.
return SymbolChange.None;
default:
// The method had to change, otherwise the synthesized symbol wouldn't be generated
throw ExceptionUtilities.UnexpectedValue(generatorChange);
}
}
if (symbol is not null)
{
return GetChange(symbol.GetISymbol());
}
// If the def that has no associated internal symbol existed in the previous generation, the def is unchanged
// (although it may contain changed defs); otherwise, it was added.
if (_definitionMap.DefinitionExists(def))
{
return (def is ITypeDefinition) ? SymbolChange.ContainsChanges : SymbolChange.None;
}
return SymbolChange.Added;
}
private SymbolChange GetChange(ISymbol symbol)
{
if (_changes.TryGetValue(symbol, out var change))
{
return change;
}
// Calculate change based on change to container.
var container = GetContainingSymbol(symbol);
if (container == null)
{
return SymbolChange.None;
}
var containerChange = GetChange(container);
switch (containerChange)
{
case SymbolChange.Added:
// If container is added then all its members have been added.
return SymbolChange.Added;
case SymbolChange.None:
// If container has no changes then none of its members have any changes.
return SymbolChange.None;
case SymbolChange.Updated:
case SymbolChange.ContainsChanges:
var internalSymbol = GetISymbolInternalOrNull(symbol);
if (internalSymbol is null)
{
return SymbolChange.None;
}
if (internalSymbol.Kind == SymbolKind.Namespace)
{
// If the namespace did not exist in the previous generation, it was added.
// Otherwise the namespace may contain changes.
return _definitionMap.NamespaceExists((INamespace)internalSymbol.GetCciAdapter()) ? SymbolChange.ContainsChanges : SymbolChange.Added;
}
// If the definition did not exist in the previous generation, it was added.
return DefinitionExistsInPreviousGeneration(internalSymbol) ? SymbolChange.None : SymbolChange.Added;
default:
throw ExceptionUtilities.UnexpectedValue(containerChange);
}
}
protected abstract ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol);
public IEnumerable<INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context)
{
foreach (var symbol in _changes.Keys)
{
var namespaceTypeDef = (GetISymbolInternalOrNull(symbol)?.GetCciAdapter() as ITypeDefinition)?.AsNamespaceTypeDefinition(context);
if (namespaceTypeDef != null)
{
yield return namespaceTypeDef;
}
}
}
/// <summary>
/// Calculate the set of changes up to top-level types. The result
/// will be used as a filter when traversing the module.
///
/// Note that these changes only include user-defined source symbols, not synthesized symbols since those will be
/// generated during lowering of the changed user-defined symbols.
/// </summary>
private static void CalculateChanges(IEnumerable<SemanticEdit> edits, out IReadOnlyDictionary<ISymbol, SymbolChange> changes, out ISet<ISymbol> replaceSymbols)
{
var changesBuilder = new Dictionary<ISymbol, SymbolChange>();
HashSet<ISymbol>? lazyReplaceSymbolsBuilder = null;
foreach (var edit in edits)
{
SymbolChange change;
switch (edit.Kind)
{
case SemanticEditKind.Update:
change = SymbolChange.Updated;
break;
case SemanticEditKind.Insert:
change = SymbolChange.Added;
break;
case SemanticEditKind.Replace:
Debug.Assert(edit.NewSymbol != null);
(lazyReplaceSymbolsBuilder ??= new HashSet<ISymbol>()).Add(edit.NewSymbol);
change = SymbolChange.Added;
break;
case SemanticEditKind.Delete:
// No work to do.
continue;
default:
throw ExceptionUtilities.UnexpectedValue(edit.Kind);
}
var member = edit.NewSymbol;
RoslynDebug.AssertNotNull(member);
// Partial methods are supplied as implementations but recorded
// internally as definitions since definitions are used in emit.
if (member.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)member;
// Partial methods should be implementations, not definitions.
Debug.Assert(method.PartialImplementationPart == null);
Debug.Assert((edit.OldSymbol == null) || (((IMethodSymbol)edit.OldSymbol).PartialImplementationPart == null));
var definitionPart = method.PartialDefinitionPart;
if (definitionPart != null)
{
member = definitionPart;
}
}
AddContainingTypesAndNamespaces(changesBuilder, member);
changesBuilder.Add(member, change);
}
changes = changesBuilder;
replaceSymbols = lazyReplaceSymbolsBuilder ?? SpecializedCollections.EmptySet<ISymbol>();
}
private static void AddContainingTypesAndNamespaces(Dictionary<ISymbol, SymbolChange> changes, ISymbol symbol)
{
while (true)
{
var containingSymbol = GetContainingSymbol(symbol);
if (containingSymbol == null || changes.ContainsKey(containingSymbol))
{
return;
}
var change = containingSymbol.Kind is SymbolKind.Property or SymbolKind.Event ?
SymbolChange.Updated : SymbolChange.ContainsChanges;
changes.Add(containingSymbol, change);
symbol = containingSymbol;
}
}
/// <summary>
/// Return the symbol that contains this symbol as far
/// as changes are concerned. For instance, an auto property
/// is considered the containing symbol for the backing
/// field and the accessor methods. By default, the containing
/// symbol is simply Symbol.ContainingSymbol.
/// </summary>
private static ISymbol? GetContainingSymbol(ISymbol symbol)
{
// This approach of walking up the symbol hierarchy towards the
// root, rather than walking down to the leaf symbols, seems
// unreliable. It may be better to walk down using the usual
// emit traversal, but prune the traversal to those types and
// members that are known to contain changes.
switch (symbol.Kind)
{
case SymbolKind.Field:
{
var associated = ((IFieldSymbol)symbol).AssociatedSymbol;
if (associated != null)
{
return associated;
}
}
break;
case SymbolKind.Method:
{
var associated = ((IMethodSymbol)symbol).AssociatedSymbol;
if (associated != null)
{
return associated;
}
}
break;
}
symbol = symbol.ContainingSymbol;
if (symbol != null)
{
switch (symbol.Kind)
{
case SymbolKind.NetModule:
case SymbolKind.Assembly:
// These symbols are never part of the changes collection.
return null;
}
}
return symbol;
}
}
}
| 1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/EditorFeatures/Core/Implementation/INavigateToLinkService.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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Editor
{
internal interface INavigateToLinkService : IWorkspaceService
{
Task<bool> TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Editor
{
internal interface INavigateToLinkService : IWorkspaceService
{
Task<bool> TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/CSharp/Portable/Syntax/SyntaxNodeRemover.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
internal static class SyntaxNodeRemover
{
internal static TRoot? RemoveNodes<TRoot>(TRoot root,
IEnumerable<SyntaxNode> nodes,
SyntaxRemoveOptions options)
where TRoot : SyntaxNode
{
if (nodes == null)
{
return root;
}
var nodeArray = nodes.ToArray();
if (nodeArray.Length == 0)
{
return root;
}
var remover = new SyntaxRemover(nodes.ToArray(), options);
var result = remover.Visit(root);
var residualTrivia = remover.ResidualTrivia;
// the result of the SyntaxRemover will be null when the root node is removed.
if (result != null && residualTrivia.Count > 0)
{
result = result.WithTrailingTrivia(result.GetTrailingTrivia().Concat(residualTrivia));
}
return (TRoot?)result;
}
private class SyntaxRemover : CSharpSyntaxRewriter
{
private readonly HashSet<SyntaxNode> _nodesToRemove;
private readonly SyntaxRemoveOptions _options;
private readonly TextSpan _searchSpan;
private readonly SyntaxTriviaListBuilder _residualTrivia;
private HashSet<SyntaxNode>? _directivesToKeep;
public SyntaxRemover(
SyntaxNode[] nodesToRemove,
SyntaxRemoveOptions options)
: base(nodesToRemove.Any(n => n.IsPartOfStructuredTrivia()))
{
_nodesToRemove = new HashSet<SyntaxNode>(nodesToRemove);
_options = options;
_searchSpan = ComputeTotalSpan(nodesToRemove);
_residualTrivia = SyntaxTriviaListBuilder.Create();
}
private static TextSpan ComputeTotalSpan(SyntaxNode[] nodes)
{
var span0 = nodes[0].FullSpan;
int start = span0.Start;
int end = span0.End;
for (int i = 1; i < nodes.Length; i++)
{
var span = nodes[i].FullSpan;
start = Math.Min(start, span.Start);
end = Math.Max(end, span.End);
}
return new TextSpan(start, end - start);
}
internal SyntaxTriviaList ResidualTrivia
{
get
{
if (_residualTrivia != null)
{
return _residualTrivia.ToList();
}
else
{
return default(SyntaxTriviaList);
}
}
}
private void AddResidualTrivia(SyntaxTriviaList trivia, bool requiresNewLine = false)
{
if (requiresNewLine)
{
this.AddEndOfLine(GetEndOfLine(trivia) ?? SyntaxFactory.CarriageReturnLineFeed);
}
_residualTrivia.Add(trivia);
}
private void AddEndOfLine(SyntaxTrivia? eolTrivia)
{
if (!eolTrivia.HasValue)
{
return;
}
if (_residualTrivia.Count == 0 || !IsEndOfLine(_residualTrivia[_residualTrivia.Count - 1]))
{
_residualTrivia.Add(eolTrivia.Value);
}
}
/// <summary>
/// Returns whether the specified <see cref="SyntaxTrivia"/> token is also the end of the line. This will
/// be true for <see cref="SyntaxKind.EndOfLineTrivia"/>, <see cref="SyntaxKind.SingleLineCommentTrivia"/>,
/// and all preprocessor directives.
/// </summary>
private static bool IsEndOfLine(SyntaxTrivia trivia)
{
return trivia.Kind() == SyntaxKind.EndOfLineTrivia
|| trivia.Kind() == SyntaxKind.SingleLineCommentTrivia
|| trivia.IsDirective;
}
/// <summary>
/// Returns the first end of line found in a <see cref="SyntaxTriviaList"/>.
/// </summary>
private static SyntaxTrivia? GetEndOfLine(SyntaxTriviaList list)
{
foreach (var trivia in list)
{
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
return trivia;
}
if (trivia.IsDirective && trivia.GetStructure() is DirectiveTriviaSyntax directive)
{
return GetEndOfLine(directive.EndOfDirectiveToken.TrailingTrivia);
}
}
return null;
}
private bool IsForRemoval(SyntaxNode node)
{
return _nodesToRemove.Contains(node);
}
private bool ShouldVisit(SyntaxNode node)
{
return node.FullSpan.IntersectsWith(_searchSpan) || (_residualTrivia != null && _residualTrivia.Count > 0);
}
[return: NotNullIfNotNull("node")]
public override SyntaxNode? Visit(SyntaxNode? node)
{
SyntaxNode? result = node;
if (node != null)
{
if (this.IsForRemoval(node))
{
this.AddTrivia(node);
result = null;
}
else if (this.ShouldVisit(node))
{
result = base.Visit(node);
}
}
return result;
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
SyntaxToken result = token;
// only bother visiting trivia if we are removing a node in structured trivia
if (this.VisitIntoStructuredTrivia)
{
result = base.VisitToken(token);
}
// the next token gets the accrued trivia.
if (result.Kind() != SyntaxKind.None && _residualTrivia != null && _residualTrivia.Count > 0)
{
_residualTrivia.Add(result.LeadingTrivia);
result = result.WithLeadingTrivia(_residualTrivia.ToList());
_residualTrivia.Clear();
}
return result;
}
// deal with separated lists and removal of associated separators
public override SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list)
{
var withSeps = list.GetWithSeparators();
bool removeNextSeparator = false;
SyntaxNodeOrTokenListBuilder? alternate = null;
for (int i = 0, n = withSeps.Count; i < n; i++)
{
var item = withSeps[i];
SyntaxNodeOrToken visited;
if (item.IsToken) // separator
{
if (removeNextSeparator)
{
removeNextSeparator = false;
visited = default(SyntaxNodeOrToken);
}
else
{
visited = this.VisitListSeparator(item.AsToken());
}
}
else
{
var node = (TNode)item.AsNode()!;
if (this.IsForRemoval(node))
{
if (alternate == null)
{
alternate = new SyntaxNodeOrTokenListBuilder(n);
alternate.Add(withSeps, 0, i);
}
CommonSyntaxNodeRemover.GetSeparatorInfo(
withSeps, i, (int)SyntaxKind.EndOfLineTrivia,
out bool nextTokenIsSeparator, out bool nextSeparatorBelongsToNode);
if (!nextSeparatorBelongsToNode &&
alternate.Count > 0 &&
alternate[alternate.Count - 1].IsToken)
{
var separator = alternate[alternate.Count - 1].AsToken();
this.AddTrivia(separator, node);
alternate.RemoveLast();
}
else if (nextTokenIsSeparator)
{
var separator = withSeps[i + 1].AsToken();
this.AddTrivia(node, separator);
removeNextSeparator = true;
}
else
{
this.AddTrivia(node);
}
visited = default;
}
else
{
visited = this.VisitListElement(node);
}
}
if (item != visited && alternate == null)
{
alternate = new SyntaxNodeOrTokenListBuilder(n);
alternate.Add(withSeps, 0, i);
}
if (alternate != null && visited.Kind() != SyntaxKind.None)
{
alternate.Add(visited);
}
}
if (alternate != null)
{
return alternate.ToList().AsSeparatedList<TNode>();
}
return list;
}
private void AddTrivia(SyntaxNode node)
{
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia()));
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
this.AddDirectives(node, GetRemovedSpan(node.Span, node.FullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia()));
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private void AddTrivia(SyntaxToken token, SyntaxNode node)
{
Debug.Assert(node.Parent is object);
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(token.LeadingTrivia);
this.AddResidualTrivia(token.TrailingTrivia);
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
// For retrieving an EOL we don't need to check the node leading trivia as
// it can be always retrieved from the token trailing trivia, if one exists.
var eol = GetEndOfLine(token.LeadingTrivia) ??
GetEndOfLine(token.TrailingTrivia);
this.AddEndOfLine(eol);
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
var span = TextSpan.FromBounds(token.Span.Start, node.Span.End);
var fullSpan = TextSpan.FromBounds(token.FullSpan.Start, node.FullSpan.End);
this.AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia()));
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private void AddTrivia(SyntaxNode node, SyntaxToken token)
{
Debug.Assert(node.Parent is object);
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia()));
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
var span = TextSpan.FromBounds(node.Span.Start, token.Span.End);
var fullSpan = TextSpan.FromBounds(node.FullSpan.Start, token.FullSpan.End);
this.AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
this.AddResidualTrivia(token.LeadingTrivia);
this.AddResidualTrivia(token.TrailingTrivia);
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
// For retrieving an EOL we don't need to check the token leading trivia as
// it can be always retrieved from the node trailing trivia, if one exists.
var eol = GetEndOfLine(node.GetTrailingTrivia()) ??
GetEndOfLine(token.TrailingTrivia);
this.AddEndOfLine(eol);
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private TextSpan GetRemovedSpan(TextSpan span, TextSpan fullSpan)
{
var removedSpan = fullSpan;
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
removedSpan = TextSpan.FromBounds(span.Start, removedSpan.End);
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
removedSpan = TextSpan.FromBounds(removedSpan.Start, span.End);
}
return removedSpan;
}
private void AddDirectives(SyntaxNode node, TextSpan span)
{
if (node.ContainsDirectives)
{
if (_directivesToKeep == null)
{
_directivesToKeep = new HashSet<SyntaxNode>();
}
else
{
_directivesToKeep.Clear();
}
var directivesInSpan = node.DescendantTrivia(span, n => n.ContainsDirectives, descendIntoTrivia: true)
.Where(tr => tr.IsDirective)
.Select(tr => (DirectiveTriviaSyntax)tr.GetStructure()!);
foreach (var directive in directivesInSpan)
{
if ((_options & SyntaxRemoveOptions.KeepDirectives) != 0)
{
_directivesToKeep.Add(directive);
}
else if (directive.Kind() == SyntaxKind.DefineDirectiveTrivia ||
directive.Kind() == SyntaxKind.UndefDirectiveTrivia)
{
// always keep #define and #undef, even if we are only keeping unbalanced directives
_directivesToKeep.Add(directive);
}
else if (HasRelatedDirectives(directive))
{
// a balanced directive with respect to a given node has all related directives rooted under that node
var relatedDirectives = directive.GetRelatedDirectives();
var balanced = relatedDirectives.All(rd => rd.FullSpan.OverlapsWith(span));
if (!balanced)
{
// if not fully balanced, all related directives under the node are considered unbalanced.
foreach (var unbalancedDirective in relatedDirectives.Where(rd => rd.FullSpan.OverlapsWith(span)))
{
_directivesToKeep.Add(unbalancedDirective);
}
}
}
if (_directivesToKeep.Contains(directive))
{
AddResidualTrivia(SyntaxFactory.TriviaList(directive.ParentTrivia), requiresNewLine: true);
}
}
}
}
private static bool HasRelatedDirectives(DirectiveTriviaSyntax directive)
{
switch (directive.Kind())
{
case SyntaxKind.IfDirectiveTrivia:
case SyntaxKind.ElseDirectiveTrivia:
case SyntaxKind.ElifDirectiveTrivia:
case SyntaxKind.EndIfDirectiveTrivia:
case SyntaxKind.RegionDirectiveTrivia:
case SyntaxKind.EndRegionDirectiveTrivia:
return true;
default:
return false;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
internal static class SyntaxNodeRemover
{
internal static TRoot? RemoveNodes<TRoot>(TRoot root,
IEnumerable<SyntaxNode> nodes,
SyntaxRemoveOptions options)
where TRoot : SyntaxNode
{
if (nodes == null)
{
return root;
}
var nodeArray = nodes.ToArray();
if (nodeArray.Length == 0)
{
return root;
}
var remover = new SyntaxRemover(nodes.ToArray(), options);
var result = remover.Visit(root);
var residualTrivia = remover.ResidualTrivia;
// the result of the SyntaxRemover will be null when the root node is removed.
if (result != null && residualTrivia.Count > 0)
{
result = result.WithTrailingTrivia(result.GetTrailingTrivia().Concat(residualTrivia));
}
return (TRoot?)result;
}
private class SyntaxRemover : CSharpSyntaxRewriter
{
private readonly HashSet<SyntaxNode> _nodesToRemove;
private readonly SyntaxRemoveOptions _options;
private readonly TextSpan _searchSpan;
private readonly SyntaxTriviaListBuilder _residualTrivia;
private HashSet<SyntaxNode>? _directivesToKeep;
public SyntaxRemover(
SyntaxNode[] nodesToRemove,
SyntaxRemoveOptions options)
: base(nodesToRemove.Any(n => n.IsPartOfStructuredTrivia()))
{
_nodesToRemove = new HashSet<SyntaxNode>(nodesToRemove);
_options = options;
_searchSpan = ComputeTotalSpan(nodesToRemove);
_residualTrivia = SyntaxTriviaListBuilder.Create();
}
private static TextSpan ComputeTotalSpan(SyntaxNode[] nodes)
{
var span0 = nodes[0].FullSpan;
int start = span0.Start;
int end = span0.End;
for (int i = 1; i < nodes.Length; i++)
{
var span = nodes[i].FullSpan;
start = Math.Min(start, span.Start);
end = Math.Max(end, span.End);
}
return new TextSpan(start, end - start);
}
internal SyntaxTriviaList ResidualTrivia
{
get
{
if (_residualTrivia != null)
{
return _residualTrivia.ToList();
}
else
{
return default(SyntaxTriviaList);
}
}
}
private void AddResidualTrivia(SyntaxTriviaList trivia, bool requiresNewLine = false)
{
if (requiresNewLine)
{
this.AddEndOfLine(GetEndOfLine(trivia) ?? SyntaxFactory.CarriageReturnLineFeed);
}
_residualTrivia.Add(trivia);
}
private void AddEndOfLine(SyntaxTrivia? eolTrivia)
{
if (!eolTrivia.HasValue)
{
return;
}
if (_residualTrivia.Count == 0 || !IsEndOfLine(_residualTrivia[_residualTrivia.Count - 1]))
{
_residualTrivia.Add(eolTrivia.Value);
}
}
/// <summary>
/// Returns whether the specified <see cref="SyntaxTrivia"/> token is also the end of the line. This will
/// be true for <see cref="SyntaxKind.EndOfLineTrivia"/>, <see cref="SyntaxKind.SingleLineCommentTrivia"/>,
/// and all preprocessor directives.
/// </summary>
private static bool IsEndOfLine(SyntaxTrivia trivia)
{
return trivia.Kind() == SyntaxKind.EndOfLineTrivia
|| trivia.Kind() == SyntaxKind.SingleLineCommentTrivia
|| trivia.IsDirective;
}
/// <summary>
/// Returns the first end of line found in a <see cref="SyntaxTriviaList"/>.
/// </summary>
private static SyntaxTrivia? GetEndOfLine(SyntaxTriviaList list)
{
foreach (var trivia in list)
{
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
return trivia;
}
if (trivia.IsDirective && trivia.GetStructure() is DirectiveTriviaSyntax directive)
{
return GetEndOfLine(directive.EndOfDirectiveToken.TrailingTrivia);
}
}
return null;
}
private bool IsForRemoval(SyntaxNode node)
{
return _nodesToRemove.Contains(node);
}
private bool ShouldVisit(SyntaxNode node)
{
return node.FullSpan.IntersectsWith(_searchSpan) || (_residualTrivia != null && _residualTrivia.Count > 0);
}
[return: NotNullIfNotNull("node")]
public override SyntaxNode? Visit(SyntaxNode? node)
{
SyntaxNode? result = node;
if (node != null)
{
if (this.IsForRemoval(node))
{
this.AddTrivia(node);
result = null;
}
else if (this.ShouldVisit(node))
{
result = base.Visit(node);
}
}
return result;
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
SyntaxToken result = token;
// only bother visiting trivia if we are removing a node in structured trivia
if (this.VisitIntoStructuredTrivia)
{
result = base.VisitToken(token);
}
// the next token gets the accrued trivia.
if (result.Kind() != SyntaxKind.None && _residualTrivia != null && _residualTrivia.Count > 0)
{
_residualTrivia.Add(result.LeadingTrivia);
result = result.WithLeadingTrivia(_residualTrivia.ToList());
_residualTrivia.Clear();
}
return result;
}
// deal with separated lists and removal of associated separators
public override SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list)
{
var withSeps = list.GetWithSeparators();
bool removeNextSeparator = false;
SyntaxNodeOrTokenListBuilder? alternate = null;
for (int i = 0, n = withSeps.Count; i < n; i++)
{
var item = withSeps[i];
SyntaxNodeOrToken visited;
if (item.IsToken) // separator
{
if (removeNextSeparator)
{
removeNextSeparator = false;
visited = default(SyntaxNodeOrToken);
}
else
{
visited = this.VisitListSeparator(item.AsToken());
}
}
else
{
var node = (TNode)item.AsNode()!;
if (this.IsForRemoval(node))
{
if (alternate == null)
{
alternate = new SyntaxNodeOrTokenListBuilder(n);
alternate.Add(withSeps, 0, i);
}
CommonSyntaxNodeRemover.GetSeparatorInfo(
withSeps, i, (int)SyntaxKind.EndOfLineTrivia,
out bool nextTokenIsSeparator, out bool nextSeparatorBelongsToNode);
if (!nextSeparatorBelongsToNode &&
alternate.Count > 0 &&
alternate[alternate.Count - 1].IsToken)
{
var separator = alternate[alternate.Count - 1].AsToken();
this.AddTrivia(separator, node);
alternate.RemoveLast();
}
else if (nextTokenIsSeparator)
{
var separator = withSeps[i + 1].AsToken();
this.AddTrivia(node, separator);
removeNextSeparator = true;
}
else
{
this.AddTrivia(node);
}
visited = default;
}
else
{
visited = this.VisitListElement(node);
}
}
if (item != visited && alternate == null)
{
alternate = new SyntaxNodeOrTokenListBuilder(n);
alternate.Add(withSeps, 0, i);
}
if (alternate != null && visited.Kind() != SyntaxKind.None)
{
alternate.Add(visited);
}
}
if (alternate != null)
{
return alternate.ToList().AsSeparatedList<TNode>();
}
return list;
}
private void AddTrivia(SyntaxNode node)
{
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia()));
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
this.AddDirectives(node, GetRemovedSpan(node.Span, node.FullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia()));
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private void AddTrivia(SyntaxToken token, SyntaxNode node)
{
Debug.Assert(node.Parent is object);
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(token.LeadingTrivia);
this.AddResidualTrivia(token.TrailingTrivia);
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
// For retrieving an EOL we don't need to check the node leading trivia as
// it can be always retrieved from the token trailing trivia, if one exists.
var eol = GetEndOfLine(token.LeadingTrivia) ??
GetEndOfLine(token.TrailingTrivia);
this.AddEndOfLine(eol);
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
var span = TextSpan.FromBounds(token.Span.Start, node.Span.End);
var fullSpan = TextSpan.FromBounds(token.FullSpan.Start, node.FullSpan.End);
this.AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia()));
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private void AddTrivia(SyntaxNode node, SyntaxToken token)
{
Debug.Assert(node.Parent is object);
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia()));
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
var span = TextSpan.FromBounds(node.Span.Start, token.Span.End);
var fullSpan = TextSpan.FromBounds(node.FullSpan.Start, token.FullSpan.End);
this.AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
this.AddResidualTrivia(token.LeadingTrivia);
this.AddResidualTrivia(token.TrailingTrivia);
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
// For retrieving an EOL we don't need to check the token leading trivia as
// it can be always retrieved from the node trailing trivia, if one exists.
var eol = GetEndOfLine(node.GetTrailingTrivia()) ??
GetEndOfLine(token.TrailingTrivia);
this.AddEndOfLine(eol);
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private TextSpan GetRemovedSpan(TextSpan span, TextSpan fullSpan)
{
var removedSpan = fullSpan;
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
removedSpan = TextSpan.FromBounds(span.Start, removedSpan.End);
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
removedSpan = TextSpan.FromBounds(removedSpan.Start, span.End);
}
return removedSpan;
}
private void AddDirectives(SyntaxNode node, TextSpan span)
{
if (node.ContainsDirectives)
{
if (_directivesToKeep == null)
{
_directivesToKeep = new HashSet<SyntaxNode>();
}
else
{
_directivesToKeep.Clear();
}
var directivesInSpan = node.DescendantTrivia(span, n => n.ContainsDirectives, descendIntoTrivia: true)
.Where(tr => tr.IsDirective)
.Select(tr => (DirectiveTriviaSyntax)tr.GetStructure()!);
foreach (var directive in directivesInSpan)
{
if ((_options & SyntaxRemoveOptions.KeepDirectives) != 0)
{
_directivesToKeep.Add(directive);
}
else if (directive.Kind() == SyntaxKind.DefineDirectiveTrivia ||
directive.Kind() == SyntaxKind.UndefDirectiveTrivia)
{
// always keep #define and #undef, even if we are only keeping unbalanced directives
_directivesToKeep.Add(directive);
}
else if (HasRelatedDirectives(directive))
{
// a balanced directive with respect to a given node has all related directives rooted under that node
var relatedDirectives = directive.GetRelatedDirectives();
var balanced = relatedDirectives.All(rd => rd.FullSpan.OverlapsWith(span));
if (!balanced)
{
// if not fully balanced, all related directives under the node are considered unbalanced.
foreach (var unbalancedDirective in relatedDirectives.Where(rd => rd.FullSpan.OverlapsWith(span)))
{
_directivesToKeep.Add(unbalancedDirective);
}
}
}
if (_directivesToKeep.Contains(directive))
{
AddResidualTrivia(SyntaxFactory.TriviaList(directive.ParentTrivia), requiresNewLine: true);
}
}
}
}
private static bool HasRelatedDirectives(DirectiveTriviaSyntax directive)
{
switch (directive.Kind())
{
case SyntaxKind.IfDirectiveTrivia:
case SyntaxKind.ElseDirectiveTrivia:
case SyntaxKind.ElifDirectiveTrivia:
case SyntaxKind.EndIfDirectiveTrivia:
case SyntaxKind.RegionDirectiveTrivia:
case SyntaxKind.EndRegionDirectiveTrivia:
return true;
default:
return false;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/VisualStudio/CSharp/Impl/EditorConfigSettings/BinaryOperatorSpacingOptionsViewModel.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 Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings
{
internal class BinaryOperatorSpacingOptionsViewModel : EnumSettingViewModel<BinaryOperatorSpacingOptions>
{
private readonly WhitespaceSetting _setting;
public BinaryOperatorSpacingOptionsViewModel(WhitespaceSetting setting)
{
_setting = setting;
}
protected override void ChangePropertyTo(BinaryOperatorSpacingOptions newValue)
{
_setting.SetValue(newValue);
}
protected override BinaryOperatorSpacingOptions GetCurrentValue()
{
return (BinaryOperatorSpacingOptions)_setting.GetValue()!;
}
protected override IReadOnlyDictionary<string, BinaryOperatorSpacingOptions> GetValuesAndDescriptions()
{
return EnumerateOptions().ToDictionary(x => x.description, x => x.value);
static IEnumerable<(string description, BinaryOperatorSpacingOptions value)> EnumerateOptions()
{
yield return (CSharpVSResources.Ignore_spaces_around_binary_operators, BinaryOperatorSpacingOptions.Ignore);
yield return (CSharpVSResources.Remove_spaces_before_and_after_binary_operators, BinaryOperatorSpacingOptions.Remove);
yield return (CSharpVSResources.Insert_space_before_and_after_binary_operators, BinaryOperatorSpacingOptions.Single);
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings
{
internal class BinaryOperatorSpacingOptionsViewModel : EnumSettingViewModel<BinaryOperatorSpacingOptions>
{
private readonly WhitespaceSetting _setting;
public BinaryOperatorSpacingOptionsViewModel(WhitespaceSetting setting)
{
_setting = setting;
}
protected override void ChangePropertyTo(BinaryOperatorSpacingOptions newValue)
{
_setting.SetValue(newValue);
}
protected override BinaryOperatorSpacingOptions GetCurrentValue()
{
return (BinaryOperatorSpacingOptions)_setting.GetValue()!;
}
protected override IReadOnlyDictionary<string, BinaryOperatorSpacingOptions> GetValuesAndDescriptions()
{
return EnumerateOptions().ToDictionary(x => x.description, x => x.value);
static IEnumerable<(string description, BinaryOperatorSpacingOptions value)> EnumerateOptions()
{
yield return (CSharpVSResources.Ignore_spaces_around_binary_operators, BinaryOperatorSpacingOptions.Ignore);
yield return (CSharpVSResources.Remove_spaces_before_and_after_binary_operators, BinaryOperatorSpacingOptions.Remove);
yield return (CSharpVSResources.Insert_space_before_and_after_binary_operators, BinaryOperatorSpacingOptions.Single);
}
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/VisualStudio/Xaml/Impl/Features/AutoInsert/XamlAutoInsertResult.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.Text;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert
{
internal class XamlAutoInsertResult
{
public TextChange TextChange { get; set; }
public int? CaretOffset { get; set; }
}
}
| // Licensed to the .NET Foundation under one or more 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.Text;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert
{
internal class XamlAutoInsertResult
{
public TextChange TextChange { get; set; }
public int? CaretOffset { get; set; }
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenReadonlyStructTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public class CodeGenReadOnlyStructTests : CompilingTestBase
{
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyStaticField()
{
var text = @"
class Program
{
static readonly S1 sf;
static void Main()
{
System.Console.Write(sf.M1());
System.Console.Write(sf.ToString());
}
readonly struct S1
{
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 37 (0x25)
.maxstack 1
IL_0000: ldsflda ""Program.S1 Program.sf""
IL_0005: call ""string Program.S1.M1()""
IL_000a: call ""void System.Console.Write(string)""
IL_000f: ldsflda ""Program.S1 Program.sf""
IL_0014: constrained. ""Program.S1""
IL_001a: callvirt ""string object.ToString()""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: ret
}");
comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 43 (0x2b)
.maxstack 1
.locals init (Program.S1 V_0)
IL_0000: ldsfld ""Program.S1 Program.sf""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""string Program.S1.M1()""
IL_000d: call ""void System.Console.Write(string)""
IL_0012: ldsfld ""Program.S1 Program.sf""
IL_0017: stloc.0
IL_0018: ldloca.s V_0
IL_001a: constrained. ""Program.S1""
IL_0020: callvirt ""string object.ToString()""
IL_0025: call ""void System.Console.Write(string)""
IL_002a: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyStaticFieldMetadata()
{
var text1 = @"
public readonly struct S1
{
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
";
var comp1 = CreateCompilation(text1, assemblyName: "A");
var ref1 = comp1.EmitToImageReference();
var text = @"
class Program
{
static readonly S1 sf;
static void Main()
{
System.Console.Write(sf.M1());
System.Console.Write(sf.ToString());
}
}
";
var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 37 (0x25)
.maxstack 1
IL_0000: ldsflda ""S1 Program.sf""
IL_0005: call ""string S1.M1()""
IL_000a: call ""void System.Console.Write(string)""
IL_000f: ldsflda ""S1 Program.sf""
IL_0014: constrained. ""S1""
IL_001a: callvirt ""string object.ToString()""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: ret
}");
comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 43 (0x2b)
.maxstack 1
.locals init (S1 V_0)
IL_0000: ldsfld ""S1 Program.sf""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""string S1.M1()""
IL_000d: call ""void System.Console.Write(string)""
IL_0012: ldsfld ""S1 Program.sf""
IL_0017: stloc.0
IL_0018: ldloca.s V_0
IL_001a: constrained. ""S1""
IL_0020: callvirt ""string object.ToString()""
IL_0025: call ""void System.Console.Write(string)""
IL_002a: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyInstanceField()
{
var text = @"
class Program
{
readonly S1 f;
static void Main()
{
var p = new Program();
System.Console.Write(p.f.M1());
System.Console.Write(p.f.ToString());
}
readonly struct S1
{
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 43 (0x2b)
.maxstack 2
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldflda ""Program.S1 Program.f""
IL_000b: call ""string Program.S1.M1()""
IL_0010: call ""void System.Console.Write(string)""
IL_0015: ldflda ""Program.S1 Program.f""
IL_001a: constrained. ""Program.S1""
IL_0020: callvirt ""string object.ToString()""
IL_0025: call ""void System.Console.Write(string)""
IL_002a: ret
}");
comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 49 (0x31)
.maxstack 2
.locals init (Program.S1 V_0)
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldfld ""Program.S1 Program.f""
IL_000b: stloc.0
IL_000c: ldloca.s V_0
IL_000e: call ""string Program.S1.M1()""
IL_0013: call ""void System.Console.Write(string)""
IL_0018: ldfld ""Program.S1 Program.f""
IL_001d: stloc.0
IL_001e: ldloca.s V_0
IL_0020: constrained. ""Program.S1""
IL_0026: callvirt ""string object.ToString()""
IL_002b: call ""void System.Console.Write(string)""
IL_0030: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyInstanceFieldGeneric()
{
var text = @"
class Program
{
readonly S1<string> f;
static void Main()
{
var p = new Program();
System.Console.Write(p.f.M1(""hello""));
System.Console.Write(p.f.ToString());
}
readonly struct S1<T>
{
public T M1(T arg)
{
return arg;
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2");
comp.VerifyIL("Program.Main", @"
{
// Code size 48 (0x30)
.maxstack 3
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldflda ""Program.S1<string> Program.f""
IL_000b: ldstr ""hello""
IL_0010: call ""string Program.S1<string>.M1(string)""
IL_0015: call ""void System.Console.Write(string)""
IL_001a: ldflda ""Program.S1<string> Program.f""
IL_001f: constrained. ""Program.S1<string>""
IL_0025: callvirt ""string object.ToString()""
IL_002a: call ""void System.Console.Write(string)""
IL_002f: ret
}");
comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2");
comp.VerifyIL("Program.Main", @"
{
// Code size 54 (0x36)
.maxstack 3
.locals init (Program.S1<string> V_0)
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldfld ""Program.S1<string> Program.f""
IL_000b: stloc.0
IL_000c: ldloca.s V_0
IL_000e: ldstr ""hello""
IL_0013: call ""string Program.S1<string>.M1(string)""
IL_0018: call ""void System.Console.Write(string)""
IL_001d: ldfld ""Program.S1<string> Program.f""
IL_0022: stloc.0
IL_0023: ldloca.s V_0
IL_0025: constrained. ""Program.S1<string>""
IL_002b: callvirt ""string object.ToString()""
IL_0030: call ""void System.Console.Write(string)""
IL_0035: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyInstanceFieldGenericMetadata()
{
var text1 = @"
readonly public struct S1<T>
{
public T M1(T arg)
{
return arg;
}
public override string ToString()
{
return ""2"";
}
}
";
var comp1 = CreateCompilation(text1, assemblyName: "A");
var ref1 = comp1.EmitToImageReference();
var text = @"
class Program
{
readonly S1<string> f;
static void Main()
{
var p = new Program();
System.Console.Write(p.f.M1(""hello""));
System.Console.Write(p.f.ToString());
}
}
";
var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2");
comp.VerifyIL("Program.Main", @"
{
// Code size 48 (0x30)
.maxstack 3
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldflda ""S1<string> Program.f""
IL_000b: ldstr ""hello""
IL_0010: call ""string S1<string>.M1(string)""
IL_0015: call ""void System.Console.Write(string)""
IL_001a: ldflda ""S1<string> Program.f""
IL_001f: constrained. ""S1<string>""
IL_0025: callvirt ""string object.ToString()""
IL_002a: call ""void System.Console.Write(string)""
IL_002f: ret
}");
comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2");
comp.VerifyIL("Program.Main", @"
{
// Code size 54 (0x36)
.maxstack 3
.locals init (S1<string> V_0)
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldfld ""S1<string> Program.f""
IL_000b: stloc.0
IL_000c: ldloca.s V_0
IL_000e: ldstr ""hello""
IL_0013: call ""string S1<string>.M1(string)""
IL_0018: call ""void System.Console.Write(string)""
IL_001d: ldfld ""S1<string> Program.f""
IL_0022: stloc.0
IL_0023: ldloca.s V_0
IL_0025: constrained. ""S1<string>""
IL_002b: callvirt ""string object.ToString()""
IL_0030: call ""void System.Console.Write(string)""
IL_0035: ret
}");
}
[Fact]
public void InvokeOnReadOnlyThis()
{
var text = @"
class Program
{
static void Main()
{
Test(default(S1));
}
static void Test(in S1 arg)
{
System.Console.Write(arg.M1());
System.Console.Write(arg.ToString());
}
readonly struct S1
{
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.Test", @"
{
// Code size 29 (0x1d)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""string Program.S1.M1()""
IL_0006: call ""void System.Console.Write(string)""
IL_000b: ldarg.0
IL_000c: constrained. ""Program.S1""
IL_0012: callvirt ""string object.ToString()""
IL_0017: call ""void System.Console.Write(string)""
IL_001c: ret
}");
}
[Fact]
public void InvokeOnThis()
{
var text = @"
class Program
{
static void Main()
{
default(S1).Test();
}
readonly struct S1
{
public void Test()
{
System.Console.Write(this.M1());
System.Console.Write(ToString());
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.S1.Test()", @"
{
// Code size 29 (0x1d)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""string Program.S1.M1()""
IL_0006: call ""void System.Console.Write(string)""
IL_000b: ldarg.0
IL_000c: constrained. ""Program.S1""
IL_0012: callvirt ""string object.ToString()""
IL_0017: call ""void System.Console.Write(string)""
IL_001c: ret
}");
comp.VerifyIL("Program.Main()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (Program.S1 V_0)
IL_0000: ldloca.s V_0
IL_0002: dup
IL_0003: initobj ""Program.S1""
IL_0009: call ""void Program.S1.Test()""
IL_000e: ret
}");
}
[Fact]
public void InvokeOnThisBaseMethods()
{
var text = @"
class Program
{
static void Main()
{
default(S1).Test();
}
readonly struct S1
{
public void Test()
{
System.Console.Write(this.GetType());
System.Console.Write(ToString());
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"Program+S1Program+S1");
comp.VerifyIL("Program.S1.Test()", @"
{
// Code size 39 (0x27)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldobj ""Program.S1""
IL_0006: box ""Program.S1""
IL_000b: call ""System.Type object.GetType()""
IL_0010: call ""void System.Console.Write(object)""
IL_0015: ldarg.0
IL_0016: constrained. ""Program.S1""
IL_001c: callvirt ""string object.ToString()""
IL_0021: call ""void System.Console.Write(string)""
IL_0026: ret
}");
}
[Fact]
public void AssignThis()
{
var text = @"
class Program
{
static void Main()
{
S1 v = new S1(42);
System.Console.Write(v.x);
S1 v2 = new S1(v);
System.Console.Write(v2.x);
}
readonly struct S1
{
public readonly int x;
public S1(int i)
{
x = i; // OK
}
public S1(S1 arg)
{
this = arg; // OK
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"4242");
comp.VerifyIL("Program.S1..ctor(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int Program.S1.x""
IL_0007: ret
}");
comp.VerifyIL("Program.S1..ctor(Program.S1)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stobj ""Program.S1""
IL_0007: ret
}");
}
[Fact]
public void AssignThisErr()
{
var text = @"
class Program
{
static void Main()
{
}
static void TakesRef(ref S1 arg){}
static void TakesRef(ref int arg){}
readonly struct S1
{
readonly int x;
public S1(int i)
{
x = i; // OK
}
public S1(S1 arg)
{
this = arg; // OK
}
public void Test1()
{
this = default; // error
}
public void Test2()
{
TakesRef(ref this); // error
}
public void Test3()
{
TakesRef(ref this.x); // error
}
}
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (27,13): error CS1604: Cannot assign to 'this' because it is read-only
// this = default; // error
Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this").WithLocation(27, 13),
// (32,26): error CS1605: Cannot use 'this' as a ref or out value because it is read-only
// TakesRef(ref this); // error
Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this").WithLocation(32, 26),
// (37,26): error CS0192: A readonly field cannot be used as a ref or out value (except in a constructor)
// TakesRef(ref this.x); // error
Diagnostic(ErrorCode.ERR_RefReadonly, "this.x").WithLocation(37, 26)
);
}
[Fact]
public void AssignThisNestedMethods()
{
var text = @"
using System;
class Program
{
static void Main()
{
}
static void TakesRef(ref S1 arg){}
static void TakesRef(ref int arg){}
readonly struct S1
{
readonly int x;
public S1(int i)
{
void F() { x = i;} // Error
Action a = () => { x = i;}; // Error
F();
}
public S1(S1 arg)
{
void F() { this = arg;} // Error
Action a = () => { this = arg;}; // Error
F();
}
public void Test1()
{
void F() { this = default;} // Error
Action a = () => { this = default;}; // Error
F();
}
public void Test2()
{
void F() { TakesRef(ref this);} // Error
Action a = () => { TakesRef(ref this);}; // Error
F();
}
public void Test3()
{
void F() { TakesRef(ref this.x);} // Error
Action a = () => { TakesRef(ref this.x);}; // Error
F();
}
}
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (19,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { x = i;} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(19, 24),
// (20,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { x = i;}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(20, 32),
// (26,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { this = arg;} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(26, 24),
// (27,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { this = arg;}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(27, 32),
// (33,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { this = default;} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(33, 24),
// (34,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { this = default;}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(34, 32),
// (40,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { TakesRef(ref this);} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(40, 37),
// (41,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { TakesRef(ref this);}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(41, 45),
// (47,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { TakesRef(ref this.x);} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(47, 37),
// (48,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { TakesRef(ref this.x);}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(48, 45)
);
}
[Fact]
public void ReadOnlyStructApi()
{
var text = @"
class Program
{
readonly struct S1
{
public S1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
readonly struct S1<T>
{
public S1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
struct S2
{
public S2(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
class C1
{
public C1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
delegate int D1();
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular);
// S1
NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1");
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
void validate(ModuleSymbol module)
{
var test = module.ContainingAssembly.GetTypeByMetadataName("Program+S1");
var peModule = (PEModuleSymbol)module;
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PENamedTypeSymbol)test).Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
CompileAndVerify(comp, symbolValidator: validate);
// S1<T>
namedType = comp.GetTypeByMetadataName("Program+S1`1");
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// T
TypeSymbol type = namedType.TypeParameters[0];
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S1<object>
namedType = namedType.Construct(comp.ObjectType);
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S2
namedType = comp.GetTypeByMetadataName("Program+S2");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind);
// C1
namedType = comp.GetTypeByMetadataName("Program+C1");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind);
// D1
namedType = comp.GetTypeByMetadataName("Program+D1");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind);
// object[]
type = comp.CreateArrayTypeSymbol(comp.ObjectType);
Assert.False(type.IsReadOnly);
// dynamic
type = comp.DynamicType;
Assert.False(type.IsReadOnly);
// object
type = comp.ObjectType;
Assert.False(type.IsReadOnly);
// anonymous type
INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq"));
Assert.False(iNamedType.IsReadOnly);
// pointer type
type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType);
Assert.False(type.IsReadOnly);
// tuple type
iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol()));
Assert.False(iNamedType.IsReadOnly);
// S1 from image
var clientComp = CreateCompilation("", references: new[] { comp.EmitToImageReference() });
NamedTypeSymbol s1 = clientComp.GetTypeByMetadataName("Program+S1");
Assert.True(s1.IsReadOnly);
Assert.Empty(s1.GetAttributes());
Assert.Equal(RefKind.Out, s1.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, s1.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, s1.GetMethod("ToString").ThisParameter.RefKind);
}
[Fact]
public void ReadOnlyStructApiMetadata()
{
var text1 = @"
class Program
{
readonly struct S1
{
public S1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
readonly struct S1<T>
{
public S1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
struct S2
{
public S2(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
class C1
{
public C1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
delegate int D1();
}
";
var comp1 = CreateCompilation(text1, assemblyName: "A");
var ref1 = comp1.EmitToImageReference();
var comp = CreateCompilation("//NO CODE HERE", new[] { ref1 }, parseOptions: TestOptions.Regular);
// S1
NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1");
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S1<T>
namedType = comp.GetTypeByMetadataName("Program+S1`1");
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// T
TypeSymbol type = namedType.TypeParameters[0];
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S1<object>
namedType = namedType.Construct(comp.ObjectType);
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S2
namedType = comp.GetTypeByMetadataName("Program+S2");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind);
// C1
namedType = comp.GetTypeByMetadataName("Program+C1");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind);
// D1
namedType = comp.GetTypeByMetadataName("Program+D1");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind);
// object[]
type = comp.CreateArrayTypeSymbol(comp.ObjectType);
Assert.False(type.IsReadOnly);
// dynamic
type = comp.DynamicType;
Assert.False(type.IsReadOnly);
// object
type = comp.ObjectType;
Assert.False(type.IsReadOnly);
// anonymous type
INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq"));
Assert.False(iNamedType.IsReadOnly);
// pointer type
type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType);
Assert.False(type.IsReadOnly);
// tuple type
iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol()));
Assert.False(iNamedType.IsReadOnly);
}
[Fact]
public void CorrectOverloadOfStackAllocSpanChosen()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
unsafe public static void Main()
{
bool condition = false;
var span1 = condition ? stackalloc int[1] : new Span<int>(null, 2);
Console.Write(span1.Length);
var span2 = condition ? stackalloc int[1] : stackalloc int[4];
Console.Write(span2.Length);
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "24", verify: Verification.Fails);
}
[Fact]
public void StackAllocExpressionIL()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public static void Main()
{
Span<int> x = stackalloc int[10];
Console.WriteLine(x.Length);
}
}", TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "10", verify: Verification.Fails).VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (System.Span<int> V_0) //x
IL_0000: ldc.i4.s 40
IL_0002: conv.u
IL_0003: localloc
IL_0005: ldc.i4.s 10
IL_0007: newobj ""System.Span<int>..ctor(void*, int)""
IL_000c: stloc.0
IL_000d: ldloca.s V_0
IL_000f: call ""int System.Span<int>.Length.get""
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ret
}");
}
[Fact]
public void StackAllocSpanLengthNotEvaluatedTwice()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
private static int length = 0;
private static int GetLength()
{
return ++length;
}
public static void Main()
{
for (int i = 0; i < 5; i++)
{
Span<int> x = stackalloc int[GetLength()];
Console.Write(x.Length);
}
}
}", TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "12345", verify: Verification.Fails).VerifyIL("Test.Main", @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (int V_0, //i
System.Span<int> V_1, //x
int V_2)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_0027
IL_0004: call ""int Test.GetLength()""
IL_0009: stloc.2
IL_000a: ldloc.2
IL_000b: conv.u
IL_000c: ldc.i4.4
IL_000d: mul.ovf.un
IL_000e: localloc
IL_0010: ldloc.2
IL_0011: newobj ""System.Span<int>..ctor(void*, int)""
IL_0016: stloc.1
IL_0017: ldloca.s V_1
IL_0019: call ""int System.Span<int>.Length.get""
IL_001e: call ""void System.Console.Write(int)""
IL_0023: ldloc.0
IL_0024: ldc.i4.1
IL_0025: add
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: ldc.i4.5
IL_0029: blt.s IL_0004
IL_002b: ret
}");
}
[Fact]
public void StackAllocSpanLengthConstantFolding()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public static void Main()
{
const int a = 5, b = 6;
Span<int> x = stackalloc int[a * b];
Console.Write(x.Length);
}
}", TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "30", verify: Verification.Fails).VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (System.Span<int> V_0) //x
IL_0000: ldc.i4.s 120
IL_0002: conv.u
IL_0003: localloc
IL_0005: ldc.i4.s 30
IL_0007: newobj ""System.Span<int>..ctor(void*, int)""
IL_000c: stloc.0
IL_000d: ldloca.s V_0
IL_000f: call ""int System.Span<int>.Length.get""
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ret
}");
}
[Fact]
public void StackAllocSpanLengthOverflow()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
static void M()
{
Span<int> x = stackalloc int[int.MaxValue];
}
public static void Main()
{
try
{
M();
}
catch (OverflowException)
{
Console.WriteLine(""overflow"");
}
}
}", TestOptions.ReleaseExe);
var expectedIL = @"
{
// Code size 22 (0x16)
.maxstack 2
IL_0000: ldc.i4 0x7fffffff
IL_0005: conv.u
IL_0006: ldc.i4.4
IL_0007: mul.ovf.un
IL_0008: localloc
IL_000a: ldc.i4 0x7fffffff
IL_000f: newobj ""System.Span<int>..ctor(void*, int)""
IL_0014: pop
IL_0015: ret
}";
var isx86 = (IntPtr.Size == 4);
if (isx86)
{
CompileAndVerify(comp, expectedOutput: "overflow", verify: Verification.Fails).VerifyIL("Test.M", expectedIL);
}
else
{
// On 64bit the native int does not overflow, so we get StackOverflow instead
// therefore we will just check the IL
CompileAndVerify(comp, verify: Verification.Fails).VerifyIL("Test.M", expectedIL);
}
}
[Fact]
public void ImplicitCastOperatorOnStackAllocIsLoweredCorrectly()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public static void Main()
{
Test obj1 = stackalloc int[10];
Console.Write(""|"");
Test obj2 = stackalloc double[10];
}
public static implicit operator Test(Span<int> value)
{
Console.Write(""SpanOpCalled"");
return default(Test);
}
public static implicit operator Test(double* value)
{
Console.Write(""PointerOpCalled"");
return default(Test);
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "SpanOpCalled|PointerOpCalled", verify: Verification.Fails);
}
[Fact]
public void ExplicitCastOperatorOnStackAllocIsLoweredCorrectly()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public static void Main()
{
Test obj1 = (Test)stackalloc int[10];
}
public static explicit operator Test(Span<int> value)
{
Console.Write(""SpanOpCalled"");
return default(Test);
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "SpanOpCalled", verify: Verification.Fails);
}
[Fact]
public void ReadOnlyMembers_Metadata()
{
var csharp = @"
public struct S
{
public void M1() {}
public readonly void M2() {}
public int P1 { get; set; }
public readonly int P2 => 42;
public int P3 { readonly get => 123; set {} }
public int P4 { get => 123; readonly set {} }
public static int P5 { get; set; }
}
";
CompileAndVerify(csharp, symbolValidator: validate);
void validate(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("S");
var m1 = type.GetMethod("M1");
var m2 = type.GetMethod("M2");
var p1 = type.GetProperty("P1");
var p2 = type.GetProperty("P2");
var p3 = type.GetProperty("P3");
var p4 = type.GetProperty("P4");
var p5 = type.GetProperty("P5");
var peModule = (PEModuleSymbol)module;
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
}
[Fact]
public void ReadOnlyMembers_RefReturn_Metadata()
{
var csharp = @"
public struct S
{
static int i;
public ref int M1() => ref i;
public readonly ref int M2() => ref i;
public ref readonly int M3() => ref i;
public readonly ref readonly int M4() => ref i;
public ref int P1 { get => ref i; }
public readonly ref int P2 { get => ref i; }
public ref readonly int P3 { get => ref i; }
public readonly ref readonly int P4 { get => ref i; }
}
";
CompileAndVerify(csharp, symbolValidator: validate);
void validate(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("S");
var m1 = type.GetMethod("M1");
var m2 = type.GetMethod("M2");
var m3 = type.GetMethod("M3");
var m4 = type.GetMethod("M4");
var p1 = type.GetProperty("P1");
var p2 = type.GetProperty("P2");
var p3 = type.GetProperty("P3");
var p4 = type.GetProperty("P4");
var peModule = (PEModuleSymbol)module;
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
}
[Fact]
public void ReadOnlyStruct_ReadOnlyMembers_Metadata()
{
var csharp = @"
// note that both the type and member declarations are marked 'readonly'
public readonly struct S
{
public void M1() {}
public readonly void M2() {}
public int P1 { get; }
public readonly int P2 => 42;
public int P3 { readonly get => 123; set {} }
public int P4 { get => 123; readonly set {} }
public static int P5 { get; set; }
}
";
CompileAndVerify(csharp, symbolValidator: validate);
void validate(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("S");
var m1 = type.GetMethod("M1");
var m2 = type.GetMethod("M2");
var p1 = type.GetProperty("P1");
var p2 = type.GetProperty("P2");
var p3 = type.GetProperty("P3");
var p4 = type.GetProperty("P4");
var p5 = type.GetProperty("P5");
var peModule = (PEModuleSymbol)module;
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
}
[Fact]
public void ReadOnlyMembers_MetadataRoundTrip()
{
var external = @"
using System;
public struct S1
{
public void M1() {}
public readonly void M2() {}
public int P1 { get; set; }
public readonly int P2 => 42;
public int P3 { readonly get => 123; set {} }
public int P4 { get => 123; readonly set {} }
public static int P5 { get; set; }
public readonly event Action<EventArgs> E { add {} remove {} }
}
public readonly struct S2
{
public void M1() {}
public int P1 { get; }
public int P2 => 42;
public int P3 { set {} }
public static int P4 { get; set; }
public event Action<EventArgs> E { add {} remove {} }
}
";
var externalComp = CreateCompilation(external);
externalComp.VerifyDiagnostics();
verify(externalComp);
var comp = CreateCompilation("", references: new[] { externalComp.EmitToImageReference() });
verify(comp);
var comp2 = CreateCompilation("", references: new[] { externalComp.ToMetadataReference() });
verify(comp2);
void verify(CSharpCompilation comp)
{
var s1 = comp.GetMember<NamedTypeSymbol>("S1");
verifyReadOnly(s1.GetMethod("M1"), false, RefKind.Ref);
verifyReadOnly(s1.GetMethod("M2"), true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P1").SetMethod, false, RefKind.Ref);
verifyReadOnly(s1.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P3").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P3").SetMethod, false, RefKind.Ref);
verifyReadOnly(s1.GetProperty("P4").GetMethod, false, RefKind.Ref);
verifyReadOnly(s1.GetProperty("P4").SetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P5").GetMethod, false, null);
verifyReadOnly(s1.GetProperty("P5").SetMethod, false, null);
verifyReadOnly(s1.GetEvent("E").AddMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly);
var s2 = comp.GetMember<NamedTypeSymbol>("S2");
verifyReadOnly(s2.GetMethod("M1"), true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetProperty("P3").SetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetProperty("P4").GetMethod, false, null);
verifyReadOnly(s2.GetProperty("P4").SetMethod, false, null);
verifyReadOnly(s2.GetEvent("E").AddMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly);
void verifyReadOnly(MethodSymbol method, bool isReadOnly, RefKind? refKind)
{
Assert.Equal(isReadOnly, method.IsEffectivelyReadOnly);
Assert.Equal(refKind, method.ThisParameter?.RefKind);
}
}
}
[Fact]
public void StaticReadOnlyMethod_FromMetadata()
{
var il = @"
.class private auto ansi '<Module>'
{
} // end of class <Module>
.class public auto ansi beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute
extends [mscorlib]System.Attribute
{
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2050
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Attribute::.ctor()
IL_0006: ret
} // end of method IsReadOnlyAttribute::.ctor
} // end of class System.Runtime.CompilerServices.IsReadOnlyAttribute
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
// Methods
.method public hidebysig
instance void M1 () cil managed
{
.custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (
01 00 00 00
)
// Method begins at RVA 0x2058
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method S::M1
// Methods
.method public hidebysig static
void M2 () cil managed
{
.custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (
01 00 00 00
)
// Method begins at RVA 0x2058
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method S::M2
} // end of class S
";
var ilRef = CompileIL(il);
var comp = CreateCompilation("", references: new[] { ilRef });
var s = comp.GetMember<NamedTypeSymbol>("S");
var m1 = s.GetMethod("M1");
Assert.True(m1.IsDeclaredReadOnly);
Assert.True(m1.IsEffectivelyReadOnly);
// even though the IsReadOnlyAttribute is in metadata,
// we ruled out the possibility of the method being readonly because it's static
var m2 = s.GetMethod("M2");
Assert.False(m2.IsDeclaredReadOnly);
Assert.False(m2.IsEffectivelyReadOnly);
}
[Fact]
public void ReadOnlyMethod_CallNormalMethod()
{
var csharp = @"
public struct S
{
public int i;
public readonly void M1()
{
// should create local copy
M2();
System.Console.Write(i);
// explicit local copy, no warning
var copy = this;
copy.M2();
System.Console.Write(copy.i);
}
void M2()
{
i = 23;
}
static void Main()
{
var s = new S { i = 1 };
s.M1();
}
}
";
var verifier = CompileAndVerify(csharp, expectedOutput: "123");
verifier.VerifyDiagnostics(
// (9,9): warning CS8655: Call to non-readonly member 'S.M2()' from a 'readonly' member results in an implicit copy of 'this'.
// M2();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "M2").WithArguments("S.M2()", "this").WithLocation(9, 9));
verifier.VerifyIL("S.M1", @"
{
// Code size 51 (0x33)
.maxstack 1
.locals init (S V_0, //copy
S V_1)
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: stloc.1
IL_0007: ldloca.s V_1
IL_0009: call ""void S.M2()""
IL_000e: ldarg.0
IL_000f: ldfld ""int S.i""
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ldarg.0
IL_001a: ldobj ""S""
IL_001f: stloc.0
IL_0020: ldloca.s V_0
IL_0022: call ""void S.M2()""
IL_0027: ldloc.0
IL_0028: ldfld ""int S.i""
IL_002d: call ""void System.Console.Write(int)""
IL_0032: ret
}");
}
[Fact]
public void InMethod_CallNormalMethod()
{
var csharp = @"
public struct S
{
public int i;
public static void M1(in S s)
{
// should create local copy
s.M2();
System.Console.Write(s.i);
// explicit local copy, no warning
var copy = s;
copy.M2();
System.Console.Write(copy.i);
}
void M2()
{
i = 23;
}
static void Main()
{
var s = new S { i = 1 };
M1(in s);
}
}
";
var verifier = CompileAndVerify(csharp, expectedOutput: "123");
// should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968)
verifier.VerifyDiagnostics();
verifier.VerifyIL("S.M1", @"
{
// Code size 51 (0x33)
.maxstack 1
.locals init (S V_0, //copy
S V_1)
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: stloc.1
IL_0007: ldloca.s V_1
IL_0009: call ""void S.M2()""
IL_000e: ldarg.0
IL_000f: ldfld ""int S.i""
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ldarg.0
IL_001a: ldobj ""S""
IL_001f: stloc.0
IL_0020: ldloca.s V_0
IL_0022: call ""void S.M2()""
IL_0027: ldloc.0
IL_0028: ldfld ""int S.i""
IL_002d: call ""void System.Console.Write(int)""
IL_0032: ret
}");
}
[Fact]
public void InMethod_CallMethodFromMetadata()
{
var external = @"
public struct S
{
public int i;
public readonly void M1() {}
public void M2()
{
i = 23;
}
}
";
var image = CreateCompilation(external).EmitToImageReference();
var csharp = @"
public static class C
{
public static void M1(in S s)
{
// should not copy, no warning
s.M1();
System.Console.Write(s.i);
// should create local copy, warn in warning wave
s.M2();
System.Console.Write(s.i);
// explicit local copy, no warning
var copy = s;
copy.M2();
System.Console.Write(copy.i);
}
static void Main()
{
var s = new S { i = 1 };
M1(in s);
}
}
";
var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123");
// should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968)
verifier.VerifyDiagnostics();
verifier.VerifyIL("C.M1", @"
{
// Code size 68 (0x44)
.maxstack 1
.locals init (S V_0, //copy
S V_1)
IL_0000: ldarg.0
IL_0001: call ""readonly void S.M1()""
IL_0006: ldarg.0
IL_0007: ldfld ""int S.i""
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldarg.0
IL_0012: ldobj ""S""
IL_0017: stloc.1
IL_0018: ldloca.s V_1
IL_001a: call ""void S.M2()""
IL_001f: ldarg.0
IL_0020: ldfld ""int S.i""
IL_0025: call ""void System.Console.Write(int)""
IL_002a: ldarg.0
IL_002b: ldobj ""S""
IL_0030: stloc.0
IL_0031: ldloca.s V_0
IL_0033: call ""void S.M2()""
IL_0038: ldloc.0
IL_0039: ldfld ""int S.i""
IL_003e: call ""void System.Console.Write(int)""
IL_0043: ret
}");
}
[Fact]
public void InMethod_CallGetAccessorFromMetadata()
{
var external = @"
public struct S
{
public int i;
public readonly int P1 => 42;
public int P2 => i = 23;
}
";
var image = CreateCompilation(external).EmitToImageReference();
var csharp = @"
public static class C
{
public static void M1(in S s)
{
// should not copy, no warning
_ = s.P1;
System.Console.Write(s.i);
// should create local copy, warn in warning wave
_ = s.P2;
System.Console.Write(s.i);
// explicit local copy, no warning
var copy = s;
_ = copy.P2;
System.Console.Write(copy.i);
}
static void Main()
{
var s = new S { i = 1 };
M1(in s);
}
}
";
var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123");
// should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968)
verifier.VerifyDiagnostics();
verifier.VerifyIL("C.M1", @"
{
// Code size 71 (0x47)
.maxstack 1
.locals init (S V_0, //copy
S V_1)
IL_0000: ldarg.0
IL_0001: call ""readonly int S.P1.get""
IL_0006: pop
IL_0007: ldarg.0
IL_0008: ldfld ""int S.i""
IL_000d: call ""void System.Console.Write(int)""
IL_0012: ldarg.0
IL_0013: ldobj ""S""
IL_0018: stloc.1
IL_0019: ldloca.s V_1
IL_001b: call ""int S.P2.get""
IL_0020: pop
IL_0021: ldarg.0
IL_0022: ldfld ""int S.i""
IL_0027: call ""void System.Console.Write(int)""
IL_002c: ldarg.0
IL_002d: ldobj ""S""
IL_0032: stloc.0
IL_0033: ldloca.s V_0
IL_0035: call ""int S.P2.get""
IL_003a: pop
IL_003b: ldloc.0
IL_003c: ldfld ""int S.i""
IL_0041: call ""void System.Console.Write(int)""
IL_0046: ret
}");
}
[Fact]
public void ReadOnlyMethod_CallReadOnlyMethod()
{
var csharp = @"
public struct S
{
public int i;
public readonly int M1() => M2() + 1;
public readonly int M2() => i;
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S.M1", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly int S.M2()""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void ReadOnlyGetAccessor_CallReadOnlyGetAccessor()
{
var csharp = @"
public struct S
{
public int i;
public readonly int P1 { get => P2 + 1; }
public readonly int P2 { get => i; }
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S.P1.get", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly int S.P2.get""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void ReadOnlyGetAccessor_CallAutoGetAccessor()
{
var csharp = @"
public struct S
{
public readonly int P1 { get => P2 + 1; }
public int P2 { get; }
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S.P1.get", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly int S.P2.get""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void InParam_CallReadOnlyMethod()
{
var csharp = @"
public struct S
{
public int i;
public static int M1(in S s) => s.M2() + 1;
public readonly int M2() => i;
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S.M1", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly int S.M2()""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void ReadOnlyMethod_CallReadOnlyMethodOnField()
{
var csharp = @"
public struct S1
{
public readonly void M1() {}
}
public struct S2
{
S1 s1;
public readonly void M2()
{
s1.M1();
}
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S2.M2", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldflda ""S1 S2.s1""
IL_0006: call ""readonly void S1.M1()""
IL_000b: ret
}");
comp.VerifyDiagnostics(
// (9,8): warning CS0649: Field 'S2.s1' is never assigned to, and will always have its default value
// S1 s1;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s1").WithArguments("S2.s1", "").WithLocation(9, 8)
);
}
[Fact]
public void ReadOnlyMethod_CallNormalMethodOnField()
{
var csharp = @"
public struct S1
{
public void M1() {}
}
public struct S2
{
S1 s1;
public readonly void M2()
{
s1.M1();
}
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S2.M2", @"
{
// Code size 15 (0xf)
.maxstack 1
.locals init (S1 V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""S1 S2.s1""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""void S1.M1()""
IL_000e: ret
}");
// should warn about calling s2.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968)
comp.VerifyDiagnostics();
}
[Fact]
public void ReadOnlyMethod_CallBaseMethod()
{
var csharp = @"
public struct S
{
readonly void M()
{
// no warnings for calls to base members
GetType();
ToString();
GetHashCode();
Equals(null);
}
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyDiagnostics();
// ToString/GetHashCode/Equals should pass the address of 'this' (not a temp). GetType should box 'this'.
comp.VerifyIL("S.M", @"
{
// Code size 58 (0x3a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: box ""S""
IL_000b: call ""System.Type object.GetType()""
IL_0010: pop
IL_0011: ldarg.0
IL_0012: constrained. ""S""
IL_0018: callvirt ""string object.ToString()""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: constrained. ""S""
IL_0025: callvirt ""int object.GetHashCode()""
IL_002a: pop
IL_002b: ldarg.0
IL_002c: ldnull
IL_002d: constrained. ""S""
IL_0033: callvirt ""bool object.Equals(object)""
IL_0038: pop
IL_0039: ret
}");
}
[Fact]
public void ReadOnlyMethod_OverrideBaseMethod()
{
var csharp = @"
public struct S
{
// note: GetType can't be overridden
public override string ToString() => throw null;
public override int GetHashCode() => throw null;
public override bool Equals(object o) => throw null;
readonly void M()
{
// should warn--non-readonly invocation
ToString();
GetHashCode();
Equals(null);
// ok
base.ToString();
base.GetHashCode();
base.Equals(null);
}
}
";
var verifier = CompileAndVerify(csharp);
verifier.VerifyDiagnostics(
// (12,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'.
// ToString();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(12, 9),
// (13,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'.
// GetHashCode();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(13, 9),
// (14,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'.
// Equals(null);
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(14, 9));
// Verify that calls to non-readonly overrides pass the address of a temp, not the address of 'this'
verifier.VerifyIL("S.M", @"
{
// Code size 117 (0x75)
.maxstack 2
.locals init (S V_0)
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: constrained. ""S""
IL_000f: callvirt ""string object.ToString()""
IL_0014: pop
IL_0015: ldarg.0
IL_0016: ldobj ""S""
IL_001b: stloc.0
IL_001c: ldloca.s V_0
IL_001e: constrained. ""S""
IL_0024: callvirt ""int object.GetHashCode()""
IL_0029: pop
IL_002a: ldarg.0
IL_002b: ldobj ""S""
IL_0030: stloc.0
IL_0031: ldloca.s V_0
IL_0033: ldnull
IL_0034: constrained. ""S""
IL_003a: callvirt ""bool object.Equals(object)""
IL_003f: pop
IL_0040: ldarg.0
IL_0041: ldobj ""S""
IL_0046: box ""S""
IL_004b: call ""string System.ValueType.ToString()""
IL_0050: pop
IL_0051: ldarg.0
IL_0052: ldobj ""S""
IL_0057: box ""S""
IL_005c: call ""int System.ValueType.GetHashCode()""
IL_0061: pop
IL_0062: ldarg.0
IL_0063: ldobj ""S""
IL_0068: box ""S""
IL_006d: ldnull
IL_006e: call ""bool System.ValueType.Equals(object)""
IL_0073: pop
IL_0074: ret
}");
}
[Fact]
public void ReadOnlyMethod_ReadOnlyOverrideBaseMethod()
{
var csharp = @"
public struct S
{
// note: GetType can't be overridden
public readonly override string ToString() => throw null;
public readonly override int GetHashCode() => throw null;
public readonly override bool Equals(object o) => throw null;
readonly void M()
{
// no warnings
ToString();
GetHashCode();
Equals(null);
base.ToString();
base.GetHashCode();
base.Equals(null);
}
}
";
var verifier = CompileAndVerify(csharp);
verifier.VerifyDiagnostics();
// Verify that calls to readonly override members pass the address of 'this' (not a temp)
verifier.VerifyIL("S.M", @"
{
// Code size 93 (0x5d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: constrained. ""S""
IL_0007: callvirt ""string object.ToString()""
IL_000c: pop
IL_000d: ldarg.0
IL_000e: constrained. ""S""
IL_0014: callvirt ""int object.GetHashCode()""
IL_0019: pop
IL_001a: ldarg.0
IL_001b: ldnull
IL_001c: constrained. ""S""
IL_0022: callvirt ""bool object.Equals(object)""
IL_0027: pop
IL_0028: ldarg.0
IL_0029: ldobj ""S""
IL_002e: box ""S""
IL_0033: call ""string System.ValueType.ToString()""
IL_0038: pop
IL_0039: ldarg.0
IL_003a: ldobj ""S""
IL_003f: box ""S""
IL_0044: call ""int System.ValueType.GetHashCode()""
IL_0049: pop
IL_004a: ldarg.0
IL_004b: ldobj ""S""
IL_0050: box ""S""
IL_0055: ldnull
IL_0056: call ""bool System.ValueType.Equals(object)""
IL_005b: pop
IL_005c: ret
}");
}
[Fact]
public void ReadOnlyMethod_NewBaseMethod()
{
var csharp = @"
public struct S
{
public new System.Type GetType() => throw null;
public new string ToString() => throw null;
public new int GetHashCode() => throw null;
public new bool Equals(object o) => throw null;
readonly void M()
{
// should warn--non-readonly invocation
GetType();
ToString();
GetHashCode();
Equals(null);
// ok
base.GetType();
base.ToString();
base.GetHashCode();
base.Equals(null);
}
}
";
var verifier = CompileAndVerify(csharp);
verifier.VerifyDiagnostics(
// (12,9): warning CS8655: Call to non-readonly member 'S.GetType()' from a 'readonly' member results in an implicit copy of 'this'.
// GetType();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetType").WithArguments("S.GetType()", "this").WithLocation(12, 9),
// (13,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'.
// ToString();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(13, 9),
// (14,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'.
// GetHashCode();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(14, 9),
// (15,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'.
// Equals(null);
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(15, 9));
// Verify that calls to new non-readonly members pass an address to a temp and that calls to base members use a box.
verifier.VerifyIL("S.M", @"
{
// Code size 131 (0x83)
.maxstack 2
.locals init (S V_0)
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""System.Type S.GetType()""
IL_000e: pop
IL_000f: ldarg.0
IL_0010: ldobj ""S""
IL_0015: stloc.0
IL_0016: ldloca.s V_0
IL_0018: call ""string S.ToString()""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: ldobj ""S""
IL_0024: stloc.0
IL_0025: ldloca.s V_0
IL_0027: call ""int S.GetHashCode()""
IL_002c: pop
IL_002d: ldarg.0
IL_002e: ldobj ""S""
IL_0033: stloc.0
IL_0034: ldloca.s V_0
IL_0036: ldnull
IL_0037: call ""bool S.Equals(object)""
IL_003c: pop
IL_003d: ldarg.0
IL_003e: ldobj ""S""
IL_0043: box ""S""
IL_0048: call ""System.Type object.GetType()""
IL_004d: pop
IL_004e: ldarg.0
IL_004f: ldobj ""S""
IL_0054: box ""S""
IL_0059: call ""string System.ValueType.ToString()""
IL_005e: pop
IL_005f: ldarg.0
IL_0060: ldobj ""S""
IL_0065: box ""S""
IL_006a: call ""int System.ValueType.GetHashCode()""
IL_006f: pop
IL_0070: ldarg.0
IL_0071: ldobj ""S""
IL_0076: box ""S""
IL_007b: ldnull
IL_007c: call ""bool System.ValueType.Equals(object)""
IL_0081: pop
IL_0082: ret
}");
}
[Fact]
public void ReadOnlyMethod_ReadOnlyNewBaseMethod()
{
var csharp = @"
public struct S
{
public readonly new System.Type GetType() => throw null;
public readonly new string ToString() => throw null;
public readonly new int GetHashCode() => throw null;
public readonly new bool Equals(object o) => throw null;
readonly void M()
{
// no warnings
GetType();
ToString();
GetHashCode();
Equals(null);
base.GetType();
base.ToString();
base.GetHashCode();
base.Equals(null);
}
}
";
var verifier = CompileAndVerify(csharp);
verifier.VerifyDiagnostics();
// Verify that calls to readonly new members pass the address of 'this' (not a temp) and that calls to base members use a box.
verifier.VerifyIL("S.M", @"
{
// Code size 99 (0x63)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly System.Type S.GetType()""
IL_0006: pop
IL_0007: ldarg.0
IL_0008: call ""readonly string S.ToString()""
IL_000d: pop
IL_000e: ldarg.0
IL_000f: call ""readonly int S.GetHashCode()""
IL_0014: pop
IL_0015: ldarg.0
IL_0016: ldnull
IL_0017: call ""readonly bool S.Equals(object)""
IL_001c: pop
IL_001d: ldarg.0
IL_001e: ldobj ""S""
IL_0023: box ""S""
IL_0028: call ""System.Type object.GetType()""
IL_002d: pop
IL_002e: ldarg.0
IL_002f: ldobj ""S""
IL_0034: box ""S""
IL_0039: call ""string System.ValueType.ToString()""
IL_003e: pop
IL_003f: ldarg.0
IL_0040: ldobj ""S""
IL_0045: box ""S""
IL_004a: call ""int System.ValueType.GetHashCode()""
IL_004f: pop
IL_0050: ldarg.0
IL_0051: ldobj ""S""
IL_0056: box ""S""
IL_005b: ldnull
IL_005c: call ""bool System.ValueType.Equals(object)""
IL_0061: pop
IL_0062: ret
}");
}
[Fact]
public void ReadOnlyMethod_FixedThis()
{
var csharp = @"
struct S
{
int i;
readonly unsafe void M()
{
fixed (S* sp = &this)
{
sp->i = 42;
}
}
static void Main()
{
var s = new S();
s.M();
System.Console.Write(s.i);
}
}
";
CompileAndVerify(csharp, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "42");
}
public static TheoryData<bool, CSharpParseOptions, Verification> ReadOnlyGetter_LangVersion_Data() =>
new TheoryData<bool, CSharpParseOptions, Verification>
{
{ false, TestOptions.Regular7_3, Verification.Passes },
{ true, null, Verification.Fails }
};
[Theory]
[MemberData(nameof(ReadOnlyGetter_LangVersion_Data))]
public void ReadOnlyGetter_LangVersion(bool isReadOnly, CSharpParseOptions parseOptions, Verification verify)
{
var csharp = @"
struct S
{
public int P { get; }
static readonly S Field = default;
static void M()
{
_ = Field.P;
}
}
";
var verifier = CompileAndVerify(csharp, parseOptions: parseOptions, verify: verify);
var type = ((CSharpCompilation)verifier.Compilation).GetMember<NamedTypeSymbol>("S");
Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsDeclaredReadOnly);
Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsEffectivelyReadOnly);
}
[Fact]
public void ReadOnlyEvent_Emit()
{
var csharp = @"
public struct S
{
public readonly event System.Action E { add { } remove { } }
}
";
CompileAndVerify(csharp, symbolValidator: validate).VerifyDiagnostics();
void validate(ModuleSymbol module)
{
var testStruct = module.ContainingAssembly.GetTypeByMetadataName("S");
var peModule = (PEModuleSymbol)module;
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").AddMethod).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").RemoveMethod).Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.ReadOnlyReferences)]
public class CodeGenReadOnlyStructTests : CompilingTestBase
{
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyStaticField()
{
var text = @"
class Program
{
static readonly S1 sf;
static void Main()
{
System.Console.Write(sf.M1());
System.Console.Write(sf.ToString());
}
readonly struct S1
{
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 37 (0x25)
.maxstack 1
IL_0000: ldsflda ""Program.S1 Program.sf""
IL_0005: call ""string Program.S1.M1()""
IL_000a: call ""void System.Console.Write(string)""
IL_000f: ldsflda ""Program.S1 Program.sf""
IL_0014: constrained. ""Program.S1""
IL_001a: callvirt ""string object.ToString()""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: ret
}");
comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 43 (0x2b)
.maxstack 1
.locals init (Program.S1 V_0)
IL_0000: ldsfld ""Program.S1 Program.sf""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""string Program.S1.M1()""
IL_000d: call ""void System.Console.Write(string)""
IL_0012: ldsfld ""Program.S1 Program.sf""
IL_0017: stloc.0
IL_0018: ldloca.s V_0
IL_001a: constrained. ""Program.S1""
IL_0020: callvirt ""string object.ToString()""
IL_0025: call ""void System.Console.Write(string)""
IL_002a: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyStaticFieldMetadata()
{
var text1 = @"
public readonly struct S1
{
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
";
var comp1 = CreateCompilation(text1, assemblyName: "A");
var ref1 = comp1.EmitToImageReference();
var text = @"
class Program
{
static readonly S1 sf;
static void Main()
{
System.Console.Write(sf.M1());
System.Console.Write(sf.ToString());
}
}
";
var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 37 (0x25)
.maxstack 1
IL_0000: ldsflda ""S1 Program.sf""
IL_0005: call ""string S1.M1()""
IL_000a: call ""void System.Console.Write(string)""
IL_000f: ldsflda ""S1 Program.sf""
IL_0014: constrained. ""S1""
IL_001a: callvirt ""string object.ToString()""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: ret
}");
comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 43 (0x2b)
.maxstack 1
.locals init (S1 V_0)
IL_0000: ldsfld ""S1 Program.sf""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""string S1.M1()""
IL_000d: call ""void System.Console.Write(string)""
IL_0012: ldsfld ""S1 Program.sf""
IL_0017: stloc.0
IL_0018: ldloca.s V_0
IL_001a: constrained. ""S1""
IL_0020: callvirt ""string object.ToString()""
IL_0025: call ""void System.Console.Write(string)""
IL_002a: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyInstanceField()
{
var text = @"
class Program
{
readonly S1 f;
static void Main()
{
var p = new Program();
System.Console.Write(p.f.M1());
System.Console.Write(p.f.ToString());
}
readonly struct S1
{
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 43 (0x2b)
.maxstack 2
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldflda ""Program.S1 Program.f""
IL_000b: call ""string Program.S1.M1()""
IL_0010: call ""void System.Console.Write(string)""
IL_0015: ldflda ""Program.S1 Program.f""
IL_001a: constrained. ""Program.S1""
IL_0020: callvirt ""string object.ToString()""
IL_0025: call ""void System.Console.Write(string)""
IL_002a: ret
}");
comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.Main", @"
{
// Code size 49 (0x31)
.maxstack 2
.locals init (Program.S1 V_0)
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldfld ""Program.S1 Program.f""
IL_000b: stloc.0
IL_000c: ldloca.s V_0
IL_000e: call ""string Program.S1.M1()""
IL_0013: call ""void System.Console.Write(string)""
IL_0018: ldfld ""Program.S1 Program.f""
IL_001d: stloc.0
IL_001e: ldloca.s V_0
IL_0020: constrained. ""Program.S1""
IL_0026: callvirt ""string object.ToString()""
IL_002b: call ""void System.Console.Write(string)""
IL_0030: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyInstanceFieldGeneric()
{
var text = @"
class Program
{
readonly S1<string> f;
static void Main()
{
var p = new Program();
System.Console.Write(p.f.M1(""hello""));
System.Console.Write(p.f.ToString());
}
readonly struct S1<T>
{
public T M1(T arg)
{
return arg;
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2");
comp.VerifyIL("Program.Main", @"
{
// Code size 48 (0x30)
.maxstack 3
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldflda ""Program.S1<string> Program.f""
IL_000b: ldstr ""hello""
IL_0010: call ""string Program.S1<string>.M1(string)""
IL_0015: call ""void System.Console.Write(string)""
IL_001a: ldflda ""Program.S1<string> Program.f""
IL_001f: constrained. ""Program.S1<string>""
IL_0025: callvirt ""string object.ToString()""
IL_002a: call ""void System.Console.Write(string)""
IL_002f: ret
}");
comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2");
comp.VerifyIL("Program.Main", @"
{
// Code size 54 (0x36)
.maxstack 3
.locals init (Program.S1<string> V_0)
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldfld ""Program.S1<string> Program.f""
IL_000b: stloc.0
IL_000c: ldloca.s V_0
IL_000e: ldstr ""hello""
IL_0013: call ""string Program.S1<string>.M1(string)""
IL_0018: call ""void System.Console.Write(string)""
IL_001d: ldfld ""Program.S1<string> Program.f""
IL_0022: stloc.0
IL_0023: ldloca.s V_0
IL_0025: constrained. ""Program.S1<string>""
IL_002b: callvirt ""string object.ToString()""
IL_0030: call ""void System.Console.Write(string)""
IL_0035: ret
}");
}
[Fact]
[CompilerTrait(CompilerFeature.PEVerifyCompat)]
public void InvokeOnReadOnlyInstanceFieldGenericMetadata()
{
var text1 = @"
readonly public struct S1<T>
{
public T M1(T arg)
{
return arg;
}
public override string ToString()
{
return ""2"";
}
}
";
var comp1 = CreateCompilation(text1, assemblyName: "A");
var ref1 = comp1.EmitToImageReference();
var text = @"
class Program
{
readonly S1<string> f;
static void Main()
{
var p = new Program();
System.Console.Write(p.f.M1(""hello""));
System.Console.Write(p.f.ToString());
}
}
";
var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2");
comp.VerifyIL("Program.Main", @"
{
// Code size 48 (0x30)
.maxstack 3
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldflda ""S1<string> Program.f""
IL_000b: ldstr ""hello""
IL_0010: call ""string S1<string>.M1(string)""
IL_0015: call ""void System.Console.Write(string)""
IL_001a: ldflda ""S1<string> Program.f""
IL_001f: constrained. ""S1<string>""
IL_0025: callvirt ""string object.ToString()""
IL_002a: call ""void System.Console.Write(string)""
IL_002f: ret
}");
comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2");
comp.VerifyIL("Program.Main", @"
{
// Code size 54 (0x36)
.maxstack 3
.locals init (S1<string> V_0)
IL_0000: newobj ""Program..ctor()""
IL_0005: dup
IL_0006: ldfld ""S1<string> Program.f""
IL_000b: stloc.0
IL_000c: ldloca.s V_0
IL_000e: ldstr ""hello""
IL_0013: call ""string S1<string>.M1(string)""
IL_0018: call ""void System.Console.Write(string)""
IL_001d: ldfld ""S1<string> Program.f""
IL_0022: stloc.0
IL_0023: ldloca.s V_0
IL_0025: constrained. ""S1<string>""
IL_002b: callvirt ""string object.ToString()""
IL_0030: call ""void System.Console.Write(string)""
IL_0035: ret
}");
}
[Fact]
public void InvokeOnReadOnlyThis()
{
var text = @"
class Program
{
static void Main()
{
Test(default(S1));
}
static void Test(in S1 arg)
{
System.Console.Write(arg.M1());
System.Console.Write(arg.ToString());
}
readonly struct S1
{
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.Test", @"
{
// Code size 29 (0x1d)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""string Program.S1.M1()""
IL_0006: call ""void System.Console.Write(string)""
IL_000b: ldarg.0
IL_000c: constrained. ""Program.S1""
IL_0012: callvirt ""string object.ToString()""
IL_0017: call ""void System.Console.Write(string)""
IL_001c: ret
}");
}
[Fact]
public void InvokeOnThis()
{
var text = @"
class Program
{
static void Main()
{
default(S1).Test();
}
readonly struct S1
{
public void Test()
{
System.Console.Write(this.M1());
System.Console.Write(ToString());
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12");
comp.VerifyIL("Program.S1.Test()", @"
{
// Code size 29 (0x1d)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""string Program.S1.M1()""
IL_0006: call ""void System.Console.Write(string)""
IL_000b: ldarg.0
IL_000c: constrained. ""Program.S1""
IL_0012: callvirt ""string object.ToString()""
IL_0017: call ""void System.Console.Write(string)""
IL_001c: ret
}");
comp.VerifyIL("Program.Main()", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (Program.S1 V_0)
IL_0000: ldloca.s V_0
IL_0002: dup
IL_0003: initobj ""Program.S1""
IL_0009: call ""void Program.S1.Test()""
IL_000e: ret
}");
}
[Fact]
public void InvokeOnThisBaseMethods()
{
var text = @"
class Program
{
static void Main()
{
default(S1).Test();
}
readonly struct S1
{
public void Test()
{
System.Console.Write(this.GetType());
System.Console.Write(ToString());
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"Program+S1Program+S1");
comp.VerifyIL("Program.S1.Test()", @"
{
// Code size 39 (0x27)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldobj ""Program.S1""
IL_0006: box ""Program.S1""
IL_000b: call ""System.Type object.GetType()""
IL_0010: call ""void System.Console.Write(object)""
IL_0015: ldarg.0
IL_0016: constrained. ""Program.S1""
IL_001c: callvirt ""string object.ToString()""
IL_0021: call ""void System.Console.Write(string)""
IL_0026: ret
}");
}
[Fact]
public void AssignThis()
{
var text = @"
class Program
{
static void Main()
{
S1 v = new S1(42);
System.Console.Write(v.x);
S1 v2 = new S1(v);
System.Console.Write(v2.x);
}
readonly struct S1
{
public readonly int x;
public S1(int i)
{
x = i; // OK
}
public S1(S1 arg)
{
this = arg; // OK
}
}
}
";
var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"4242");
comp.VerifyIL("Program.S1..ctor(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int Program.S1.x""
IL_0007: ret
}");
comp.VerifyIL("Program.S1..ctor(Program.S1)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stobj ""Program.S1""
IL_0007: ret
}");
}
[Fact]
public void AssignThisErr()
{
var text = @"
class Program
{
static void Main()
{
}
static void TakesRef(ref S1 arg){}
static void TakesRef(ref int arg){}
readonly struct S1
{
readonly int x;
public S1(int i)
{
x = i; // OK
}
public S1(S1 arg)
{
this = arg; // OK
}
public void Test1()
{
this = default; // error
}
public void Test2()
{
TakesRef(ref this); // error
}
public void Test3()
{
TakesRef(ref this.x); // error
}
}
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (27,13): error CS1604: Cannot assign to 'this' because it is read-only
// this = default; // error
Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this").WithLocation(27, 13),
// (32,26): error CS1605: Cannot use 'this' as a ref or out value because it is read-only
// TakesRef(ref this); // error
Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this").WithLocation(32, 26),
// (37,26): error CS0192: A readonly field cannot be used as a ref or out value (except in a constructor)
// TakesRef(ref this.x); // error
Diagnostic(ErrorCode.ERR_RefReadonly, "this.x").WithLocation(37, 26)
);
}
[Fact]
public void AssignThisNestedMethods()
{
var text = @"
using System;
class Program
{
static void Main()
{
}
static void TakesRef(ref S1 arg){}
static void TakesRef(ref int arg){}
readonly struct S1
{
readonly int x;
public S1(int i)
{
void F() { x = i;} // Error
Action a = () => { x = i;}; // Error
F();
}
public S1(S1 arg)
{
void F() { this = arg;} // Error
Action a = () => { this = arg;}; // Error
F();
}
public void Test1()
{
void F() { this = default;} // Error
Action a = () => { this = default;}; // Error
F();
}
public void Test2()
{
void F() { TakesRef(ref this);} // Error
Action a = () => { TakesRef(ref this);}; // Error
F();
}
public void Test3()
{
void F() { TakesRef(ref this.x);} // Error
Action a = () => { TakesRef(ref this.x);}; // Error
F();
}
}
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (19,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { x = i;} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(19, 24),
// (20,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { x = i;}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(20, 32),
// (26,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { this = arg;} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(26, 24),
// (27,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { this = arg;}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(27, 32),
// (33,24): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { this = default;} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(33, 24),
// (34,32): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { this = default;}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(34, 32),
// (40,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { TakesRef(ref this);} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(40, 37),
// (41,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { TakesRef(ref this);}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(41, 45),
// (47,37): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// void F() { TakesRef(ref this.x);} // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(47, 37),
// (48,45): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.
// Action a = () => { TakesRef(ref this.x);}; // Error
Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(48, 45)
);
}
[Fact]
public void ReadOnlyStructApi()
{
var text = @"
class Program
{
readonly struct S1
{
public S1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
readonly struct S1<T>
{
public S1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
struct S2
{
public S2(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
class C1
{
public C1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
delegate int D1();
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular);
// S1
NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1");
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
void validate(ModuleSymbol module)
{
var test = module.ContainingAssembly.GetTypeByMetadataName("Program+S1");
var peModule = (PEModuleSymbol)module;
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PENamedTypeSymbol)test).Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
CompileAndVerify(comp, symbolValidator: validate);
// S1<T>
namedType = comp.GetTypeByMetadataName("Program+S1`1");
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// T
TypeSymbol type = namedType.TypeParameters[0];
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S1<object>
namedType = namedType.Construct(comp.ObjectType);
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S2
namedType = comp.GetTypeByMetadataName("Program+S2");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind);
// C1
namedType = comp.GetTypeByMetadataName("Program+C1");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind);
// D1
namedType = comp.GetTypeByMetadataName("Program+D1");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind);
// object[]
type = comp.CreateArrayTypeSymbol(comp.ObjectType);
Assert.False(type.IsReadOnly);
// dynamic
type = comp.DynamicType;
Assert.False(type.IsReadOnly);
// object
type = comp.ObjectType;
Assert.False(type.IsReadOnly);
// anonymous type
INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq"));
Assert.False(iNamedType.IsReadOnly);
// pointer type
type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType);
Assert.False(type.IsReadOnly);
// tuple type
iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol()));
Assert.False(iNamedType.IsReadOnly);
// S1 from image
var clientComp = CreateCompilation("", references: new[] { comp.EmitToImageReference() });
NamedTypeSymbol s1 = clientComp.GetTypeByMetadataName("Program+S1");
Assert.True(s1.IsReadOnly);
Assert.Empty(s1.GetAttributes());
Assert.Equal(RefKind.Out, s1.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, s1.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, s1.GetMethod("ToString").ThisParameter.RefKind);
}
[Fact]
public void ReadOnlyStructApiMetadata()
{
var text1 = @"
class Program
{
readonly struct S1
{
public S1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
readonly struct S1<T>
{
public S1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
struct S2
{
public S2(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
class C1
{
public C1(int dummy)
{
}
public string M1()
{
return ""1"";
}
public override string ToString()
{
return ""2"";
}
}
delegate int D1();
}
";
var comp1 = CreateCompilation(text1, assemblyName: "A");
var ref1 = comp1.EmitToImageReference();
var comp = CreateCompilation("//NO CODE HERE", new[] { ref1 }, parseOptions: TestOptions.Regular);
// S1
NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1");
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S1<T>
namedType = comp.GetTypeByMetadataName("Program+S1`1");
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// T
TypeSymbol type = namedType.TypeParameters[0];
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S1<object>
namedType = namedType.Construct(comp.ObjectType);
Assert.True(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind);
// S2
namedType = comp.GetTypeByMetadataName("Program+S2");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind);
// C1
namedType = comp.GetTypeByMetadataName("Program+C1");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind);
// D1
namedType = comp.GetTypeByMetadataName("Program+D1");
Assert.False(namedType.IsReadOnly);
Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind);
Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind);
// object[]
type = comp.CreateArrayTypeSymbol(comp.ObjectType);
Assert.False(type.IsReadOnly);
// dynamic
type = comp.DynamicType;
Assert.False(type.IsReadOnly);
// object
type = comp.ObjectType;
Assert.False(type.IsReadOnly);
// anonymous type
INamedTypeSymbol iNamedType = comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol()), ImmutableArray.Create("qq"));
Assert.False(iNamedType.IsReadOnly);
// pointer type
type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType);
Assert.False(type.IsReadOnly);
// tuple type
iNamedType = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType.GetPublicSymbol(), comp.ObjectType.GetPublicSymbol()));
Assert.False(iNamedType.IsReadOnly);
}
[Fact]
public void CorrectOverloadOfStackAllocSpanChosen()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
unsafe public static void Main()
{
bool condition = false;
var span1 = condition ? stackalloc int[1] : new Span<int>(null, 2);
Console.Write(span1.Length);
var span2 = condition ? stackalloc int[1] : stackalloc int[4];
Console.Write(span2.Length);
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "24", verify: Verification.Fails);
}
[Fact]
public void StackAllocExpressionIL()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public static void Main()
{
Span<int> x = stackalloc int[10];
Console.WriteLine(x.Length);
}
}", TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "10", verify: Verification.Fails).VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (System.Span<int> V_0) //x
IL_0000: ldc.i4.s 40
IL_0002: conv.u
IL_0003: localloc
IL_0005: ldc.i4.s 10
IL_0007: newobj ""System.Span<int>..ctor(void*, int)""
IL_000c: stloc.0
IL_000d: ldloca.s V_0
IL_000f: call ""int System.Span<int>.Length.get""
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ret
}");
}
[Fact]
public void StackAllocSpanLengthNotEvaluatedTwice()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
private static int length = 0;
private static int GetLength()
{
return ++length;
}
public static void Main()
{
for (int i = 0; i < 5; i++)
{
Span<int> x = stackalloc int[GetLength()];
Console.Write(x.Length);
}
}
}", TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "12345", verify: Verification.Fails).VerifyIL("Test.Main", @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (int V_0, //i
System.Span<int> V_1, //x
int V_2)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_0027
IL_0004: call ""int Test.GetLength()""
IL_0009: stloc.2
IL_000a: ldloc.2
IL_000b: conv.u
IL_000c: ldc.i4.4
IL_000d: mul.ovf.un
IL_000e: localloc
IL_0010: ldloc.2
IL_0011: newobj ""System.Span<int>..ctor(void*, int)""
IL_0016: stloc.1
IL_0017: ldloca.s V_1
IL_0019: call ""int System.Span<int>.Length.get""
IL_001e: call ""void System.Console.Write(int)""
IL_0023: ldloc.0
IL_0024: ldc.i4.1
IL_0025: add
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: ldc.i4.5
IL_0029: blt.s IL_0004
IL_002b: ret
}");
}
[Fact]
public void StackAllocSpanLengthConstantFolding()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
public static void Main()
{
const int a = 5, b = 6;
Span<int> x = stackalloc int[a * b];
Console.Write(x.Length);
}
}", TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "30", verify: Verification.Fails).VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (System.Span<int> V_0) //x
IL_0000: ldc.i4.s 120
IL_0002: conv.u
IL_0003: localloc
IL_0005: ldc.i4.s 30
IL_0007: newobj ""System.Span<int>..ctor(void*, int)""
IL_000c: stloc.0
IL_000d: ldloca.s V_0
IL_000f: call ""int System.Span<int>.Length.get""
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ret
}");
}
[Fact]
public void StackAllocSpanLengthOverflow()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
class Test
{
static void M()
{
Span<int> x = stackalloc int[int.MaxValue];
}
public static void Main()
{
try
{
M();
}
catch (OverflowException)
{
Console.WriteLine(""overflow"");
}
}
}", TestOptions.ReleaseExe);
var expectedIL = @"
{
// Code size 22 (0x16)
.maxstack 2
IL_0000: ldc.i4 0x7fffffff
IL_0005: conv.u
IL_0006: ldc.i4.4
IL_0007: mul.ovf.un
IL_0008: localloc
IL_000a: ldc.i4 0x7fffffff
IL_000f: newobj ""System.Span<int>..ctor(void*, int)""
IL_0014: pop
IL_0015: ret
}";
var isx86 = (IntPtr.Size == 4);
if (isx86)
{
CompileAndVerify(comp, expectedOutput: "overflow", verify: Verification.Fails).VerifyIL("Test.M", expectedIL);
}
else
{
// On 64bit the native int does not overflow, so we get StackOverflow instead
// therefore we will just check the IL
CompileAndVerify(comp, verify: Verification.Fails).VerifyIL("Test.M", expectedIL);
}
}
[Fact]
public void ImplicitCastOperatorOnStackAllocIsLoweredCorrectly()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public static void Main()
{
Test obj1 = stackalloc int[10];
Console.Write(""|"");
Test obj2 = stackalloc double[10];
}
public static implicit operator Test(Span<int> value)
{
Console.Write(""SpanOpCalled"");
return default(Test);
}
public static implicit operator Test(double* value)
{
Console.Write(""PointerOpCalled"");
return default(Test);
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "SpanOpCalled|PointerOpCalled", verify: Verification.Fails);
}
[Fact]
public void ExplicitCastOperatorOnStackAllocIsLoweredCorrectly()
{
var comp = CreateCompilationWithMscorlibAndSpan(@"
using System;
unsafe class Test
{
public static void Main()
{
Test obj1 = (Test)stackalloc int[10];
}
public static explicit operator Test(Span<int> value)
{
Console.Write(""SpanOpCalled"");
return default(Test);
}
}", TestOptions.UnsafeReleaseExe);
CompileAndVerify(comp, expectedOutput: "SpanOpCalled", verify: Verification.Fails);
}
[Fact]
public void ReadOnlyMembers_Metadata()
{
var csharp = @"
public struct S
{
public void M1() {}
public readonly void M2() {}
public int P1 { get; set; }
public readonly int P2 => 42;
public int P3 { readonly get => 123; set {} }
public int P4 { get => 123; readonly set {} }
public static int P5 { get; set; }
}
";
CompileAndVerify(csharp, symbolValidator: validate);
void validate(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("S");
var m1 = type.GetMethod("M1");
var m2 = type.GetMethod("M2");
var p1 = type.GetProperty("P1");
var p2 = type.GetProperty("P2");
var p3 = type.GetProperty("P3");
var p4 = type.GetProperty("P4");
var p5 = type.GetProperty("P5");
var peModule = (PEModuleSymbol)module;
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
}
[Fact]
public void ReadOnlyMembers_RefReturn_Metadata()
{
var csharp = @"
public struct S
{
static int i;
public ref int M1() => ref i;
public readonly ref int M2() => ref i;
public ref readonly int M3() => ref i;
public readonly ref readonly int M4() => ref i;
public ref int P1 { get => ref i; }
public readonly ref int P2 { get => ref i; }
public ref readonly int P3 { get => ref i; }
public readonly ref readonly int P4 { get => ref i; }
}
";
CompileAndVerify(csharp, symbolValidator: validate);
void validate(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("S");
var m1 = type.GetMethod("M1");
var m2 = type.GetMethod("M2");
var m3 = type.GetMethod("M3");
var m4 = type.GetMethod("M4");
var p1 = type.GetProperty("P1");
var p2 = type.GetProperty("P2");
var p3 = type.GetProperty("P3");
var p4 = type.GetProperty("P4");
var peModule = (PEModuleSymbol)module;
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m3).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m4).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
}
[Fact]
public void ReadOnlyStruct_ReadOnlyMembers_Metadata()
{
var csharp = @"
// note that both the type and member declarations are marked 'readonly'
public readonly struct S
{
public void M1() {}
public readonly void M2() {}
public int P1 { get; }
public readonly int P2 => 42;
public int P3 { readonly get => 123; set {} }
public int P4 { get => 123; readonly set {} }
public static int P5 { get; set; }
}
";
CompileAndVerify(csharp, symbolValidator: validate);
void validate(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("S");
var m1 = type.GetMethod("M1");
var m2 = type.GetMethod("M2");
var p1 = type.GetProperty("P1");
var p2 = type.GetProperty("P2");
var p3 = type.GetProperty("P3");
var p4 = type.GetProperty("P4");
var p5 = type.GetProperty("P5");
var peModule = (PEModuleSymbol)module;
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m1).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)m2).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p1).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p1.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p2).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p2.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p3).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p3.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p4).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p4.SetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEPropertySymbol)p5).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.GetMethod).Signature.ReturnParam.Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Handle));
Assert.False(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)p5.SetMethod).Signature.ReturnParam.Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
}
[Fact]
public void ReadOnlyMembers_MetadataRoundTrip()
{
var external = @"
using System;
public struct S1
{
public void M1() {}
public readonly void M2() {}
public int P1 { get; set; }
public readonly int P2 => 42;
public int P3 { readonly get => 123; set {} }
public int P4 { get => 123; readonly set {} }
public static int P5 { get; set; }
public readonly event Action<EventArgs> E { add {} remove {} }
}
public readonly struct S2
{
public void M1() {}
public int P1 { get; }
public int P2 => 42;
public int P3 { set {} }
public static int P4 { get; set; }
public event Action<EventArgs> E { add {} remove {} }
}
";
var externalComp = CreateCompilation(external);
externalComp.VerifyDiagnostics();
verify(externalComp);
var comp = CreateCompilation("", references: new[] { externalComp.EmitToImageReference() });
verify(comp);
var comp2 = CreateCompilation("", references: new[] { externalComp.ToMetadataReference() });
verify(comp2);
void verify(CSharpCompilation comp)
{
var s1 = comp.GetMember<NamedTypeSymbol>("S1");
verifyReadOnly(s1.GetMethod("M1"), false, RefKind.Ref);
verifyReadOnly(s1.GetMethod("M2"), true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P1").SetMethod, false, RefKind.Ref);
verifyReadOnly(s1.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P3").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P3").SetMethod, false, RefKind.Ref);
verifyReadOnly(s1.GetProperty("P4").GetMethod, false, RefKind.Ref);
verifyReadOnly(s1.GetProperty("P4").SetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetProperty("P5").GetMethod, false, null);
verifyReadOnly(s1.GetProperty("P5").SetMethod, false, null);
verifyReadOnly(s1.GetEvent("E").AddMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s1.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly);
var s2 = comp.GetMember<NamedTypeSymbol>("S2");
verifyReadOnly(s2.GetMethod("M1"), true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetProperty("P1").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetProperty("P2").GetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetProperty("P3").SetMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetProperty("P4").GetMethod, false, null);
verifyReadOnly(s2.GetProperty("P4").SetMethod, false, null);
verifyReadOnly(s2.GetEvent("E").AddMethod, true, RefKind.RefReadOnly);
verifyReadOnly(s2.GetEvent("E").RemoveMethod, true, RefKind.RefReadOnly);
void verifyReadOnly(MethodSymbol method, bool isReadOnly, RefKind? refKind)
{
Assert.Equal(isReadOnly, method.IsEffectivelyReadOnly);
Assert.Equal(refKind, method.ThisParameter?.RefKind);
}
}
}
[Fact]
public void StaticReadOnlyMethod_FromMetadata()
{
var il = @"
.class private auto ansi '<Module>'
{
} // end of class <Module>
.class public auto ansi beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute
extends [mscorlib]System.Attribute
{
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2050
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Attribute::.ctor()
IL_0006: ret
} // end of method IsReadOnlyAttribute::.ctor
} // end of class System.Runtime.CompilerServices.IsReadOnlyAttribute
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
// Methods
.method public hidebysig
instance void M1 () cil managed
{
.custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (
01 00 00 00
)
// Method begins at RVA 0x2058
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method S::M1
// Methods
.method public hidebysig static
void M2 () cil managed
{
.custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (
01 00 00 00
)
// Method begins at RVA 0x2058
// Code size 1 (0x1)
.maxstack 8
IL_0000: ret
} // end of method S::M2
} // end of class S
";
var ilRef = CompileIL(il);
var comp = CreateCompilation("", references: new[] { ilRef });
var s = comp.GetMember<NamedTypeSymbol>("S");
var m1 = s.GetMethod("M1");
Assert.True(m1.IsDeclaredReadOnly);
Assert.True(m1.IsEffectivelyReadOnly);
// even though the IsReadOnlyAttribute is in metadata,
// we ruled out the possibility of the method being readonly because it's static
var m2 = s.GetMethod("M2");
Assert.False(m2.IsDeclaredReadOnly);
Assert.False(m2.IsEffectivelyReadOnly);
}
[Fact]
public void ReadOnlyMethod_CallNormalMethod()
{
var csharp = @"
public struct S
{
public int i;
public readonly void M1()
{
// should create local copy
M2();
System.Console.Write(i);
// explicit local copy, no warning
var copy = this;
copy.M2();
System.Console.Write(copy.i);
}
void M2()
{
i = 23;
}
static void Main()
{
var s = new S { i = 1 };
s.M1();
}
}
";
var verifier = CompileAndVerify(csharp, expectedOutput: "123");
verifier.VerifyDiagnostics(
// (9,9): warning CS8655: Call to non-readonly member 'S.M2()' from a 'readonly' member results in an implicit copy of 'this'.
// M2();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "M2").WithArguments("S.M2()", "this").WithLocation(9, 9));
verifier.VerifyIL("S.M1", @"
{
// Code size 51 (0x33)
.maxstack 1
.locals init (S V_0, //copy
S V_1)
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: stloc.1
IL_0007: ldloca.s V_1
IL_0009: call ""void S.M2()""
IL_000e: ldarg.0
IL_000f: ldfld ""int S.i""
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ldarg.0
IL_001a: ldobj ""S""
IL_001f: stloc.0
IL_0020: ldloca.s V_0
IL_0022: call ""void S.M2()""
IL_0027: ldloc.0
IL_0028: ldfld ""int S.i""
IL_002d: call ""void System.Console.Write(int)""
IL_0032: ret
}");
}
[Fact]
public void InMethod_CallNormalMethod()
{
var csharp = @"
public struct S
{
public int i;
public static void M1(in S s)
{
// should create local copy
s.M2();
System.Console.Write(s.i);
// explicit local copy, no warning
var copy = s;
copy.M2();
System.Console.Write(copy.i);
}
void M2()
{
i = 23;
}
static void Main()
{
var s = new S { i = 1 };
M1(in s);
}
}
";
var verifier = CompileAndVerify(csharp, expectedOutput: "123");
// should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968)
verifier.VerifyDiagnostics();
verifier.VerifyIL("S.M1", @"
{
// Code size 51 (0x33)
.maxstack 1
.locals init (S V_0, //copy
S V_1)
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: stloc.1
IL_0007: ldloca.s V_1
IL_0009: call ""void S.M2()""
IL_000e: ldarg.0
IL_000f: ldfld ""int S.i""
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ldarg.0
IL_001a: ldobj ""S""
IL_001f: stloc.0
IL_0020: ldloca.s V_0
IL_0022: call ""void S.M2()""
IL_0027: ldloc.0
IL_0028: ldfld ""int S.i""
IL_002d: call ""void System.Console.Write(int)""
IL_0032: ret
}");
}
[Fact]
public void InMethod_CallMethodFromMetadata()
{
var external = @"
public struct S
{
public int i;
public readonly void M1() {}
public void M2()
{
i = 23;
}
}
";
var image = CreateCompilation(external).EmitToImageReference();
var csharp = @"
public static class C
{
public static void M1(in S s)
{
// should not copy, no warning
s.M1();
System.Console.Write(s.i);
// should create local copy, warn in warning wave
s.M2();
System.Console.Write(s.i);
// explicit local copy, no warning
var copy = s;
copy.M2();
System.Console.Write(copy.i);
}
static void Main()
{
var s = new S { i = 1 };
M1(in s);
}
}
";
var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123");
// should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968)
verifier.VerifyDiagnostics();
verifier.VerifyIL("C.M1", @"
{
// Code size 68 (0x44)
.maxstack 1
.locals init (S V_0, //copy
S V_1)
IL_0000: ldarg.0
IL_0001: call ""readonly void S.M1()""
IL_0006: ldarg.0
IL_0007: ldfld ""int S.i""
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldarg.0
IL_0012: ldobj ""S""
IL_0017: stloc.1
IL_0018: ldloca.s V_1
IL_001a: call ""void S.M2()""
IL_001f: ldarg.0
IL_0020: ldfld ""int S.i""
IL_0025: call ""void System.Console.Write(int)""
IL_002a: ldarg.0
IL_002b: ldobj ""S""
IL_0030: stloc.0
IL_0031: ldloca.s V_0
IL_0033: call ""void S.M2()""
IL_0038: ldloc.0
IL_0039: ldfld ""int S.i""
IL_003e: call ""void System.Console.Write(int)""
IL_0043: ret
}");
}
[Fact]
public void InMethod_CallGetAccessorFromMetadata()
{
var external = @"
public struct S
{
public int i;
public readonly int P1 => 42;
public int P2 => i = 23;
}
";
var image = CreateCompilation(external).EmitToImageReference();
var csharp = @"
public static class C
{
public static void M1(in S s)
{
// should not copy, no warning
_ = s.P1;
System.Console.Write(s.i);
// should create local copy, warn in warning wave
_ = s.P2;
System.Console.Write(s.i);
// explicit local copy, no warning
var copy = s;
_ = copy.P2;
System.Console.Write(copy.i);
}
static void Main()
{
var s = new S { i = 1 };
M1(in s);
}
}
";
var verifier = CompileAndVerify(csharp, references: new[] { image }, expectedOutput: "1123");
// should warn about calling s.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968)
verifier.VerifyDiagnostics();
verifier.VerifyIL("C.M1", @"
{
// Code size 71 (0x47)
.maxstack 1
.locals init (S V_0, //copy
S V_1)
IL_0000: ldarg.0
IL_0001: call ""readonly int S.P1.get""
IL_0006: pop
IL_0007: ldarg.0
IL_0008: ldfld ""int S.i""
IL_000d: call ""void System.Console.Write(int)""
IL_0012: ldarg.0
IL_0013: ldobj ""S""
IL_0018: stloc.1
IL_0019: ldloca.s V_1
IL_001b: call ""int S.P2.get""
IL_0020: pop
IL_0021: ldarg.0
IL_0022: ldfld ""int S.i""
IL_0027: call ""void System.Console.Write(int)""
IL_002c: ldarg.0
IL_002d: ldobj ""S""
IL_0032: stloc.0
IL_0033: ldloca.s V_0
IL_0035: call ""int S.P2.get""
IL_003a: pop
IL_003b: ldloc.0
IL_003c: ldfld ""int S.i""
IL_0041: call ""void System.Console.Write(int)""
IL_0046: ret
}");
}
[Fact]
public void ReadOnlyMethod_CallReadOnlyMethod()
{
var csharp = @"
public struct S
{
public int i;
public readonly int M1() => M2() + 1;
public readonly int M2() => i;
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S.M1", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly int S.M2()""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void ReadOnlyGetAccessor_CallReadOnlyGetAccessor()
{
var csharp = @"
public struct S
{
public int i;
public readonly int P1 { get => P2 + 1; }
public readonly int P2 { get => i; }
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S.P1.get", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly int S.P2.get""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void ReadOnlyGetAccessor_CallAutoGetAccessor()
{
var csharp = @"
public struct S
{
public readonly int P1 { get => P2 + 1; }
public int P2 { get; }
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S.P1.get", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly int S.P2.get""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void InParam_CallReadOnlyMethod()
{
var csharp = @"
public struct S
{
public int i;
public static int M1(in S s) => s.M2() + 1;
public readonly int M2() => i;
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S.M1", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly int S.M2()""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void ReadOnlyMethod_CallReadOnlyMethodOnField()
{
var csharp = @"
public struct S1
{
public readonly void M1() {}
}
public struct S2
{
S1 s1;
public readonly void M2()
{
s1.M1();
}
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S2.M2", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldflda ""S1 S2.s1""
IL_0006: call ""readonly void S1.M1()""
IL_000b: ret
}");
comp.VerifyDiagnostics(
// (9,8): warning CS0649: Field 'S2.s1' is never assigned to, and will always have its default value
// S1 s1;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s1").WithArguments("S2.s1", "").WithLocation(9, 8)
);
}
[Fact]
public void ReadOnlyMethod_CallNormalMethodOnField()
{
var csharp = @"
public struct S1
{
public void M1() {}
}
public struct S2
{
S1 s1;
public readonly void M2()
{
s1.M1();
}
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyIL("S2.M2", @"
{
// Code size 15 (0xf)
.maxstack 1
.locals init (S1 V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""S1 S2.s1""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""void S1.M1()""
IL_000e: ret
}");
// should warn about calling s2.M2 in warning wave (see https://github.com/dotnet/roslyn/issues/33968)
comp.VerifyDiagnostics();
}
[Fact]
public void ReadOnlyMethod_CallBaseMethod()
{
var csharp = @"
public struct S
{
readonly void M()
{
// no warnings for calls to base members
GetType();
ToString();
GetHashCode();
Equals(null);
}
}
";
var comp = CompileAndVerify(csharp);
comp.VerifyDiagnostics();
// ToString/GetHashCode/Equals should pass the address of 'this' (not a temp). GetType should box 'this'.
comp.VerifyIL("S.M", @"
{
// Code size 58 (0x3a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: box ""S""
IL_000b: call ""System.Type object.GetType()""
IL_0010: pop
IL_0011: ldarg.0
IL_0012: constrained. ""S""
IL_0018: callvirt ""string object.ToString()""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: constrained. ""S""
IL_0025: callvirt ""int object.GetHashCode()""
IL_002a: pop
IL_002b: ldarg.0
IL_002c: ldnull
IL_002d: constrained. ""S""
IL_0033: callvirt ""bool object.Equals(object)""
IL_0038: pop
IL_0039: ret
}");
}
[Fact]
public void ReadOnlyMethod_OverrideBaseMethod()
{
var csharp = @"
public struct S
{
// note: GetType can't be overridden
public override string ToString() => throw null;
public override int GetHashCode() => throw null;
public override bool Equals(object o) => throw null;
readonly void M()
{
// should warn--non-readonly invocation
ToString();
GetHashCode();
Equals(null);
// ok
base.ToString();
base.GetHashCode();
base.Equals(null);
}
}
";
var verifier = CompileAndVerify(csharp);
verifier.VerifyDiagnostics(
// (12,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'.
// ToString();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(12, 9),
// (13,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'.
// GetHashCode();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(13, 9),
// (14,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'.
// Equals(null);
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(14, 9));
// Verify that calls to non-readonly overrides pass the address of a temp, not the address of 'this'
verifier.VerifyIL("S.M", @"
{
// Code size 117 (0x75)
.maxstack 2
.locals init (S V_0)
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: constrained. ""S""
IL_000f: callvirt ""string object.ToString()""
IL_0014: pop
IL_0015: ldarg.0
IL_0016: ldobj ""S""
IL_001b: stloc.0
IL_001c: ldloca.s V_0
IL_001e: constrained. ""S""
IL_0024: callvirt ""int object.GetHashCode()""
IL_0029: pop
IL_002a: ldarg.0
IL_002b: ldobj ""S""
IL_0030: stloc.0
IL_0031: ldloca.s V_0
IL_0033: ldnull
IL_0034: constrained. ""S""
IL_003a: callvirt ""bool object.Equals(object)""
IL_003f: pop
IL_0040: ldarg.0
IL_0041: ldobj ""S""
IL_0046: box ""S""
IL_004b: call ""string System.ValueType.ToString()""
IL_0050: pop
IL_0051: ldarg.0
IL_0052: ldobj ""S""
IL_0057: box ""S""
IL_005c: call ""int System.ValueType.GetHashCode()""
IL_0061: pop
IL_0062: ldarg.0
IL_0063: ldobj ""S""
IL_0068: box ""S""
IL_006d: ldnull
IL_006e: call ""bool System.ValueType.Equals(object)""
IL_0073: pop
IL_0074: ret
}");
}
[Fact]
public void ReadOnlyMethod_ReadOnlyOverrideBaseMethod()
{
var csharp = @"
public struct S
{
// note: GetType can't be overridden
public readonly override string ToString() => throw null;
public readonly override int GetHashCode() => throw null;
public readonly override bool Equals(object o) => throw null;
readonly void M()
{
// no warnings
ToString();
GetHashCode();
Equals(null);
base.ToString();
base.GetHashCode();
base.Equals(null);
}
}
";
var verifier = CompileAndVerify(csharp);
verifier.VerifyDiagnostics();
// Verify that calls to readonly override members pass the address of 'this' (not a temp)
verifier.VerifyIL("S.M", @"
{
// Code size 93 (0x5d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: constrained. ""S""
IL_0007: callvirt ""string object.ToString()""
IL_000c: pop
IL_000d: ldarg.0
IL_000e: constrained. ""S""
IL_0014: callvirt ""int object.GetHashCode()""
IL_0019: pop
IL_001a: ldarg.0
IL_001b: ldnull
IL_001c: constrained. ""S""
IL_0022: callvirt ""bool object.Equals(object)""
IL_0027: pop
IL_0028: ldarg.0
IL_0029: ldobj ""S""
IL_002e: box ""S""
IL_0033: call ""string System.ValueType.ToString()""
IL_0038: pop
IL_0039: ldarg.0
IL_003a: ldobj ""S""
IL_003f: box ""S""
IL_0044: call ""int System.ValueType.GetHashCode()""
IL_0049: pop
IL_004a: ldarg.0
IL_004b: ldobj ""S""
IL_0050: box ""S""
IL_0055: ldnull
IL_0056: call ""bool System.ValueType.Equals(object)""
IL_005b: pop
IL_005c: ret
}");
}
[Fact]
public void ReadOnlyMethod_NewBaseMethod()
{
var csharp = @"
public struct S
{
public new System.Type GetType() => throw null;
public new string ToString() => throw null;
public new int GetHashCode() => throw null;
public new bool Equals(object o) => throw null;
readonly void M()
{
// should warn--non-readonly invocation
GetType();
ToString();
GetHashCode();
Equals(null);
// ok
base.GetType();
base.ToString();
base.GetHashCode();
base.Equals(null);
}
}
";
var verifier = CompileAndVerify(csharp);
verifier.VerifyDiagnostics(
// (12,9): warning CS8655: Call to non-readonly member 'S.GetType()' from a 'readonly' member results in an implicit copy of 'this'.
// GetType();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetType").WithArguments("S.GetType()", "this").WithLocation(12, 9),
// (13,9): warning CS8655: Call to non-readonly member 'S.ToString()' from a 'readonly' member results in an implicit copy of 'this'.
// ToString();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "ToString").WithArguments("S.ToString()", "this").WithLocation(13, 9),
// (14,9): warning CS8655: Call to non-readonly member 'S.GetHashCode()' from a 'readonly' member results in an implicit copy of 'this'.
// GetHashCode();
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "GetHashCode").WithArguments("S.GetHashCode()", "this").WithLocation(14, 9),
// (15,9): warning CS8655: Call to non-readonly member 'S.Equals(object)' from a 'readonly' member results in an implicit copy of 'this'.
// Equals(null);
Diagnostic(ErrorCode.WRN_ImplicitCopyInReadOnlyMember, "Equals").WithArguments("S.Equals(object)", "this").WithLocation(15, 9));
// Verify that calls to new non-readonly members pass an address to a temp and that calls to base members use a box.
verifier.VerifyIL("S.M", @"
{
// Code size 131 (0x83)
.maxstack 2
.locals init (S V_0)
IL_0000: ldarg.0
IL_0001: ldobj ""S""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""System.Type S.GetType()""
IL_000e: pop
IL_000f: ldarg.0
IL_0010: ldobj ""S""
IL_0015: stloc.0
IL_0016: ldloca.s V_0
IL_0018: call ""string S.ToString()""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: ldobj ""S""
IL_0024: stloc.0
IL_0025: ldloca.s V_0
IL_0027: call ""int S.GetHashCode()""
IL_002c: pop
IL_002d: ldarg.0
IL_002e: ldobj ""S""
IL_0033: stloc.0
IL_0034: ldloca.s V_0
IL_0036: ldnull
IL_0037: call ""bool S.Equals(object)""
IL_003c: pop
IL_003d: ldarg.0
IL_003e: ldobj ""S""
IL_0043: box ""S""
IL_0048: call ""System.Type object.GetType()""
IL_004d: pop
IL_004e: ldarg.0
IL_004f: ldobj ""S""
IL_0054: box ""S""
IL_0059: call ""string System.ValueType.ToString()""
IL_005e: pop
IL_005f: ldarg.0
IL_0060: ldobj ""S""
IL_0065: box ""S""
IL_006a: call ""int System.ValueType.GetHashCode()""
IL_006f: pop
IL_0070: ldarg.0
IL_0071: ldobj ""S""
IL_0076: box ""S""
IL_007b: ldnull
IL_007c: call ""bool System.ValueType.Equals(object)""
IL_0081: pop
IL_0082: ret
}");
}
[Fact]
public void ReadOnlyMethod_ReadOnlyNewBaseMethod()
{
var csharp = @"
public struct S
{
public readonly new System.Type GetType() => throw null;
public readonly new string ToString() => throw null;
public readonly new int GetHashCode() => throw null;
public readonly new bool Equals(object o) => throw null;
readonly void M()
{
// no warnings
GetType();
ToString();
GetHashCode();
Equals(null);
base.GetType();
base.ToString();
base.GetHashCode();
base.Equals(null);
}
}
";
var verifier = CompileAndVerify(csharp);
verifier.VerifyDiagnostics();
// Verify that calls to readonly new members pass the address of 'this' (not a temp) and that calls to base members use a box.
verifier.VerifyIL("S.M", @"
{
// Code size 99 (0x63)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""readonly System.Type S.GetType()""
IL_0006: pop
IL_0007: ldarg.0
IL_0008: call ""readonly string S.ToString()""
IL_000d: pop
IL_000e: ldarg.0
IL_000f: call ""readonly int S.GetHashCode()""
IL_0014: pop
IL_0015: ldarg.0
IL_0016: ldnull
IL_0017: call ""readonly bool S.Equals(object)""
IL_001c: pop
IL_001d: ldarg.0
IL_001e: ldobj ""S""
IL_0023: box ""S""
IL_0028: call ""System.Type object.GetType()""
IL_002d: pop
IL_002e: ldarg.0
IL_002f: ldobj ""S""
IL_0034: box ""S""
IL_0039: call ""string System.ValueType.ToString()""
IL_003e: pop
IL_003f: ldarg.0
IL_0040: ldobj ""S""
IL_0045: box ""S""
IL_004a: call ""int System.ValueType.GetHashCode()""
IL_004f: pop
IL_0050: ldarg.0
IL_0051: ldobj ""S""
IL_0056: box ""S""
IL_005b: ldnull
IL_005c: call ""bool System.ValueType.Equals(object)""
IL_0061: pop
IL_0062: ret
}");
}
[Fact]
public void ReadOnlyMethod_FixedThis()
{
var csharp = @"
struct S
{
int i;
readonly unsafe void M()
{
fixed (S* sp = &this)
{
sp->i = 42;
}
}
static void Main()
{
var s = new S();
s.M();
System.Console.Write(s.i);
}
}
";
CompileAndVerify(csharp, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "42");
}
public static TheoryData<bool, CSharpParseOptions, Verification> ReadOnlyGetter_LangVersion_Data() =>
new TheoryData<bool, CSharpParseOptions, Verification>
{
{ false, TestOptions.Regular7_3, Verification.Passes },
{ true, null, Verification.Fails }
};
[Theory]
[MemberData(nameof(ReadOnlyGetter_LangVersion_Data))]
public void ReadOnlyGetter_LangVersion(bool isReadOnly, CSharpParseOptions parseOptions, Verification verify)
{
var csharp = @"
struct S
{
public int P { get; }
static readonly S Field = default;
static void M()
{
_ = Field.P;
}
}
";
var verifier = CompileAndVerify(csharp, parseOptions: parseOptions, verify: verify);
var type = ((CSharpCompilation)verifier.Compilation).GetMember<NamedTypeSymbol>("S");
Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsDeclaredReadOnly);
Assert.Equal(isReadOnly, type.GetProperty("P").GetMethod.IsEffectivelyReadOnly);
}
[Fact]
public void ReadOnlyEvent_Emit()
{
var csharp = @"
public struct S
{
public readonly event System.Action E { add { } remove { } }
}
";
CompileAndVerify(csharp, symbolValidator: validate).VerifyDiagnostics();
void validate(ModuleSymbol module)
{
var testStruct = module.ContainingAssembly.GetTypeByMetadataName("S");
var peModule = (PEModuleSymbol)module;
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").AddMethod).Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)testStruct.GetEvent("E").RemoveMethod).Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
}
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Workspaces/Core/Portable/Options/SerializableOptionSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Options
{
/// <summary>
/// Serializable implementation of <see cref="OptionSet"/> for <see cref="Solution.Options"/>.
/// It contains prepopulated fetched option values for all serializable options and values, and delegates to <see cref="WorkspaceOptionSet"/> for non-serializable values.
/// It ensures a contract that values are immutable from this instance once observed.
/// </summary>
internal sealed partial class SerializableOptionSet : OptionSet
{
/// <summary>
/// Languages for which all the applicable serializable options have been prefetched and saved in <see cref="_serializableOptionValues"/>.
/// </summary>
private readonly ImmutableHashSet<string> _languages;
/// <summary>
/// Fallback option set for non-serializable options. See comments on <see cref="WorkspaceOptionSet"/> for more details.
/// </summary>
private readonly WorkspaceOptionSet _workspaceOptionSet;
/// <summary>
/// All serializable options for <see cref="_languages"/>.
/// </summary>
private readonly ImmutableHashSet<IOption> _serializableOptions;
/// <summary>
/// Prefetched option values for all <see cref="_serializableOptions"/> applicable for <see cref="_languages"/>.
/// </summary>
private readonly ImmutableDictionary<OptionKey, object?> _serializableOptionValues;
/// <summary>
/// Set of changed options in this option set which are serializable.
/// </summary>
private readonly ImmutableHashSet<OptionKey> _changedOptionKeysSerializable;
/// <summary>
/// Set of changed options in this option set which are non-serializable.
/// </summary>
private readonly ImmutableHashSet<OptionKey> _changedOptionKeysNonSerializable;
private SerializableOptionSet(
ImmutableHashSet<string> languages,
WorkspaceOptionSet workspaceOptionSet,
ImmutableHashSet<IOption> serializableOptions,
ImmutableDictionary<OptionKey, object?> values,
ImmutableHashSet<OptionKey> changedOptionKeysSerializable,
ImmutableHashSet<OptionKey> changedOptionKeysNonSerializable)
{
Debug.Assert(languages.All(RemoteSupportedLanguages.IsSupported));
_languages = languages;
_workspaceOptionSet = workspaceOptionSet;
_serializableOptions = serializableOptions;
_serializableOptionValues = values;
_changedOptionKeysSerializable = changedOptionKeysSerializable;
_changedOptionKeysNonSerializable = changedOptionKeysNonSerializable;
Debug.Assert(values.Keys.All(ShouldSerialize));
Debug.Assert(changedOptionKeysSerializable.All(optionKey => ShouldSerialize(optionKey)));
Debug.Assert(changedOptionKeysNonSerializable.All(optionKey => !ShouldSerialize(optionKey)));
}
internal SerializableOptionSet(
ImmutableHashSet<string> languages,
IOptionService optionService,
ImmutableHashSet<IOption> serializableOptions,
ImmutableDictionary<OptionKey, object?> values,
ImmutableHashSet<OptionKey> changedOptionKeysSerializable)
: this(languages, new WorkspaceOptionSet(optionService), serializableOptions, values, changedOptionKeysSerializable, changedOptionKeysNonSerializable: ImmutableHashSet<OptionKey>.Empty)
{
}
/// <summary>
/// Returns an option set with all the serializable option values prefetched for given <paramref name="languages"/>,
/// while also retaining all the explicitly changed option values in this option set for any language.
/// NOTE: All the provided <paramref name="languages"/> must be <see cref="RemoteSupportedLanguages.IsSupported(string)"/>.
/// </summary>
public SerializableOptionSet WithLanguages(ImmutableHashSet<string> languages)
{
Debug.Assert(languages.All(RemoteSupportedLanguages.IsSupported));
if (_languages.SetEquals(languages))
{
return this;
}
// First create a base option set for the given languages.
var newOptionSet = _workspaceOptionSet.OptionService.GetSerializableOptionsSnapshot(languages);
// Then apply all the changed options from the current option set to the new option set.
foreach (var changedOption in this.GetChangedOptions())
{
var valueInNewOptionSet = newOptionSet.GetOption(changedOption);
var changedValueInThisOptionSet = this.GetOption(changedOption);
if (!Equals(changedValueInThisOptionSet, valueInNewOptionSet))
{
newOptionSet = (SerializableOptionSet)newOptionSet.WithChangedOption(changedOption, changedValueInThisOptionSet);
}
}
return newOptionSet;
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)]
private protected override object? GetOptionCore(OptionKey optionKey)
{
if (_serializableOptionValues.TryGetValue(optionKey, out var value))
{
return value;
}
return _workspaceOptionSet.GetOption(optionKey);
}
private bool ShouldSerialize(OptionKey optionKey)
=> _serializableOptions.Contains(optionKey.Option) &&
(!optionKey.Option.IsPerLanguage || _languages.Contains(optionKey.Language!));
public override OptionSet WithChangedOption(OptionKey optionKey, object? value)
{
// Make sure we first load this in current optionset
var currentValue = this.GetOption(optionKey);
// Check if the new value is the same as the current value.
if (Equals(value, currentValue))
{
// Return a cloned option set as the public API 'WithChangedOption' guarantees a new option set is returned.
return new SerializableOptionSet(_languages, _workspaceOptionSet, _serializableOptions,
_serializableOptionValues, _changedOptionKeysSerializable, _changedOptionKeysNonSerializable);
}
WorkspaceOptionSet workspaceOptionSet;
ImmutableDictionary<OptionKey, object?> serializableOptionValues;
ImmutableHashSet<OptionKey> changedOptionKeysSerializable;
ImmutableHashSet<OptionKey> changedOptionKeysNonSerializable;
if (ShouldSerialize(optionKey))
{
workspaceOptionSet = _workspaceOptionSet;
serializableOptionValues = _serializableOptionValues.SetItem(optionKey, value);
changedOptionKeysSerializable = _changedOptionKeysSerializable.Add(optionKey);
changedOptionKeysNonSerializable = _changedOptionKeysNonSerializable;
}
else
{
workspaceOptionSet = (WorkspaceOptionSet)_workspaceOptionSet.WithChangedOption(optionKey, value);
serializableOptionValues = _serializableOptionValues;
changedOptionKeysSerializable = _changedOptionKeysSerializable;
changedOptionKeysNonSerializable = _changedOptionKeysNonSerializable.Add(optionKey);
}
return new SerializableOptionSet(_languages, workspaceOptionSet, _serializableOptions,
serializableOptionValues, changedOptionKeysSerializable, changedOptionKeysNonSerializable);
}
/// <summary>
/// Gets a list of all the options that were changed.
/// </summary>
internal IEnumerable<OptionKey> GetChangedOptions()
=> _changedOptionKeysSerializable.Concat(_changedOptionKeysNonSerializable);
internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet? optionSet)
{
if (optionSet == this)
{
yield break;
}
foreach (var key in GetChangedOptions())
{
var currentValue = optionSet?.GetOption(key);
var changedValue = this.GetOption(key);
if (!object.Equals(currentValue, changedValue))
{
yield return key;
}
}
}
public void Serialize(ObjectWriter writer, CancellationToken cancellationToken)
{
// We serialize the following contents from this option set:
// 1. Languages
// 2. Prefetched serializable option key-value pairs
// 3. Changed option keys.
// NOTE: keep the serialization in sync with Deserialize method below.
cancellationToken.ThrowIfCancellationRequested();
writer.WriteInt32(_languages.Count);
foreach (var language in _languages.Order())
{
Debug.Assert(RemoteSupportedLanguages.IsSupported(language));
writer.WriteString(language);
}
var valuesBuilder = new SortedDictionary<OptionKey, (OptionValueKind, object?)>(OptionKeyComparer.Instance);
foreach (var (optionKey, value) in _serializableOptionValues)
{
Debug.Assert(ShouldSerialize(optionKey));
if (!_serializableOptions.Contains(optionKey.Option))
continue;
OptionValueKind kind;
switch (value)
{
case ICodeStyleOption:
if (optionKey.Option.Type.GenericTypeArguments.Length != 1)
continue;
kind = OptionValueKind.CodeStyleOption;
break;
case NamingStylePreferences:
kind = OptionValueKind.NamingStylePreferences;
break;
default:
kind = value != null && value.GetType().IsEnum ? OptionValueKind.Enum : OptionValueKind.Object;
break;
}
valuesBuilder.Add(optionKey, (kind, value));
}
writer.WriteInt32(valuesBuilder.Count);
foreach (var (optionKey, (kind, value)) in valuesBuilder)
{
SerializeOptionKey(optionKey);
writer.WriteInt32((int)kind);
if (kind == OptionValueKind.Enum)
{
RoslynDebug.Assert(value != null);
writer.WriteInt32((int)value);
}
else if (kind is OptionValueKind.CodeStyleOption or OptionValueKind.NamingStylePreferences)
{
RoslynDebug.Assert(value != null);
((IObjectWritable)value).WriteTo(writer);
}
else
{
writer.WriteValue(value);
}
}
writer.WriteInt32(_changedOptionKeysSerializable.Count);
foreach (var changedKey in _changedOptionKeysSerializable.OrderBy(OptionKeyComparer.Instance))
SerializeOptionKey(changedKey);
return;
void SerializeOptionKey(OptionKey optionKey)
{
Debug.Assert(ShouldSerialize(optionKey));
writer.WriteString(optionKey.Option.Name);
writer.WriteString(optionKey.Option.Feature);
writer.WriteBoolean(optionKey.Option.IsPerLanguage);
if (optionKey.Option.IsPerLanguage)
{
writer.WriteString(optionKey.Language);
}
}
}
public static SerializableOptionSet Deserialize(ObjectReader reader, IOptionService optionService, CancellationToken cancellationToken)
{
// We deserialize the following contents from this option set:
// 1. Languages
// 2. Prefetched serializable option key-value pairs
// 3. Changed option keys.
// NOTE: keep the deserialization in sync with Serialize method above.
cancellationToken.ThrowIfCancellationRequested();
var count = reader.ReadInt32();
var languagesBuilder = ImmutableHashSet.CreateBuilder<string>();
for (var i = 0; i < count; i++)
{
var language = reader.ReadString();
Debug.Assert(RemoteSupportedLanguages.IsSupported(language));
languagesBuilder.Add(language);
}
var languages = languagesBuilder.ToImmutable();
var serializableOptions = optionService.GetRegisteredSerializableOptions(languages);
var lookup = serializableOptions.ToLookup(o => o.Name);
count = reader.ReadInt32();
var builder = ImmutableDictionary.CreateBuilder<OptionKey, object?>();
for (var i = 0; i < count; i++)
{
var optionKeyOpt = TryDeserializeOptionKey(reader, lookup);
var kind = (OptionValueKind)reader.ReadInt32();
var readValue = kind switch
{
OptionValueKind.Enum => reader.ReadInt32(),
OptionValueKind.CodeStyleOption => CodeStyleOption2<object>.ReadFrom(reader),
OptionValueKind.NamingStylePreferences => NamingStylePreferences.ReadFrom(reader),
_ => reader.ReadValue(),
};
if (optionKeyOpt == null)
continue;
var optionKey = optionKeyOpt.Value;
if (!serializableOptions.Contains(optionKey.Option))
continue;
object? optionValue;
switch (kind)
{
case OptionValueKind.CodeStyleOption:
if (optionKey.Option.DefaultValue is not ICodeStyleOption defaultValue ||
optionKey.Option.Type.GenericTypeArguments.Length != 1)
{
continue;
}
var parsedCodeStyleOption = (CodeStyleOption2<object>)readValue;
var value = parsedCodeStyleOption.Value;
var type = optionKey.Option.Type.GenericTypeArguments[0];
var convertedValue = type.IsEnum ? Enum.ToObject(type, value) : Convert.ChangeType(value, type);
optionValue = defaultValue.WithValue(convertedValue).WithNotification(parsedCodeStyleOption.Notification);
break;
case OptionValueKind.NamingStylePreferences:
optionValue = (NamingStylePreferences)readValue;
break;
case OptionValueKind.Enum:
optionValue = Enum.ToObject(optionKey.Option.Type, readValue);
break;
default:
optionValue = readValue;
break;
}
builder[optionKey] = optionValue;
}
count = reader.ReadInt32();
var changedKeysBuilder = ImmutableHashSet.CreateBuilder<OptionKey>();
for (var i = 0; i < count; i++)
{
if (TryDeserializeOptionKey(reader, lookup) is { } optionKey)
changedKeysBuilder.Add(optionKey);
}
var serializableOptionValues = builder.ToImmutable();
var changedOptionKeysSerializable = changedKeysBuilder.ToImmutable();
var workspaceOptionSet = new WorkspaceOptionSet(optionService);
return new SerializableOptionSet(
languages, workspaceOptionSet, serializableOptions, serializableOptionValues,
changedOptionKeysSerializable, changedOptionKeysNonSerializable: ImmutableHashSet<OptionKey>.Empty);
static OptionKey? TryDeserializeOptionKey(ObjectReader reader, ILookup<string, IOption> lookup)
{
var name = reader.ReadString();
var feature = reader.ReadString();
var isPerLanguage = reader.ReadBoolean();
var language = isPerLanguage ? reader.ReadString() : null;
foreach (var option in lookup[name])
{
if (option.Feature == feature &&
option.IsPerLanguage == isPerLanguage)
{
return new OptionKey(option, language);
}
}
Debug.Fail($"Failed to deserialize: {name}-{feature}-{isPerLanguage}-{language}");
return null;
}
}
private enum OptionValueKind
{
CodeStyleOption,
NamingStylePreferences,
Object,
Enum
}
private sealed class OptionKeyComparer : IComparer<OptionKey>
{
public static readonly OptionKeyComparer Instance = new();
private OptionKeyComparer() { }
public int Compare(OptionKey x, OptionKey y)
{
if (x.Option.Name != y.Option.Name)
{
return StringComparer.Ordinal.Compare(x.Option.Name, y.Option.Name);
}
if (x.Option.Feature != y.Option.Feature)
{
return StringComparer.Ordinal.Compare(x.Option.Feature, y.Option.Feature);
}
if (x.Language != y.Language)
{
return StringComparer.Ordinal.Compare(x.Language, y.Language);
}
return Comparer.Default.Compare(x.GetHashCode(), y.GetHashCode());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Options
{
/// <summary>
/// Serializable implementation of <see cref="OptionSet"/> for <see cref="Solution.Options"/>.
/// It contains prepopulated fetched option values for all serializable options and values, and delegates to <see cref="WorkspaceOptionSet"/> for non-serializable values.
/// It ensures a contract that values are immutable from this instance once observed.
/// </summary>
internal sealed partial class SerializableOptionSet : OptionSet
{
/// <summary>
/// Languages for which all the applicable serializable options have been prefetched and saved in <see cref="_serializableOptionValues"/>.
/// </summary>
private readonly ImmutableHashSet<string> _languages;
/// <summary>
/// Fallback option set for non-serializable options. See comments on <see cref="WorkspaceOptionSet"/> for more details.
/// </summary>
private readonly WorkspaceOptionSet _workspaceOptionSet;
/// <summary>
/// All serializable options for <see cref="_languages"/>.
/// </summary>
private readonly ImmutableHashSet<IOption> _serializableOptions;
/// <summary>
/// Prefetched option values for all <see cref="_serializableOptions"/> applicable for <see cref="_languages"/>.
/// </summary>
private readonly ImmutableDictionary<OptionKey, object?> _serializableOptionValues;
/// <summary>
/// Set of changed options in this option set which are serializable.
/// </summary>
private readonly ImmutableHashSet<OptionKey> _changedOptionKeysSerializable;
/// <summary>
/// Set of changed options in this option set which are non-serializable.
/// </summary>
private readonly ImmutableHashSet<OptionKey> _changedOptionKeysNonSerializable;
private SerializableOptionSet(
ImmutableHashSet<string> languages,
WorkspaceOptionSet workspaceOptionSet,
ImmutableHashSet<IOption> serializableOptions,
ImmutableDictionary<OptionKey, object?> values,
ImmutableHashSet<OptionKey> changedOptionKeysSerializable,
ImmutableHashSet<OptionKey> changedOptionKeysNonSerializable)
{
Debug.Assert(languages.All(RemoteSupportedLanguages.IsSupported));
_languages = languages;
_workspaceOptionSet = workspaceOptionSet;
_serializableOptions = serializableOptions;
_serializableOptionValues = values;
_changedOptionKeysSerializable = changedOptionKeysSerializable;
_changedOptionKeysNonSerializable = changedOptionKeysNonSerializable;
Debug.Assert(values.Keys.All(ShouldSerialize));
Debug.Assert(changedOptionKeysSerializable.All(optionKey => ShouldSerialize(optionKey)));
Debug.Assert(changedOptionKeysNonSerializable.All(optionKey => !ShouldSerialize(optionKey)));
}
internal SerializableOptionSet(
ImmutableHashSet<string> languages,
IOptionService optionService,
ImmutableHashSet<IOption> serializableOptions,
ImmutableDictionary<OptionKey, object?> values,
ImmutableHashSet<OptionKey> changedOptionKeysSerializable)
: this(languages, new WorkspaceOptionSet(optionService), serializableOptions, values, changedOptionKeysSerializable, changedOptionKeysNonSerializable: ImmutableHashSet<OptionKey>.Empty)
{
}
/// <summary>
/// Returns an option set with all the serializable option values prefetched for given <paramref name="languages"/>,
/// while also retaining all the explicitly changed option values in this option set for any language.
/// NOTE: All the provided <paramref name="languages"/> must be <see cref="RemoteSupportedLanguages.IsSupported(string)"/>.
/// </summary>
public SerializableOptionSet WithLanguages(ImmutableHashSet<string> languages)
{
Debug.Assert(languages.All(RemoteSupportedLanguages.IsSupported));
if (_languages.SetEquals(languages))
{
return this;
}
// First create a base option set for the given languages.
var newOptionSet = _workspaceOptionSet.OptionService.GetSerializableOptionsSnapshot(languages);
// Then apply all the changed options from the current option set to the new option set.
foreach (var changedOption in this.GetChangedOptions())
{
var valueInNewOptionSet = newOptionSet.GetOption(changedOption);
var changedValueInThisOptionSet = this.GetOption(changedOption);
if (!Equals(changedValueInThisOptionSet, valueInNewOptionSet))
{
newOptionSet = (SerializableOptionSet)newOptionSet.WithChangedOption(changedOption, changedValueInThisOptionSet);
}
}
return newOptionSet;
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)]
private protected override object? GetOptionCore(OptionKey optionKey)
{
if (_serializableOptionValues.TryGetValue(optionKey, out var value))
{
return value;
}
return _workspaceOptionSet.GetOption(optionKey);
}
private bool ShouldSerialize(OptionKey optionKey)
=> _serializableOptions.Contains(optionKey.Option) &&
(!optionKey.Option.IsPerLanguage || _languages.Contains(optionKey.Language!));
public override OptionSet WithChangedOption(OptionKey optionKey, object? value)
{
// Make sure we first load this in current optionset
var currentValue = this.GetOption(optionKey);
// Check if the new value is the same as the current value.
if (Equals(value, currentValue))
{
// Return a cloned option set as the public API 'WithChangedOption' guarantees a new option set is returned.
return new SerializableOptionSet(_languages, _workspaceOptionSet, _serializableOptions,
_serializableOptionValues, _changedOptionKeysSerializable, _changedOptionKeysNonSerializable);
}
WorkspaceOptionSet workspaceOptionSet;
ImmutableDictionary<OptionKey, object?> serializableOptionValues;
ImmutableHashSet<OptionKey> changedOptionKeysSerializable;
ImmutableHashSet<OptionKey> changedOptionKeysNonSerializable;
if (ShouldSerialize(optionKey))
{
workspaceOptionSet = _workspaceOptionSet;
serializableOptionValues = _serializableOptionValues.SetItem(optionKey, value);
changedOptionKeysSerializable = _changedOptionKeysSerializable.Add(optionKey);
changedOptionKeysNonSerializable = _changedOptionKeysNonSerializable;
}
else
{
workspaceOptionSet = (WorkspaceOptionSet)_workspaceOptionSet.WithChangedOption(optionKey, value);
serializableOptionValues = _serializableOptionValues;
changedOptionKeysSerializable = _changedOptionKeysSerializable;
changedOptionKeysNonSerializable = _changedOptionKeysNonSerializable.Add(optionKey);
}
return new SerializableOptionSet(_languages, workspaceOptionSet, _serializableOptions,
serializableOptionValues, changedOptionKeysSerializable, changedOptionKeysNonSerializable);
}
/// <summary>
/// Gets a list of all the options that were changed.
/// </summary>
internal IEnumerable<OptionKey> GetChangedOptions()
=> _changedOptionKeysSerializable.Concat(_changedOptionKeysNonSerializable);
internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet? optionSet)
{
if (optionSet == this)
{
yield break;
}
foreach (var key in GetChangedOptions())
{
var currentValue = optionSet?.GetOption(key);
var changedValue = this.GetOption(key);
if (!object.Equals(currentValue, changedValue))
{
yield return key;
}
}
}
public void Serialize(ObjectWriter writer, CancellationToken cancellationToken)
{
// We serialize the following contents from this option set:
// 1. Languages
// 2. Prefetched serializable option key-value pairs
// 3. Changed option keys.
// NOTE: keep the serialization in sync with Deserialize method below.
cancellationToken.ThrowIfCancellationRequested();
writer.WriteInt32(_languages.Count);
foreach (var language in _languages.Order())
{
Debug.Assert(RemoteSupportedLanguages.IsSupported(language));
writer.WriteString(language);
}
var valuesBuilder = new SortedDictionary<OptionKey, (OptionValueKind, object?)>(OptionKeyComparer.Instance);
foreach (var (optionKey, value) in _serializableOptionValues)
{
Debug.Assert(ShouldSerialize(optionKey));
if (!_serializableOptions.Contains(optionKey.Option))
continue;
OptionValueKind kind;
switch (value)
{
case ICodeStyleOption:
if (optionKey.Option.Type.GenericTypeArguments.Length != 1)
continue;
kind = OptionValueKind.CodeStyleOption;
break;
case NamingStylePreferences:
kind = OptionValueKind.NamingStylePreferences;
break;
default:
kind = value != null && value.GetType().IsEnum ? OptionValueKind.Enum : OptionValueKind.Object;
break;
}
valuesBuilder.Add(optionKey, (kind, value));
}
writer.WriteInt32(valuesBuilder.Count);
foreach (var (optionKey, (kind, value)) in valuesBuilder)
{
SerializeOptionKey(optionKey);
writer.WriteInt32((int)kind);
if (kind == OptionValueKind.Enum)
{
RoslynDebug.Assert(value != null);
writer.WriteInt32((int)value);
}
else if (kind is OptionValueKind.CodeStyleOption or OptionValueKind.NamingStylePreferences)
{
RoslynDebug.Assert(value != null);
((IObjectWritable)value).WriteTo(writer);
}
else
{
writer.WriteValue(value);
}
}
writer.WriteInt32(_changedOptionKeysSerializable.Count);
foreach (var changedKey in _changedOptionKeysSerializable.OrderBy(OptionKeyComparer.Instance))
SerializeOptionKey(changedKey);
return;
void SerializeOptionKey(OptionKey optionKey)
{
Debug.Assert(ShouldSerialize(optionKey));
writer.WriteString(optionKey.Option.Name);
writer.WriteString(optionKey.Option.Feature);
writer.WriteBoolean(optionKey.Option.IsPerLanguage);
if (optionKey.Option.IsPerLanguage)
{
writer.WriteString(optionKey.Language);
}
}
}
public static SerializableOptionSet Deserialize(ObjectReader reader, IOptionService optionService, CancellationToken cancellationToken)
{
// We deserialize the following contents from this option set:
// 1. Languages
// 2. Prefetched serializable option key-value pairs
// 3. Changed option keys.
// NOTE: keep the deserialization in sync with Serialize method above.
cancellationToken.ThrowIfCancellationRequested();
var count = reader.ReadInt32();
var languagesBuilder = ImmutableHashSet.CreateBuilder<string>();
for (var i = 0; i < count; i++)
{
var language = reader.ReadString();
Debug.Assert(RemoteSupportedLanguages.IsSupported(language));
languagesBuilder.Add(language);
}
var languages = languagesBuilder.ToImmutable();
var serializableOptions = optionService.GetRegisteredSerializableOptions(languages);
var lookup = serializableOptions.ToLookup(o => o.Name);
count = reader.ReadInt32();
var builder = ImmutableDictionary.CreateBuilder<OptionKey, object?>();
for (var i = 0; i < count; i++)
{
var optionKeyOpt = TryDeserializeOptionKey(reader, lookup);
var kind = (OptionValueKind)reader.ReadInt32();
var readValue = kind switch
{
OptionValueKind.Enum => reader.ReadInt32(),
OptionValueKind.CodeStyleOption => CodeStyleOption2<object>.ReadFrom(reader),
OptionValueKind.NamingStylePreferences => NamingStylePreferences.ReadFrom(reader),
_ => reader.ReadValue(),
};
if (optionKeyOpt == null)
continue;
var optionKey = optionKeyOpt.Value;
if (!serializableOptions.Contains(optionKey.Option))
continue;
object? optionValue;
switch (kind)
{
case OptionValueKind.CodeStyleOption:
if (optionKey.Option.DefaultValue is not ICodeStyleOption defaultValue ||
optionKey.Option.Type.GenericTypeArguments.Length != 1)
{
continue;
}
var parsedCodeStyleOption = (CodeStyleOption2<object>)readValue;
var value = parsedCodeStyleOption.Value;
var type = optionKey.Option.Type.GenericTypeArguments[0];
var convertedValue = type.IsEnum ? Enum.ToObject(type, value) : Convert.ChangeType(value, type);
optionValue = defaultValue.WithValue(convertedValue).WithNotification(parsedCodeStyleOption.Notification);
break;
case OptionValueKind.NamingStylePreferences:
optionValue = (NamingStylePreferences)readValue;
break;
case OptionValueKind.Enum:
optionValue = Enum.ToObject(optionKey.Option.Type, readValue);
break;
default:
optionValue = readValue;
break;
}
builder[optionKey] = optionValue;
}
count = reader.ReadInt32();
var changedKeysBuilder = ImmutableHashSet.CreateBuilder<OptionKey>();
for (var i = 0; i < count; i++)
{
if (TryDeserializeOptionKey(reader, lookup) is { } optionKey)
changedKeysBuilder.Add(optionKey);
}
var serializableOptionValues = builder.ToImmutable();
var changedOptionKeysSerializable = changedKeysBuilder.ToImmutable();
var workspaceOptionSet = new WorkspaceOptionSet(optionService);
return new SerializableOptionSet(
languages, workspaceOptionSet, serializableOptions, serializableOptionValues,
changedOptionKeysSerializable, changedOptionKeysNonSerializable: ImmutableHashSet<OptionKey>.Empty);
static OptionKey? TryDeserializeOptionKey(ObjectReader reader, ILookup<string, IOption> lookup)
{
var name = reader.ReadString();
var feature = reader.ReadString();
var isPerLanguage = reader.ReadBoolean();
var language = isPerLanguage ? reader.ReadString() : null;
foreach (var option in lookup[name])
{
if (option.Feature == feature &&
option.IsPerLanguage == isPerLanguage)
{
return new OptionKey(option, language);
}
}
Debug.Fail($"Failed to deserialize: {name}-{feature}-{isPerLanguage}-{language}");
return null;
}
}
private enum OptionValueKind
{
CodeStyleOption,
NamingStylePreferences,
Object,
Enum
}
private sealed class OptionKeyComparer : IComparer<OptionKey>
{
public static readonly OptionKeyComparer Instance = new();
private OptionKeyComparer() { }
public int Compare(OptionKey x, OptionKey y)
{
if (x.Option.Name != y.Option.Name)
{
return StringComparer.Ordinal.Compare(x.Option.Name, y.Option.Name);
}
if (x.Option.Feature != y.Option.Feature)
{
return StringComparer.Ordinal.Compare(x.Option.Feature, y.Option.Feature);
}
if (x.Language != y.Language)
{
return StringComparer.Ordinal.Compare(x.Language, y.Language);
}
return Comparer.Default.Compare(x.GetHashCode(), y.GetHashCode());
}
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpUpdateProjectToAllowUnsafe.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;
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.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpUpdateProjectToAllowUnsafe : AbstractUpdateProjectTest
{
public CSharpUpdateProjectToAllowUnsafe(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
private void InvokeFix()
{
VisualStudio.Editor.SetText(@"
unsafe class C
{
}");
VisualStudio.Editor.Activate();
VisualStudio.Editor.PlaceCaret("C");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Allow unsafe code in this project", applyFix: true);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/44301"), Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void CPSProject_GeneralPropertyGroupUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.CSharpNetStandardClassLibrary, LanguageNames.CSharp);
VisualStudio.SolutionExplorer.RestoreNuGetPackages(project);
InvokeFix();
VerifyPropertyOutsideConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void LegacyProject_AllConfigurationsUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.ClassLibrary, LanguageNames.CSharp);
InvokeFix();
VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
[WorkItem(23342, "https://github.com/dotnet/roslyn/issues/23342")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void LegacyProject_MultiplePlatforms_AllConfigurationsUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddCustomProject(project, ".csproj", $@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" />
<PropertyGroup>
<Configuration Condition=""'$(Configuration)' == ''"">Debug</Configuration>
<Platform Condition=""'$(Platform)' == ''"">x64</Platform>
<ProjectGuid>{{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>{ProjectName}</RootNamespace>
<AssemblyName>{ProjectName}</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'"">
<OutputPath>bin\x86\Debug\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'"">
<OutputPath>bin\x86\Release\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x64'"">
<OutputPath>bin\x64\Debug\</OutputPath>
<PlatformTarget>x64</PlatformTarget>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'"">
<OutputPath>bin\x64\Release\</OutputPath>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
</ItemGroup>
<Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
</Project>");
VisualStudio.SolutionExplorer.AddFile(project, "C.cs", open: true);
InvokeFix();
VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using 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.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpUpdateProjectToAllowUnsafe : AbstractUpdateProjectTest
{
public CSharpUpdateProjectToAllowUnsafe(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
private void InvokeFix()
{
VisualStudio.Editor.SetText(@"
unsafe class C
{
}");
VisualStudio.Editor.Activate();
VisualStudio.Editor.PlaceCaret("C");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Allow unsafe code in this project", applyFix: true);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/44301"), Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void CPSProject_GeneralPropertyGroupUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.CSharpNetStandardClassLibrary, LanguageNames.CSharp);
VisualStudio.SolutionExplorer.RestoreNuGetPackages(project);
InvokeFix();
VerifyPropertyOutsideConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void LegacyProject_AllConfigurationsUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.ClassLibrary, LanguageNames.CSharp);
InvokeFix();
VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
[WorkItem(23342, "https://github.com/dotnet/roslyn/issues/23342")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void LegacyProject_MultiplePlatforms_AllConfigurationsUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddCustomProject(project, ".csproj", $@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" />
<PropertyGroup>
<Configuration Condition=""'$(Configuration)' == ''"">Debug</Configuration>
<Platform Condition=""'$(Platform)' == ''"">x64</Platform>
<ProjectGuid>{{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>{ProjectName}</RootNamespace>
<AssemblyName>{ProjectName}</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'"">
<OutputPath>bin\x86\Debug\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'"">
<OutputPath>bin\x86\Release\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x64'"">
<OutputPath>bin\x64\Debug\</OutputPath>
<PlatformTarget>x64</PlatformTarget>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'"">
<OutputPath>bin\x64\Release\</OutputPath>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
</ItemGroup>
<Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
</Project>");
VisualStudio.SolutionExplorer.AddFile(project, "C.cs", open: true);
InvokeFix();
VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/CSharp/Portable/Parser/AbstractLexer.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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
// separate out text windowing implementation (keeps scanning & lexing functions from abusing details)
internal class AbstractLexer : IDisposable
{
internal readonly SlidingTextWindow TextWindow;
private List<SyntaxDiagnosticInfo> _errors;
protected AbstractLexer(SourceText text)
{
this.TextWindow = new SlidingTextWindow(text);
}
public virtual void Dispose()
{
this.TextWindow.Dispose();
}
protected void Start()
{
TextWindow.Start();
_errors = null;
}
protected bool HasErrors
{
get { return _errors != null; }
}
protected SyntaxDiagnosticInfo[] GetErrors(int leadingTriviaWidth)
{
if (_errors != null)
{
if (leadingTriviaWidth > 0)
{
var array = new SyntaxDiagnosticInfo[_errors.Count];
for (int i = 0; i < _errors.Count; i++)
{
// fixup error positioning to account for leading trivia
array[i] = _errors[i].WithOffset(_errors[i].Offset + leadingTriviaWidth);
}
return array;
}
else
{
return _errors.ToArray();
}
}
else
{
return null;
}
}
protected void AddError(int position, int width, ErrorCode code)
{
this.AddError(this.MakeError(position, width, code));
}
protected void AddError(int position, int width, ErrorCode code, params object[] args)
{
this.AddError(this.MakeError(position, width, code, args));
}
protected void AddError(int position, int width, XmlParseErrorCode code, params object[] args)
{
this.AddError(this.MakeError(position, width, code, args));
}
protected void AddError(ErrorCode code)
{
this.AddError(MakeError(code));
}
protected void AddError(ErrorCode code, params object[] args)
{
this.AddError(MakeError(code, args));
}
protected void AddError(XmlParseErrorCode code)
{
this.AddError(MakeError(code));
}
protected void AddError(XmlParseErrorCode code, params object[] args)
{
this.AddError(MakeError(code, args));
}
protected void AddError(SyntaxDiagnosticInfo error)
{
if (error != null)
{
if (_errors == null)
{
_errors = new List<SyntaxDiagnosticInfo>(8);
}
_errors.Add(error);
}
}
protected SyntaxDiagnosticInfo MakeError(int position, int width, ErrorCode code)
{
int offset = GetLexemeOffsetFromPosition(position);
return new SyntaxDiagnosticInfo(offset, width, code);
}
protected SyntaxDiagnosticInfo MakeError(int position, int width, ErrorCode code, params object[] args)
{
int offset = GetLexemeOffsetFromPosition(position);
return new SyntaxDiagnosticInfo(offset, width, code, args);
}
protected XmlSyntaxDiagnosticInfo MakeError(int position, int width, XmlParseErrorCode code, params object[] args)
{
int offset = GetLexemeOffsetFromPosition(position);
return new XmlSyntaxDiagnosticInfo(offset, width, code, args);
}
private int GetLexemeOffsetFromPosition(int position)
{
return position >= TextWindow.LexemeStartPosition ? position - TextWindow.LexemeStartPosition : position;
}
protected static SyntaxDiagnosticInfo MakeError(ErrorCode code)
{
return new SyntaxDiagnosticInfo(code);
}
protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args)
{
return new SyntaxDiagnosticInfo(code, args);
}
protected static XmlSyntaxDiagnosticInfo MakeError(XmlParseErrorCode code)
{
return new XmlSyntaxDiagnosticInfo(0, 0, code);
}
protected static XmlSyntaxDiagnosticInfo MakeError(XmlParseErrorCode code, params object[] args)
{
return new XmlSyntaxDiagnosticInfo(0, 0, code, args);
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
// separate out text windowing implementation (keeps scanning & lexing functions from abusing details)
internal class AbstractLexer : IDisposable
{
internal readonly SlidingTextWindow TextWindow;
private List<SyntaxDiagnosticInfo> _errors;
protected AbstractLexer(SourceText text)
{
this.TextWindow = new SlidingTextWindow(text);
}
public virtual void Dispose()
{
this.TextWindow.Dispose();
}
protected void Start()
{
TextWindow.Start();
_errors = null;
}
protected bool HasErrors
{
get { return _errors != null; }
}
protected SyntaxDiagnosticInfo[] GetErrors(int leadingTriviaWidth)
{
if (_errors != null)
{
if (leadingTriviaWidth > 0)
{
var array = new SyntaxDiagnosticInfo[_errors.Count];
for (int i = 0; i < _errors.Count; i++)
{
// fixup error positioning to account for leading trivia
array[i] = _errors[i].WithOffset(_errors[i].Offset + leadingTriviaWidth);
}
return array;
}
else
{
return _errors.ToArray();
}
}
else
{
return null;
}
}
protected void AddError(int position, int width, ErrorCode code)
{
this.AddError(this.MakeError(position, width, code));
}
protected void AddError(int position, int width, ErrorCode code, params object[] args)
{
this.AddError(this.MakeError(position, width, code, args));
}
protected void AddError(int position, int width, XmlParseErrorCode code, params object[] args)
{
this.AddError(this.MakeError(position, width, code, args));
}
protected void AddError(ErrorCode code)
{
this.AddError(MakeError(code));
}
protected void AddError(ErrorCode code, params object[] args)
{
this.AddError(MakeError(code, args));
}
protected void AddError(XmlParseErrorCode code)
{
this.AddError(MakeError(code));
}
protected void AddError(XmlParseErrorCode code, params object[] args)
{
this.AddError(MakeError(code, args));
}
protected void AddError(SyntaxDiagnosticInfo error)
{
if (error != null)
{
if (_errors == null)
{
_errors = new List<SyntaxDiagnosticInfo>(8);
}
_errors.Add(error);
}
}
protected SyntaxDiagnosticInfo MakeError(int position, int width, ErrorCode code)
{
int offset = GetLexemeOffsetFromPosition(position);
return new SyntaxDiagnosticInfo(offset, width, code);
}
protected SyntaxDiagnosticInfo MakeError(int position, int width, ErrorCode code, params object[] args)
{
int offset = GetLexemeOffsetFromPosition(position);
return new SyntaxDiagnosticInfo(offset, width, code, args);
}
protected XmlSyntaxDiagnosticInfo MakeError(int position, int width, XmlParseErrorCode code, params object[] args)
{
int offset = GetLexemeOffsetFromPosition(position);
return new XmlSyntaxDiagnosticInfo(offset, width, code, args);
}
private int GetLexemeOffsetFromPosition(int position)
{
return position >= TextWindow.LexemeStartPosition ? position - TextWindow.LexemeStartPosition : position;
}
protected static SyntaxDiagnosticInfo MakeError(ErrorCode code)
{
return new SyntaxDiagnosticInfo(code);
}
protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args)
{
return new SyntaxDiagnosticInfo(code, args);
}
protected static XmlSyntaxDiagnosticInfo MakeError(XmlParseErrorCode code)
{
return new XmlSyntaxDiagnosticInfo(0, 0, code);
}
protected static XmlSyntaxDiagnosticInfo MakeError(XmlParseErrorCode code, params object[] args)
{
return new XmlSyntaxDiagnosticInfo(0, 0, code, args);
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Tools/ExternalAccess/FSharp/Classification/IFSharpClassificationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Classification
{
internal interface IFSharpClassificationService
{
/// <summary>
/// Produce the classifications for the span of text specified. Classification should be
/// performed as quickly as possible, and should process the text in a lexical fashion.
/// This allows classification results to be shown to the user when a file is opened before
/// any additional compiler information is available for the text.
///
/// Important: The classification should not consider the context the text exists in, and how
/// that may affect the final classifications. This may result in incorrect classification
/// (i.e. identifiers being classified as keywords). These incorrect results will be patched
/// up when the lexical results are superseded by the calls to AddSyntacticClassifications.
/// </summary>
void AddLexicalClassifications(SourceText text, TextSpan textSpan, List<ClassifiedSpan> result, CancellationToken cancellationToken);
/// <summary>
/// Produce the classifications for the span of text specified. The syntax of the document
/// can be accessed to provide more correct classifications. For example, the syntax can
/// be used to determine if a piece of text that looks like a keyword should actually be
/// considered an identifier in its current context.
/// </summary>
Task AddSyntacticClassificationsAsync(Document document, TextSpan textSpan, List<ClassifiedSpan> result, CancellationToken cancellationToken);
/// <summary>
/// Produce the classifications for the span of text specified. Semantics of the language
/// can be used to provide richer information for constructs where syntax is insufficient.
/// For example, semantic information can be used to determine if an identifier should be
/// classified as a type, structure, or something else entirely.
/// </summary>
Task AddSemanticClassificationsAsync(Document document, TextSpan textSpan, List<ClassifiedSpan> result, CancellationToken cancellationToken);
/// <summary>
/// Adjust a classification from a previous version of text accordingly based on the current
/// text. For example, if a piece of text was classified as an identifier in a previous version,
/// but a character was added that would make it into a keyword, then indicate that here.
///
/// This allows the classified to quickly fix up old classifications as the user types. These
/// adjustments are allowed to be incorrect as they will be superseded by calls to get the
/// syntactic and semantic classifications for this version later.
/// </summary>
ClassifiedSpan AdjustStaleClassification(SourceText text, ClassifiedSpan classifiedSpan);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Classification
{
internal interface IFSharpClassificationService
{
/// <summary>
/// Produce the classifications for the span of text specified. Classification should be
/// performed as quickly as possible, and should process the text in a lexical fashion.
/// This allows classification results to be shown to the user when a file is opened before
/// any additional compiler information is available for the text.
///
/// Important: The classification should not consider the context the text exists in, and how
/// that may affect the final classifications. This may result in incorrect classification
/// (i.e. identifiers being classified as keywords). These incorrect results will be patched
/// up when the lexical results are superseded by the calls to AddSyntacticClassifications.
/// </summary>
void AddLexicalClassifications(SourceText text, TextSpan textSpan, List<ClassifiedSpan> result, CancellationToken cancellationToken);
/// <summary>
/// Produce the classifications for the span of text specified. The syntax of the document
/// can be accessed to provide more correct classifications. For example, the syntax can
/// be used to determine if a piece of text that looks like a keyword should actually be
/// considered an identifier in its current context.
/// </summary>
Task AddSyntacticClassificationsAsync(Document document, TextSpan textSpan, List<ClassifiedSpan> result, CancellationToken cancellationToken);
/// <summary>
/// Produce the classifications for the span of text specified. Semantics of the language
/// can be used to provide richer information for constructs where syntax is insufficient.
/// For example, semantic information can be used to determine if an identifier should be
/// classified as a type, structure, or something else entirely.
/// </summary>
Task AddSemanticClassificationsAsync(Document document, TextSpan textSpan, List<ClassifiedSpan> result, CancellationToken cancellationToken);
/// <summary>
/// Adjust a classification from a previous version of text accordingly based on the current
/// text. For example, if a piece of text was classified as an identifier in a previous version,
/// but a character was added that would make it into a keyword, then indicate that here.
///
/// This allows the classified to quickly fix up old classifications as the user types. These
/// adjustments are allowed to be incorrect as they will be superseded by calls to get the
/// syntactic and semantic classifications for this version later.
/// </summary>
ClassifiedSpan AdjustStaleClassification(SourceText text, ClassifiedSpan classifiedSpan);
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/CSharp/Test/Semantic/Semantics/ConditionalOperatorTests.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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// Test binding of the conditional (aka ternary) operator.
/// </summary>
public class ConditionalOperatorTests : CSharpTestBase
{
/// <summary>
/// Both branches have the same type, so no conversion is necessary.
/// </summary>
[Fact]
public void TestSameType()
{
TestConditional("true ? 1 : 2", expectedType: "System.Int32");
TestConditional("false ? 'a' : 'b'", expectedType: "System.Char");
TestConditional("true ? 1.5 : GetDouble()", expectedType: "System.Double");
TestConditional("false ? GetObject() : GetObject()", expectedType: "System.Object");
TestConditional("true ? GetUserGeneric<T>() : GetUserGeneric<T>()", expectedType: "D<T>");
TestConditional("false ? GetTypeParameter<T>() : GetTypeParameter<T>()", expectedType: "T");
}
/// <summary>
/// Both branches have types and exactly one expression is convertible to the type of the other.
/// </summary>
[Fact]
public void TestOneConversion()
{
TestConditional("true ? GetShort() : GetInt()", expectedType: "System.Int32");
TestConditional("false ? \"string\" : GetObject()", expectedType: "System.Object");
TestConditional("true ? GetVariantInterface<string, int>() : GetVariantInterface<object, int>()", expectedType: "I<System.String, System.Int32>");
TestConditional("false ? GetVariantInterface<int, object>() : GetVariantInterface<int, string>()", expectedType: "I<System.Int32, System.Object>");
}
/// <summary>
/// Both branches have types and both expression are convertible to the type of the other.
/// The wider type is preferred.
/// </summary>
/// <remarks>
/// Cases where both conversions are possible and neither is preferred as the
/// wider of the two are possible only in the presence of user-defined implicit
/// conversions. Such cases are tested separately.
/// See SemanticErrorTests.CS0172ERR_AmbigQM.
/// </remarks>
[Fact]
public void TestAmbiguousPreferWider()
{
TestConditional("true ? 1 : (short)2", expectedType: "System.Int32");
TestConditional("false ? (float)2 : 1", expectedType: "System.Single");
TestConditional("true ? 1.5d : (double)2", expectedType: "System.Double");
}
/// <summary>
/// Both branches have types but neither expression is convertible to the type
/// of the other.
/// </summary>
[Fact]
public void TestNoConversion()
{
TestConditional("true ? T : U", null, parseOptions: TestOptions.Regular8,
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type"),
Diagnostic(ErrorCode.ERR_BadSKunknown, "U").WithArguments("U", "type"));
TestConditional("true ? T : U", null, parseOptions: TestOptions.Regular8.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()),
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type"),
Diagnostic(ErrorCode.ERR_BadSKunknown, "U").WithArguments("U", "type"));
TestConditional("false ? T : 1", null, parseOptions: TestOptions.Regular8,
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type"));
TestConditional("false ? T : 1", null, parseOptions: TestOptions.Regular8.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()),
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type"));
TestConditional("true ? GetUserGeneric<char>() : GetUserNonGeneric()", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? GetUserGeneric<char>() : GetUserNonGeneric()").WithArguments("D<char>", "C"));
}
/// <summary>
/// Exactly one branch has a type and the other expression is convertible to that type.
/// </summary>
[Fact]
public void TestOneUntypedSuccess()
{
TestConditional("true ? GetObject() : null", expectedType: "System.Object"); //null literal
TestConditional("false ? GetString : (System.Func<string>)null", expectedType: "System.Func<System.String>"); //method group
TestConditional("true ? (System.Func<int, int>)null : x => x", expectedType: "System.Func<System.Int32, System.Int32>"); //lambda
}
/// <summary>
/// Exactly one branch has a type but the other expression is not convertible to that type.
/// </summary>
[Fact]
public void TestOneUntypedFailure()
{
TestConditional("true ? GetInt() : null", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? GetInt() : null").WithArguments("int", "<null>"));
TestConditional("false ? GetString : (System.Func<int>)null", null, TestOptions.WithoutImprovedOverloadCandidates,
Diagnostic(ErrorCode.ERR_BadRetType, "GetString").WithArguments("C.GetString()", "string"));
TestConditional("false ? GetString : (System.Func<int>)null", null,
// (6,13): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'Func<int>'
// _ = false ? GetString : (System.Func<int>)null;
Diagnostic(ErrorCode.ERR_InvalidQM, "false ? GetString : (System.Func<int>)null").WithArguments("method group", "System.Func<int>"));
TestConditional("true ? (System.Func<int, short>)null : x => x", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? (System.Func<int, short>)null : x => x").WithArguments("System.Func<int, short>", "lambda expression"));
}
[Fact]
public void TestBothUntyped()
{
TestConditional("true ? null : null", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? null : null").WithArguments("<null>", "<null>"));
TestConditional("false ? null : GetInt", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "false ? null : GetInt").WithArguments("<null>", "method group"));
TestConditional("true ? null : x => x", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? null : x => x").WithArguments("<null>", "lambda expression"));
TestConditional("false ? GetInt : GetInt", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "false ? GetInt : GetInt").WithArguments("method group", "method group"));
TestConditional("true ? GetInt : x => x", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? GetInt : x => x").WithArguments("method group", "lambda expression"));
TestConditional("false ? x => x : x => x", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "false ? x => x : x => x").WithArguments("lambda expression", "lambda expression"));
}
[Fact]
public void TestFunCall()
{
TestConditional("true ? GetVoid() : GetInt()", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? GetVoid() : GetInt()").WithArguments("void", "int"));
TestConditional("GetVoid() ? 1 : 2", null,
Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetVoid()").WithArguments("void", "bool"));
TestConditional("GetInt() ? 1 : 2", null,
Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetInt()").WithArguments("int", "bool"));
TestConditional("GetBool() ? 1 : 2", "System.Int32");
}
[Fact]
public void TestEmptyExpression()
{
TestConditional("true ? : GetInt()", null,
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"));
TestConditional("true ? GetInt() : ", null,
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"));
}
[Fact]
public void TestEnum()
{
TestConditional("true? 0 : color.Blue", "color");
TestConditional("true? 5 : color.Blue", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true? 5 : color.Blue").WithArguments("int", "color"));
TestConditional("true? null : color.Blue", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true? null : color.Blue").WithArguments("<null>", "color"));
}
[Fact]
public void TestAs()
{
TestConditional(@"(1 < 2) ? ""MyString"" as string : "" """, "System.String");
TestConditional(@"(1 > 2) ? "" "" : ""MyString"" as string", "System.String");
}
[Fact]
public void TestGeneric()
{
TestConditional(@"GetUserNonGeneric()? 1 : 2", null, Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetUserNonGeneric()").WithArguments("C", "bool"));
TestConditional(@"GetUserGeneric<T>()? 1 : 2", null, Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetUserGeneric<T>()").WithArguments("D<T>", "bool"));
TestConditional(@"GetTypeParameter<T>()? 1 : 2", null, Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetTypeParameter<T>()").WithArguments("T", "bool"));
TestConditional(@"GetVariantInterface<T, U>()? 1 : 2", null, Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetVariantInterface<T, U>()").WithArguments("I<T, U>", "bool"));
}
[Fact]
public void TestInvalidCondition()
{
// CONSIDER: dev10 reports ERR_ConstOutOfRange
TestConditional("1 ? 2 : 3", null,
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool"));
TestConditional("goo ? 'a' : 'b'", null,
Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo"));
TestConditional("new Goo() ? GetObject() : null", null,
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Goo").WithArguments("Goo"));
// CONSIDER: dev10 reports ERR_ConstOutOfRange
TestConditional("1 ? null : null", null, parseOptions: TestOptions.Regular8,
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool")
);
TestConditional("1 ? null : null", null, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()),
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool")
);
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestDelegateCovarianceConversions()
{
var source = @"
using System;
using System.Collections.Generic;
delegate void D<out T>();
class Base { }
class Derived : Base { }
class Program
{
static void Main()
{
bool testFlag = true;
D<Base> baseDelegate = () => Console.WriteLine(""B"");
D<Derived> derivedDelegate = () => Console.WriteLine(""D"");
D<Base> fcn;
fcn = testFlag ? baseDelegate : derivedDelegate;
fcn();
fcn = testFlag ? derivedDelegate : baseDelegate;
fcn();
fcn = baseDelegate ?? derivedDelegate;
fcn();
fcn = derivedDelegate ?? baseDelegate;
fcn();
IEnumerable<Base> baseSequence = null;
List<Derived> derivedList = null;
IEnumerable<Base> result = testFlag ? baseSequence : derivedList;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"B
D
B
D");
// Note no castclass instructions
// to be completely sure that stack states merge with expected types
// we use "stloc;ldloc" as a surrogate "static cast" for values
// in different branches
verifier.VerifyIL("Program.Main", @"
{
// Code size 133 (0x85)
.maxstack 3
.locals init (D<Base> V_0, //baseDelegate
D<Derived> V_1, //derivedDelegate
System.Collections.Generic.IEnumerable<Base> V_2, //baseSequence
System.Collections.Generic.List<Derived> V_3, //derivedList
D<Base> V_4)
IL_0000: ldc.i4.1
IL_0001: ldsfld ""D<Base> Program.<>c.<>9__0_0""
IL_0006: dup
IL_0007: brtrue.s IL_0020
IL_0009: pop
IL_000a: ldsfld ""Program.<>c Program.<>c.<>9""
IL_000f: ldftn ""void Program.<>c.<Main>b__0_0()""
IL_0015: newobj ""D<Base>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""D<Base> Program.<>c.<>9__0_0""
IL_0020: stloc.0
IL_0021: ldsfld ""D<Derived> Program.<>c.<>9__0_1""
IL_0026: dup
IL_0027: brtrue.s IL_0040
IL_0029: pop
IL_002a: ldsfld ""Program.<>c Program.<>c.<>9""
IL_002f: ldftn ""void Program.<>c.<Main>b__0_1()""
IL_0035: newobj ""D<Derived>..ctor(object, System.IntPtr)""
IL_003a: dup
IL_003b: stsfld ""D<Derived> Program.<>c.<>9__0_1""
IL_0040: stloc.1
IL_0041: dup
IL_0042: brtrue.s IL_004b
IL_0044: ldloc.1
IL_0045: stloc.s V_4
IL_0047: ldloc.s V_4
IL_0049: br.s IL_004c
IL_004b: ldloc.0
IL_004c: callvirt ""void D<Base>.Invoke()""
IL_0051: dup
IL_0052: brtrue.s IL_0057
IL_0054: ldloc.0
IL_0055: br.s IL_005c
IL_0057: ldloc.1
IL_0058: stloc.s V_4
IL_005a: ldloc.s V_4
IL_005c: callvirt ""void D<Base>.Invoke()""
IL_0061: ldloc.0
IL_0062: dup
IL_0063: brtrue.s IL_006b
IL_0065: pop
IL_0066: ldloc.1
IL_0067: stloc.s V_4
IL_0069: ldloc.s V_4
IL_006b: callvirt ""void D<Base>.Invoke()""
IL_0070: ldloc.1
IL_0071: stloc.s V_4
IL_0073: ldloc.s V_4
IL_0075: dup
IL_0076: brtrue.s IL_007a
IL_0078: pop
IL_0079: ldloc.0
IL_007a: callvirt ""void D<Base>.Invoke()""
IL_007f: ldnull
IL_0080: stloc.2
IL_0081: ldnull
IL_0082: stloc.3
IL_0083: pop
IL_0084: ret
}");
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestDelegateContravarianceConversions()
{
var source = @"
using System;
delegate void D<in T>();
class Base { }
class Derived : Base { }
class Program
{
static void Main()
{
bool testFlag = true;
D<Base> baseDelegate = () => Console.Write('B');
D<Derived> derivedDelegate = () => Console.Write('D');
D<Derived> fcn;
fcn = testFlag ? baseDelegate : derivedDelegate;
fcn();
fcn = testFlag ? derivedDelegate : baseDelegate;
fcn();
fcn = baseDelegate ?? derivedDelegate;
fcn();
fcn = derivedDelegate ?? baseDelegate;
fcn();
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"BDBD");
verifier.VerifyIL("Program.Main", @"
{
// Code size 119 (0x77)
.maxstack 3
.locals init (D<Base> V_0, //baseDelegate
D<Derived> V_1, //derivedDelegate
D<Derived> V_2)
IL_0000: ldc.i4.1
IL_0001: ldsfld ""D<Base> Program.<>c.<>9__0_0""
IL_0006: dup
IL_0007: brtrue.s IL_0020
IL_0009: pop
IL_000a: ldsfld ""Program.<>c Program.<>c.<>9""
IL_000f: ldftn ""void Program.<>c.<Main>b__0_0()""
IL_0015: newobj ""D<Base>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""D<Base> Program.<>c.<>9__0_0""
IL_0020: stloc.0
IL_0021: ldsfld ""D<Derived> Program.<>c.<>9__0_1""
IL_0026: dup
IL_0027: brtrue.s IL_0040
IL_0029: pop
IL_002a: ldsfld ""Program.<>c Program.<>c.<>9""
IL_002f: ldftn ""void Program.<>c.<Main>b__0_1()""
IL_0035: newobj ""D<Derived>..ctor(object, System.IntPtr)""
IL_003a: dup
IL_003b: stsfld ""D<Derived> Program.<>c.<>9__0_1""
IL_0040: stloc.1
IL_0041: dup
IL_0042: brtrue.s IL_0047
IL_0044: ldloc.1
IL_0045: br.s IL_004a
IL_0047: ldloc.0
IL_0048: stloc.2
IL_0049: ldloc.2
IL_004a: callvirt ""void D<Derived>.Invoke()""
IL_004f: brtrue.s IL_0056
IL_0051: ldloc.0
IL_0052: stloc.2
IL_0053: ldloc.2
IL_0054: br.s IL_0057
IL_0056: ldloc.1
IL_0057: callvirt ""void D<Derived>.Invoke()""
IL_005c: ldloc.0
IL_005d: stloc.2
IL_005e: ldloc.2
IL_005f: dup
IL_0060: brtrue.s IL_0064
IL_0062: pop
IL_0063: ldloc.1
IL_0064: callvirt ""void D<Derived>.Invoke()""
IL_0069: ldloc.1
IL_006a: dup
IL_006b: brtrue.s IL_0071
IL_006d: pop
IL_006e: ldloc.0
IL_006f: stloc.2
IL_0070: ldloc.2
IL_0071: callvirt ""void D<Derived>.Invoke()""
IL_0076: ret
}");
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestInterfaceCovarianceConversions()
{
string source = @"
using System;
interface I<out T> { }
class Base { }
class Derived : Base { }
class B : I<Base> { }
class D : I<Derived> { }
class Program
{
static void Main()
{
bool testFlag = true;
I<Base> baseInstance = new B();
I<Derived> derivedInstance = new D();
I<Base> i;
i = testFlag ? baseInstance : derivedInstance;
Console.Write(i.GetType().Name);
i = testFlag ? derivedInstance : baseInstance;
Console.Write(i.GetType().Name);
i = baseInstance ?? derivedInstance;
Console.Write(i.GetType().Name);
i = derivedInstance ?? baseInstance;
Console.Write(i.GetType().Name);
}
}
";
string expectedIL = @"
{
// Code size 107 (0x6b)
.maxstack 2
.locals init (I<Base> V_0, //baseInstance
I<Derived> V_1, //derivedInstance
I<Base> V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""B..ctor()""
IL_0006: stloc.0
IL_0007: newobj ""D..ctor()""
IL_000c: stloc.1
IL_000d: dup
IL_000e: brtrue.s IL_0015
IL_0010: ldloc.1
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: br.s IL_0016
IL_0015: ldloc.0
IL_0016: callvirt ""System.Type object.GetType()""
IL_001b: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0020: call ""void System.Console.Write(string)""
IL_0025: brtrue.s IL_002a
IL_0027: ldloc.0
IL_0028: br.s IL_002d
IL_002a: ldloc.1
IL_002b: stloc.2
IL_002c: ldloc.2
IL_002d: callvirt ""System.Type object.GetType()""
IL_0032: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0037: call ""void System.Console.Write(string)""
IL_003c: ldloc.0
IL_003d: dup
IL_003e: brtrue.s IL_0044
IL_0040: pop
IL_0041: ldloc.1
IL_0042: stloc.2
IL_0043: ldloc.2
IL_0044: callvirt ""System.Type object.GetType()""
IL_0049: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_004e: call ""void System.Console.Write(string)""
IL_0053: ldloc.1
IL_0054: stloc.2
IL_0055: ldloc.2
IL_0056: dup
IL_0057: brtrue.s IL_005b
IL_0059: pop
IL_005a: ldloc.0
IL_005b: callvirt ""System.Type object.GetType()""
IL_0060: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0065: call ""void System.Console.Write(string)""
IL_006a: ret
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"BDBD");
verifier.VerifyIL("Program.Main", expectedIL);
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestInterfaceContravarianceConversions()
{
string source = @"
using System;
interface I<in T> { }
class Base { }
class Derived : Base { }
class B : I<Base> { }
class D : I<Derived> { }
class Program
{
static void Main()
{
bool testFlag = true;
I<Base> baseInstance = new B();
I<Derived> derivedInstance = new D();
I<Derived> i;
i = testFlag ? baseInstance : derivedInstance;
Console.Write(i.GetType().Name);
i = testFlag ? derivedInstance : baseInstance;
Console.Write(i.GetType().Name);
i = baseInstance ?? derivedInstance;
Console.Write(i.GetType().Name);
i = derivedInstance ?? baseInstance;
Console.Write(i.GetType().Name);
}
}
";
string expectedIL = @"
{
// Code size 107 (0x6b)
.maxstack 2
.locals init (I<Base> V_0, //baseInstance
I<Derived> V_1, //derivedInstance
I<Derived> V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""B..ctor()""
IL_0006: stloc.0
IL_0007: newobj ""D..ctor()""
IL_000c: stloc.1
IL_000d: dup
IL_000e: brtrue.s IL_0013
IL_0010: ldloc.1
IL_0011: br.s IL_0016
IL_0013: ldloc.0
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: callvirt ""System.Type object.GetType()""
IL_001b: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0020: call ""void System.Console.Write(string)""
IL_0025: brtrue.s IL_002c
IL_0027: ldloc.0
IL_0028: stloc.2
IL_0029: ldloc.2
IL_002a: br.s IL_002d
IL_002c: ldloc.1
IL_002d: callvirt ""System.Type object.GetType()""
IL_0032: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0037: call ""void System.Console.Write(string)""
IL_003c: ldloc.0
IL_003d: stloc.2
IL_003e: ldloc.2
IL_003f: dup
IL_0040: brtrue.s IL_0044
IL_0042: pop
IL_0043: ldloc.1
IL_0044: callvirt ""System.Type object.GetType()""
IL_0049: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_004e: call ""void System.Console.Write(string)""
IL_0053: ldloc.1
IL_0054: dup
IL_0055: brtrue.s IL_005b
IL_0057: pop
IL_0058: ldloc.0
IL_0059: stloc.2
IL_005a: ldloc.2
IL_005b: callvirt ""System.Type object.GetType()""
IL_0060: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0065: call ""void System.Console.Write(string)""
IL_006a: ret
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"BDBD");
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void TestBug7196()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = false;
static void Main()
{
IEnumerable<string> v1 = Enumerable.Repeat<string>(""string"", 1);
IEnumerable<object> v2 = Enumerable.Empty<object>();
IEnumerable<object> v3 = testFlag ? v2 : v1;
if (!testFlag){
Console.WriteLine(v3.Count());
}
}
}
";
string expectedIL = @"
{
// Code size 51 (0x33)
.maxstack 2
.locals init (System.Collections.Generic.IEnumerable<string> V_0, //v1
System.Collections.Generic.IEnumerable<object> V_1, //v2
System.Collections.Generic.IEnumerable<object> V_2, //v3
System.Collections.Generic.IEnumerable<object> V_3)
IL_0000: ldstr ""string""
IL_0005: ldc.i4.1
IL_0006: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_000b: stloc.0
IL_000c: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0011: stloc.1
IL_0012: ldsfld ""bool Program.testFlag""
IL_0017: brtrue.s IL_001e
IL_0019: ldloc.0
IL_001a: stloc.3
IL_001b: ldloc.3
IL_001c: br.s IL_001f
IL_001e: ldloc.1
IL_001f: stloc.2
IL_0020: ldsfld ""bool Program.testFlag""
IL_0025: brtrue.s IL_0032
IL_0027: ldloc.2
IL_0028: call ""int System.Linq.Enumerable.Count<object>(System.Collections.Generic.IEnumerable<object>)""
IL_002d: call ""void System.Console.WriteLine(int)""
IL_0032: ret
}
";
var verifier = CompileAndVerify(
new string[] { source },
expectedOutput: "1",
symbolValidator: validator,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All));
verifier.VerifyIL("Program.Main", expectedIL);
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Program");
Assert.Null(type.GetMember(".cctor"));
}
}
[Fact]
public void TestBug7196a()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = true;
static void Main()
{
IEnumerable<string> v1 = Enumerable.Repeat<string>(""string"", 1);
IEnumerable<object> v2 = Enumerable.Empty<object>();
IEnumerable<object> v3 = v1 ?? v2;
if (testFlag){
Console.WriteLine(v3.Count());
}
}
}
";
string expectedIL = @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (System.Collections.Generic.IEnumerable<object> V_0, //v2
System.Collections.Generic.IEnumerable<object> V_1, //v3
System.Collections.Generic.IEnumerable<object> V_2)
IL_0000: ldstr ""string""
IL_0005: ldc.i4.1
IL_0006: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_000b: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0010: stloc.0
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: dup
IL_0014: brtrue.s IL_0018
IL_0016: pop
IL_0017: ldloc.0
IL_0018: stloc.1
IL_0019: ldsfld ""bool Program.testFlag""
IL_001e: brfalse.s IL_002b
IL_0020: ldloc.1
IL_0021: call ""int System.Linq.Enumerable.Count<object>(System.Collections.Generic.IEnumerable<object>)""
IL_0026: call ""void System.Console.WriteLine(int)""
IL_002b: ret
}
";
var verifier = CompileAndVerify(new string[] { source }, expectedOutput: "1");
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void TestBug7196b()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = true;
static void Main()
{
string[] v1 = Enumerable.Repeat<string>(""string"", 1).ToArray();
object[] v2 = Enumerable.Empty<object>().ToArray();
object[] v3 = v1 ?? v2;
if (testFlag){
Console.WriteLine(v3.Length);
}
}
}
";
string expectedIL = @"
{
// Code size 51 (0x33)
.maxstack 2
.locals init (object[] V_0, //v2
object[] V_1, //v3
object[] V_2)
IL_0000: ldstr ""string""
IL_0005: ldc.i4.1
IL_0006: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_000b: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)""
IL_0010: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0015: call ""object[] System.Linq.Enumerable.ToArray<object>(System.Collections.Generic.IEnumerable<object>)""
IL_001a: stloc.0
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: dup
IL_001e: brtrue.s IL_0022
IL_0020: pop
IL_0021: ldloc.0
IL_0022: stloc.1
IL_0023: ldsfld ""bool Program.testFlag""
IL_0028: brfalse.s IL_0032
IL_002a: ldloc.1
IL_002b: ldlen
IL_002c: conv.i4
IL_002d: call ""void System.Console.WriteLine(int)""
IL_0032: ret
}
";
var verifier = CompileAndVerify(new string[] { source }, expectedOutput: "1");
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void TestBug7196c()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = true;
static void Main()
{
IEnumerable<string>[] v1 = new IEnumerable<string>[] { Enumerable.Repeat<string>(""string"", 1)};
IEnumerable<object>[] v2 = new IEnumerable<object>[] { Enumerable.Empty<object>()};
IEnumerable<object>[] v3 = v1 ?? v2;
if (testFlag){
Console.WriteLine(v3.Length);
}
}
}
";
string expectedIL = @"
{
// Code size 61 (0x3d)
.maxstack 5
.locals init (System.Collections.Generic.IEnumerable<string>[] V_0, //v1
System.Collections.Generic.IEnumerable<object>[] V_1, //v2
System.Collections.Generic.IEnumerable<object>[] V_2, //v3
System.Collections.Generic.IEnumerable<object>[] V_3)
IL_0000: ldc.i4.1
IL_0001: newarr ""System.Collections.Generic.IEnumerable<string>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldstr ""string""
IL_000d: ldc.i4.1
IL_000e: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_0013: stelem.ref
IL_0014: stloc.0
IL_0015: ldc.i4.1
IL_0016: newarr ""System.Collections.Generic.IEnumerable<object>""
IL_001b: dup
IL_001c: ldc.i4.0
IL_001d: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0022: stelem.ref
IL_0023: stloc.1
IL_0024: ldloc.0
IL_0025: stloc.3
IL_0026: ldloc.3
IL_0027: dup
IL_0028: brtrue.s IL_002c
IL_002a: pop
IL_002b: ldloc.1
IL_002c: stloc.2
IL_002d: ldsfld ""bool Program.testFlag""
IL_0032: brfalse.s IL_003c
IL_0034: ldloc.2
IL_0035: ldlen
IL_0036: conv.i4
IL_0037: call ""void System.Console.WriteLine(int)""
IL_003c: ret
}
";
var verifier = CompileAndVerify(new string[] { source }, expectedOutput: "1");
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void TestBug7196d()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = true;
static void Main()
{
IEnumerable<string>[] v1 = new IEnumerable<string>[] { Enumerable.Repeat<string>(""string"", 1)};
IEnumerable[] v2 = new IEnumerable<object>[] { Enumerable.Empty<object>()};
IEnumerable[] v3 = v1 ?? v2;
if (testFlag){
Console.WriteLine(v3.Length);
}
}
}
";
string expectedIL = @"
{
// Code size 63 (0x3f)
.maxstack 5
.locals init (System.Collections.Generic.IEnumerable<string>[] V_0, //v1
System.Collections.IEnumerable[] V_1, //v2
System.Collections.IEnumerable[] V_2, //v3
System.Collections.IEnumerable[] V_3)
IL_0000: ldc.i4.1
IL_0001: newarr ""System.Collections.Generic.IEnumerable<string>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldstr ""string""
IL_000d: ldc.i4.1
IL_000e: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_0013: stelem.ref
IL_0014: stloc.0
IL_0015: ldc.i4.1
IL_0016: newarr ""System.Collections.Generic.IEnumerable<object>""
IL_001b: dup
IL_001c: ldc.i4.0
IL_001d: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0022: stelem.ref
IL_0023: stloc.3
IL_0024: ldloc.3
IL_0025: stloc.1
IL_0026: ldloc.0
IL_0027: stloc.3
IL_0028: ldloc.3
IL_0029: dup
IL_002a: brtrue.s IL_002e
IL_002c: pop
IL_002d: ldloc.1
IL_002e: stloc.2
IL_002f: ldsfld ""bool Program.testFlag""
IL_0034: brfalse.s IL_003e
IL_0036: ldloc.2
IL_0037: ldlen
IL_0038: conv.i4
IL_0039: call ""void System.Console.WriteLine(int)""
IL_003e: ret
}
";
var verifier = CompileAndVerify(new string[] { source }, expectedOutput: "1");
verifier.VerifyIL("Program.Main", expectedIL);
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestVarianceConversions()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
namespace TernaryAndVarianceConversion
{
delegate void CovariantDelegateWithVoidReturn<out T>();
delegate T CovariantDelegateWithValidReturn<out T>();
delegate void ContravariantDelegateVoidReturn<in T>();
delegate void ContravariantDelegateWithValidInParm<in T>(T inVal);
interface ICovariantInterface<out T>
{
void CovariantInterfaceMethodWithVoidReturn();
T CovariantInterfaceMethodWithValidReturn();
T CovariantInterfacePropertyWithValidGetter { get; }
void Test();
}
interface IContravariantInterface<in T>
{
void ContravariantInterfaceMethodWithVoidReturn();
void ContravariantInterfaceMethodWithValidInParm(T inVal);
T ContravariantInterfacePropertyWithValidSetter { set; }
void Test();
}
class CovariantInterfaceImpl<T> : ICovariantInterface<T>
{
public void CovariantInterfaceMethodWithVoidReturn() { }
public T CovariantInterfaceMethodWithValidReturn()
{
return default(T);
}
public T CovariantInterfacePropertyWithValidGetter
{
get { return default(T); }
}
public void Test()
{
Console.WriteLine(""{0}"", typeof(T));
}
}
class ContravariantInterfaceImpl<T> : IContravariantInterface<T>
{
public void ContravariantInterfaceMethodWithVoidReturn() { }
public void ContravariantInterfaceMethodWithValidInParm(T inVal) { }
public T ContravariantInterfacePropertyWithValidSetter
{
set { }
}
public void Test()
{
Console.WriteLine(""{0}"", typeof(T));
}
}
class Animal { }
class Mammal : Animal { }
class Program
{
static void Test(bool testFlag)
{
Console.WriteLine(""Testing with ternary test flag == {0}"", testFlag);
// Repro case for bug 7196
IEnumerable<object> EnumerableOfObject =
(testFlag ?
Enumerable.Repeat<string>(""string"", 1) :
Enumerable.Empty<object>());
Console.WriteLine(""{0}"", EnumerableOfObject.Count());
// Covariant implicit conversion for delegates
CovariantDelegateWithVoidReturn<Animal> covariantDelegateWithVoidReturnOfAnimal = () => { Console.WriteLine(""{0}"", typeof(Animal)); };
CovariantDelegateWithVoidReturn<Mammal> covariantDelegateWithVoidReturnOfMammal = () => { Console.WriteLine(""{0}"", typeof(Mammal)); };
CovariantDelegateWithVoidReturn<Animal> covariantDelegateWithVoidReturnOfAnimalTest;
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfMammal : covariantDelegateWithVoidReturnOfAnimal;
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfAnimal : covariantDelegateWithVoidReturnOfMammal;
covariantDelegateWithVoidReturnOfAnimalTest();
CovariantDelegateWithValidReturn<Animal> covariantDelegateWithValidReturnOfAnimal = () => { Console.WriteLine(""{0}"", typeof(Animal)); return default(Animal); };
CovariantDelegateWithValidReturn<Mammal> covariantDelegateWithValidReturnOfMammal = () => { Console.WriteLine(""{0}"", typeof(Mammal)); return default(Mammal); };
CovariantDelegateWithValidReturn<Animal> covariantDelegateWithValidReturnOfAnimalTest;
covariantDelegateWithValidReturnOfAnimalTest = testFlag ? covariantDelegateWithValidReturnOfMammal : covariantDelegateWithValidReturnOfAnimal;
covariantDelegateWithValidReturnOfAnimalTest();
covariantDelegateWithValidReturnOfAnimalTest = testFlag ? covariantDelegateWithValidReturnOfAnimal : covariantDelegateWithValidReturnOfMammal;
covariantDelegateWithValidReturnOfAnimalTest();
// Contravariant implicit conversion for delegates
ContravariantDelegateVoidReturn<Animal> contravariantDelegateVoidReturnOfAnimal = () => { Console.WriteLine(""{0}"", typeof(Animal)); };
ContravariantDelegateVoidReturn<Mammal> contravariantDelegateVoidReturnOfMammal = () => { Console.WriteLine(""{0}"", typeof(Mammal)); };
ContravariantDelegateVoidReturn<Mammal> contravariantDelegateVoidReturnOfMammalTest;
contravariantDelegateVoidReturnOfMammalTest = testFlag ? contravariantDelegateVoidReturnOfMammal : contravariantDelegateVoidReturnOfAnimal;
contravariantDelegateVoidReturnOfMammalTest();
contravariantDelegateVoidReturnOfMammalTest = testFlag ? contravariantDelegateVoidReturnOfAnimal : contravariantDelegateVoidReturnOfMammal;
contravariantDelegateVoidReturnOfMammalTest();
ContravariantDelegateWithValidInParm<Animal> contravariantDelegateWithValidInParmOfAnimal = (Animal) => { Console.WriteLine(""{0}"", typeof(Animal)); };
ContravariantDelegateWithValidInParm<Mammal> contravariantDelegateWithValidInParmOfMammal = (Mammal) => { Console.WriteLine(""{0}"", typeof(Mammal)); };
ContravariantDelegateWithValidInParm<Mammal> contravariantDelegateWithValidInParmOfMammalTest;
contravariantDelegateWithValidInParmOfMammalTest = testFlag ? contravariantDelegateWithValidInParmOfMammal : contravariantDelegateWithValidInParmOfAnimal;
contravariantDelegateWithValidInParmOfMammalTest(default(Mammal));
contravariantDelegateWithValidInParmOfMammalTest = testFlag ? contravariantDelegateWithValidInParmOfAnimal : contravariantDelegateWithValidInParmOfMammal;
contravariantDelegateWithValidInParmOfMammalTest(default(Mammal));
// Covariant implicit conversion for interfaces
ICovariantInterface<Animal> covariantInterfaceOfAnimal = new CovariantInterfaceImpl<Animal>();
ICovariantInterface<Mammal> covariantInterfaceOfMammal = new CovariantInterfaceImpl<Mammal>();
ICovariantInterface<Animal> covariantInterfaceOfAnimalTest;
covariantInterfaceOfAnimalTest = testFlag ? covariantInterfaceOfMammal : covariantInterfaceOfAnimal;
covariantInterfaceOfAnimalTest.Test();
covariantInterfaceOfAnimalTest = testFlag ? covariantInterfaceOfAnimal : covariantInterfaceOfMammal;
covariantInterfaceOfAnimalTest.Test();
// Contravariant implicit conversion for interfaces
IContravariantInterface<Animal> contravariantInterfaceOfAnimal = new ContravariantInterfaceImpl<Animal>();
IContravariantInterface<Mammal> contravariantInterfaceOfMammal = new ContravariantInterfaceImpl<Mammal>();
IContravariantInterface<Mammal> contravariantInterfaceOfMammalTest;
contravariantInterfaceOfMammalTest = testFlag ? contravariantInterfaceOfMammal : contravariantInterfaceOfAnimal;
contravariantInterfaceOfMammalTest.Test();
contravariantInterfaceOfMammalTest = testFlag ? contravariantInterfaceOfAnimal : contravariantInterfaceOfMammal;
contravariantInterfaceOfMammalTest.Test();
// With explicit casting
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? (CovariantDelegateWithVoidReturn<Animal>)covariantDelegateWithVoidReturnOfMammal : covariantDelegateWithVoidReturnOfAnimal;
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfAnimal : (CovariantDelegateWithVoidReturn<Animal>)covariantDelegateWithVoidReturnOfMammal;
covariantDelegateWithVoidReturnOfAnimalTest();
// With parens
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? (covariantDelegateWithVoidReturnOfMammal) : covariantDelegateWithVoidReturnOfAnimal;
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfAnimal : (covariantDelegateWithVoidReturnOfMammal);
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? ((CovariantDelegateWithVoidReturn<Animal>)covariantDelegateWithVoidReturnOfMammal) : covariantDelegateWithVoidReturnOfAnimal;
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfAnimal : ((CovariantDelegateWithVoidReturn<Animal>)covariantDelegateWithVoidReturnOfMammal);
covariantDelegateWithVoidReturnOfAnimalTest();
// Bug 291602
int[] intarr = { 1, 2, 3 };
IList<int> intlist = new List<int>(intarr);
IList<int> intternary = testFlag ? intarr : intlist;
Console.WriteLine(intternary);
}
static void Main(string[] args)
{
Test(true);
Test(false);
}
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: @"Testing with ternary test flag == True
1
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
System.Int32[]
Testing with ternary test flag == False
0
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
System.Collections.Generic.List`1[System.Int32]
");
}
[WorkItem(528424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528424")]
[Fact()]
public void TestErrorOperand()
{
var source =
@"class C
{
static object M(bool b, C c, D d)
{
return b ? c : d;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,34): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D"));
}
private static void TestConditional(string conditionalExpression, string? expectedType, params DiagnosticDescription[] expectedDiagnostics)
{
TestConditional(conditionalExpression, expectedType, null, expectedDiagnostics);
}
private static void TestConditional(string conditionalExpression, string? expectedType, CSharpParseOptions? parseOptions, params DiagnosticDescription[] expectedDiagnostics)
{
if (parseOptions is null)
{
TestConditionalCore(conditionalExpression, expectedType, TestOptions.Regular8, expectedDiagnostics);
TestConditionalCore(conditionalExpression, expectedType, TestOptions.Regular8.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()), expectedDiagnostics);
}
else
{
TestConditionalCore(conditionalExpression, expectedType, parseOptions, expectedDiagnostics);
}
}
private static void TestConditionalCore(string conditionalExpression, string? expectedType, CSharpParseOptions parseOptions, params DiagnosticDescription[] expectedDiagnostics)
{
string source = $@"
class C
{{
void Test<T, U>()
{{
_ = {conditionalExpression};
}}
int GetInt() {{ return 1; }}
void GetVoid() {{ return ; }}
bool GetBool() {{ return true; }}
short GetShort() {{ return 1; }}
char GetChar() {{ return 'a'; }}
double GetDouble() {{ return 1.5; }}
string GetString() {{ return ""hello""; }}
object GetObject() {{ return new object(); }}
C GetUserNonGeneric() {{ return new C(); }}
D<T> GetUserGeneric<T>() {{ return new D<T>(); }}
T GetTypeParameter<T>() {{ return default(T); }}
I<T, U> GetVariantInterface<T, U>() {{ return null; }}
}}
class D<T> {{ }}
public enum color {{ Red, Blue, Green }};
interface I<in T, out U> {{ }}";
var tree = Parse(source, options: parseOptions);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics(expectedDiagnostics);
var compUnit = tree.GetCompilationUnitRoot();
var classC = (TypeDeclarationSyntax)compUnit.Members.First();
var methodTest = (MethodDeclarationSyntax)classC.Members.First();
var stmt = (ExpressionStatementSyntax)methodTest.Body!.Statements.First();
var assignment = (AssignmentExpressionSyntax)stmt.Expression;
var conditionalExpr = (ConditionalExpressionSyntax)assignment.Right;
var model = comp.GetSemanticModel(tree);
if (expectedType != null)
{
Assert.Equal(expectedType, model.GetTypeInfo(conditionalExpr).Type.ToTestDisplayString());
if (!expectedDiagnostics.Any())
{
Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(conditionalExpr.Condition).Type!.SpecialType);
Assert.Equal(expectedType, model.GetTypeInfo(conditionalExpr.WhenTrue).ConvertedType.ToTestDisplayString()); //in parent to catch conversion
Assert.Equal(expectedType, model.GetTypeInfo(conditionalExpr.WhenFalse).ConvertedType.ToTestDisplayString()); //in parent to catch conversion
}
}
}
[Fact, WorkItem(4028, "https://github.com/dotnet/roslyn/issues/4028")]
public void ConditionalAccessToEvent_01()
{
string source = @"
using System;
class TestClass
{
event Action test;
public static void Test(TestClass receiver)
{
Console.WriteLine(receiver?.test);
}
static void Main()
{
Console.WriteLine(""----"");
Test(null);
Console.WriteLine(""----"");
Test(new TestClass() {test = Main});
Console.WriteLine(""----"");
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput:
@"----
----
System.Action
----");
var tree = compilation.SyntaxTrees.Single();
var memberBinding = tree.GetRoot().DescendantNodes().OfType<MemberBindingExpressionSyntax>().Single();
var access = (ConditionalAccessExpressionSyntax)memberBinding.Parent!;
Assert.Equal(".test", memberBinding.ToString());
Assert.Equal("receiver?.test", access.ToString());
var model = compilation.GetSemanticModel(tree);
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding).Symbol.ToTestDisplayString());
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding.Name).Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(access).Symbol);
}
[Fact, WorkItem(4028, "https://github.com/dotnet/roslyn/issues/4028")]
public void ConditionalAccessToEvent_02()
{
string source = @"
using System;
class TestClass
{
event Action test;
public static void Test(TestClass receiver)
{
receiver?.test();
}
static void Main()
{
Console.WriteLine(""----"");
Test(null);
Console.WriteLine(""----"");
Test(new TestClass() {test = Target});
Console.WriteLine(""----"");
}
static void Target()
{
Console.WriteLine(""Target"");
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput:
@"----
----
Target
----");
var tree = compilation.SyntaxTrees.Single();
var memberBinding = tree.GetRoot().DescendantNodes().OfType<MemberBindingExpressionSyntax>().Single();
var invocation = (InvocationExpressionSyntax)memberBinding.Parent!;
var access = (ConditionalAccessExpressionSyntax)invocation.Parent!;
Assert.Equal(".test", memberBinding.ToString());
Assert.Equal(".test()", invocation.ToString());
Assert.Equal("receiver?.test()", access.ToString());
var model = compilation.GetSemanticModel(tree);
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding).Symbol.ToTestDisplayString());
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding.Name).Symbol.ToTestDisplayString());
Assert.Equal("void System.Action.Invoke()", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(access).Symbol);
}
[Fact, WorkItem(4028, "https://github.com/dotnet/roslyn/issues/4028")]
public void ConditionalAccessToEvent_03()
{
string source = @"
using System;
class TestClass
{
event Action test;
public static void Test(TestClass receiver)
{
receiver?.test += Main;
}
static void Main()
{
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// receiver?.test += Main;
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "receiver?.test").WithLocation(10, 9)
);
var tree = compilation.SyntaxTrees.Single();
var memberBinding = tree.GetRoot().DescendantNodes().OfType<MemberBindingExpressionSyntax>().Single();
var access = (ConditionalAccessExpressionSyntax)memberBinding.Parent!;
Assert.Equal(".test", memberBinding.ToString());
Assert.Equal("receiver?.test", access.ToString());
var model = compilation.GetSemanticModel(tree);
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding).Symbol.ToTestDisplayString());
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding.Name).Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(access).Symbol);
}
[Fact(), WorkItem(4615, "https://github.com/dotnet/roslyn/issues/4615")]
public void ConditionalAndConditionalMethods()
{
string source = @"
class Program
{
static void Main(string[] args)
{
TestClass.Create().Test();
TestClass.Create().Self().Test();
System.Console.WriteLine(""---"");
TestClass.Create()?.Test();
TestClass.Create()?.Self().Test();
TestClass.Create()?.Self()?.Test();
}
}
class TestClass
{
[System.Diagnostics.Conditional(""DEBUG"")]
public void Test()
{
System.Console.WriteLine(""Test"");
}
public static TestClass Create()
{
System.Console.WriteLine(""Create"");
return new TestClass();
}
public TestClass Self()
{
System.Console.WriteLine(""Self"");
return this;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe,
parseOptions: CSharpParseOptions.Default.WithPreprocessorSymbols("DEBUG"));
CompileAndVerify(compilation, expectedOutput:
@"Create
Test
Create
Self
Test
---
Create
Test
Create
Self
Test
Create
Self
Test
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: "---");
}
[Fact, WorkItem(1198816, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1198816/")]
public void DefiniteAssignment_UnconvertedConditionalOperator()
{
var source =
@"class Program
{
static void Main()
{
_ = new(bad) ? null : new object();
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): error CS0103: The name 'bad' does not exist in the current context
// _ = new(bad) ? null : new object();
Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(5, 17)
);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// Test binding of the conditional (aka ternary) operator.
/// </summary>
public class ConditionalOperatorTests : CSharpTestBase
{
/// <summary>
/// Both branches have the same type, so no conversion is necessary.
/// </summary>
[Fact]
public void TestSameType()
{
TestConditional("true ? 1 : 2", expectedType: "System.Int32");
TestConditional("false ? 'a' : 'b'", expectedType: "System.Char");
TestConditional("true ? 1.5 : GetDouble()", expectedType: "System.Double");
TestConditional("false ? GetObject() : GetObject()", expectedType: "System.Object");
TestConditional("true ? GetUserGeneric<T>() : GetUserGeneric<T>()", expectedType: "D<T>");
TestConditional("false ? GetTypeParameter<T>() : GetTypeParameter<T>()", expectedType: "T");
}
/// <summary>
/// Both branches have types and exactly one expression is convertible to the type of the other.
/// </summary>
[Fact]
public void TestOneConversion()
{
TestConditional("true ? GetShort() : GetInt()", expectedType: "System.Int32");
TestConditional("false ? \"string\" : GetObject()", expectedType: "System.Object");
TestConditional("true ? GetVariantInterface<string, int>() : GetVariantInterface<object, int>()", expectedType: "I<System.String, System.Int32>");
TestConditional("false ? GetVariantInterface<int, object>() : GetVariantInterface<int, string>()", expectedType: "I<System.Int32, System.Object>");
}
/// <summary>
/// Both branches have types and both expression are convertible to the type of the other.
/// The wider type is preferred.
/// </summary>
/// <remarks>
/// Cases where both conversions are possible and neither is preferred as the
/// wider of the two are possible only in the presence of user-defined implicit
/// conversions. Such cases are tested separately.
/// See SemanticErrorTests.CS0172ERR_AmbigQM.
/// </remarks>
[Fact]
public void TestAmbiguousPreferWider()
{
TestConditional("true ? 1 : (short)2", expectedType: "System.Int32");
TestConditional("false ? (float)2 : 1", expectedType: "System.Single");
TestConditional("true ? 1.5d : (double)2", expectedType: "System.Double");
}
/// <summary>
/// Both branches have types but neither expression is convertible to the type
/// of the other.
/// </summary>
[Fact]
public void TestNoConversion()
{
TestConditional("true ? T : U", null, parseOptions: TestOptions.Regular8,
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type"),
Diagnostic(ErrorCode.ERR_BadSKunknown, "U").WithArguments("U", "type"));
TestConditional("true ? T : U", null, parseOptions: TestOptions.Regular8.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()),
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type"),
Diagnostic(ErrorCode.ERR_BadSKunknown, "U").WithArguments("U", "type"));
TestConditional("false ? T : 1", null, parseOptions: TestOptions.Regular8,
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type"));
TestConditional("false ? T : 1", null, parseOptions: TestOptions.Regular8.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()),
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type"));
TestConditional("true ? GetUserGeneric<char>() : GetUserNonGeneric()", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? GetUserGeneric<char>() : GetUserNonGeneric()").WithArguments("D<char>", "C"));
}
/// <summary>
/// Exactly one branch has a type and the other expression is convertible to that type.
/// </summary>
[Fact]
public void TestOneUntypedSuccess()
{
TestConditional("true ? GetObject() : null", expectedType: "System.Object"); //null literal
TestConditional("false ? GetString : (System.Func<string>)null", expectedType: "System.Func<System.String>"); //method group
TestConditional("true ? (System.Func<int, int>)null : x => x", expectedType: "System.Func<System.Int32, System.Int32>"); //lambda
}
/// <summary>
/// Exactly one branch has a type but the other expression is not convertible to that type.
/// </summary>
[Fact]
public void TestOneUntypedFailure()
{
TestConditional("true ? GetInt() : null", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? GetInt() : null").WithArguments("int", "<null>"));
TestConditional("false ? GetString : (System.Func<int>)null", null, TestOptions.WithoutImprovedOverloadCandidates,
Diagnostic(ErrorCode.ERR_BadRetType, "GetString").WithArguments("C.GetString()", "string"));
TestConditional("false ? GetString : (System.Func<int>)null", null,
// (6,13): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'Func<int>'
// _ = false ? GetString : (System.Func<int>)null;
Diagnostic(ErrorCode.ERR_InvalidQM, "false ? GetString : (System.Func<int>)null").WithArguments("method group", "System.Func<int>"));
TestConditional("true ? (System.Func<int, short>)null : x => x", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? (System.Func<int, short>)null : x => x").WithArguments("System.Func<int, short>", "lambda expression"));
}
[Fact]
public void TestBothUntyped()
{
TestConditional("true ? null : null", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? null : null").WithArguments("<null>", "<null>"));
TestConditional("false ? null : GetInt", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "false ? null : GetInt").WithArguments("<null>", "method group"));
TestConditional("true ? null : x => x", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? null : x => x").WithArguments("<null>", "lambda expression"));
TestConditional("false ? GetInt : GetInt", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "false ? GetInt : GetInt").WithArguments("method group", "method group"));
TestConditional("true ? GetInt : x => x", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? GetInt : x => x").WithArguments("method group", "lambda expression"));
TestConditional("false ? x => x : x => x", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "false ? x => x : x => x").WithArguments("lambda expression", "lambda expression"));
}
[Fact]
public void TestFunCall()
{
TestConditional("true ? GetVoid() : GetInt()", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true ? GetVoid() : GetInt()").WithArguments("void", "int"));
TestConditional("GetVoid() ? 1 : 2", null,
Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetVoid()").WithArguments("void", "bool"));
TestConditional("GetInt() ? 1 : 2", null,
Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetInt()").WithArguments("int", "bool"));
TestConditional("GetBool() ? 1 : 2", "System.Int32");
}
[Fact]
public void TestEmptyExpression()
{
TestConditional("true ? : GetInt()", null,
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"));
TestConditional("true ? GetInt() : ", null,
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"));
}
[Fact]
public void TestEnum()
{
TestConditional("true? 0 : color.Blue", "color");
TestConditional("true? 5 : color.Blue", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true? 5 : color.Blue").WithArguments("int", "color"));
TestConditional("true? null : color.Blue", null,
Diagnostic(ErrorCode.ERR_InvalidQM, "true? null : color.Blue").WithArguments("<null>", "color"));
}
[Fact]
public void TestAs()
{
TestConditional(@"(1 < 2) ? ""MyString"" as string : "" """, "System.String");
TestConditional(@"(1 > 2) ? "" "" : ""MyString"" as string", "System.String");
}
[Fact]
public void TestGeneric()
{
TestConditional(@"GetUserNonGeneric()? 1 : 2", null, Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetUserNonGeneric()").WithArguments("C", "bool"));
TestConditional(@"GetUserGeneric<T>()? 1 : 2", null, Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetUserGeneric<T>()").WithArguments("D<T>", "bool"));
TestConditional(@"GetTypeParameter<T>()? 1 : 2", null, Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetTypeParameter<T>()").WithArguments("T", "bool"));
TestConditional(@"GetVariantInterface<T, U>()? 1 : 2", null, Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetVariantInterface<T, U>()").WithArguments("I<T, U>", "bool"));
}
[Fact]
public void TestInvalidCondition()
{
// CONSIDER: dev10 reports ERR_ConstOutOfRange
TestConditional("1 ? 2 : 3", null,
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool"));
TestConditional("goo ? 'a' : 'b'", null,
Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo"));
TestConditional("new Goo() ? GetObject() : null", null,
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Goo").WithArguments("Goo"));
// CONSIDER: dev10 reports ERR_ConstOutOfRange
TestConditional("1 ? null : null", null, parseOptions: TestOptions.Regular8,
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool")
);
TestConditional("1 ? null : null", null, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()),
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool")
);
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestDelegateCovarianceConversions()
{
var source = @"
using System;
using System.Collections.Generic;
delegate void D<out T>();
class Base { }
class Derived : Base { }
class Program
{
static void Main()
{
bool testFlag = true;
D<Base> baseDelegate = () => Console.WriteLine(""B"");
D<Derived> derivedDelegate = () => Console.WriteLine(""D"");
D<Base> fcn;
fcn = testFlag ? baseDelegate : derivedDelegate;
fcn();
fcn = testFlag ? derivedDelegate : baseDelegate;
fcn();
fcn = baseDelegate ?? derivedDelegate;
fcn();
fcn = derivedDelegate ?? baseDelegate;
fcn();
IEnumerable<Base> baseSequence = null;
List<Derived> derivedList = null;
IEnumerable<Base> result = testFlag ? baseSequence : derivedList;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"B
D
B
D");
// Note no castclass instructions
// to be completely sure that stack states merge with expected types
// we use "stloc;ldloc" as a surrogate "static cast" for values
// in different branches
verifier.VerifyIL("Program.Main", @"
{
// Code size 133 (0x85)
.maxstack 3
.locals init (D<Base> V_0, //baseDelegate
D<Derived> V_1, //derivedDelegate
System.Collections.Generic.IEnumerable<Base> V_2, //baseSequence
System.Collections.Generic.List<Derived> V_3, //derivedList
D<Base> V_4)
IL_0000: ldc.i4.1
IL_0001: ldsfld ""D<Base> Program.<>c.<>9__0_0""
IL_0006: dup
IL_0007: brtrue.s IL_0020
IL_0009: pop
IL_000a: ldsfld ""Program.<>c Program.<>c.<>9""
IL_000f: ldftn ""void Program.<>c.<Main>b__0_0()""
IL_0015: newobj ""D<Base>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""D<Base> Program.<>c.<>9__0_0""
IL_0020: stloc.0
IL_0021: ldsfld ""D<Derived> Program.<>c.<>9__0_1""
IL_0026: dup
IL_0027: brtrue.s IL_0040
IL_0029: pop
IL_002a: ldsfld ""Program.<>c Program.<>c.<>9""
IL_002f: ldftn ""void Program.<>c.<Main>b__0_1()""
IL_0035: newobj ""D<Derived>..ctor(object, System.IntPtr)""
IL_003a: dup
IL_003b: stsfld ""D<Derived> Program.<>c.<>9__0_1""
IL_0040: stloc.1
IL_0041: dup
IL_0042: brtrue.s IL_004b
IL_0044: ldloc.1
IL_0045: stloc.s V_4
IL_0047: ldloc.s V_4
IL_0049: br.s IL_004c
IL_004b: ldloc.0
IL_004c: callvirt ""void D<Base>.Invoke()""
IL_0051: dup
IL_0052: brtrue.s IL_0057
IL_0054: ldloc.0
IL_0055: br.s IL_005c
IL_0057: ldloc.1
IL_0058: stloc.s V_4
IL_005a: ldloc.s V_4
IL_005c: callvirt ""void D<Base>.Invoke()""
IL_0061: ldloc.0
IL_0062: dup
IL_0063: brtrue.s IL_006b
IL_0065: pop
IL_0066: ldloc.1
IL_0067: stloc.s V_4
IL_0069: ldloc.s V_4
IL_006b: callvirt ""void D<Base>.Invoke()""
IL_0070: ldloc.1
IL_0071: stloc.s V_4
IL_0073: ldloc.s V_4
IL_0075: dup
IL_0076: brtrue.s IL_007a
IL_0078: pop
IL_0079: ldloc.0
IL_007a: callvirt ""void D<Base>.Invoke()""
IL_007f: ldnull
IL_0080: stloc.2
IL_0081: ldnull
IL_0082: stloc.3
IL_0083: pop
IL_0084: ret
}");
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestDelegateContravarianceConversions()
{
var source = @"
using System;
delegate void D<in T>();
class Base { }
class Derived : Base { }
class Program
{
static void Main()
{
bool testFlag = true;
D<Base> baseDelegate = () => Console.Write('B');
D<Derived> derivedDelegate = () => Console.Write('D');
D<Derived> fcn;
fcn = testFlag ? baseDelegate : derivedDelegate;
fcn();
fcn = testFlag ? derivedDelegate : baseDelegate;
fcn();
fcn = baseDelegate ?? derivedDelegate;
fcn();
fcn = derivedDelegate ?? baseDelegate;
fcn();
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"BDBD");
verifier.VerifyIL("Program.Main", @"
{
// Code size 119 (0x77)
.maxstack 3
.locals init (D<Base> V_0, //baseDelegate
D<Derived> V_1, //derivedDelegate
D<Derived> V_2)
IL_0000: ldc.i4.1
IL_0001: ldsfld ""D<Base> Program.<>c.<>9__0_0""
IL_0006: dup
IL_0007: brtrue.s IL_0020
IL_0009: pop
IL_000a: ldsfld ""Program.<>c Program.<>c.<>9""
IL_000f: ldftn ""void Program.<>c.<Main>b__0_0()""
IL_0015: newobj ""D<Base>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""D<Base> Program.<>c.<>9__0_0""
IL_0020: stloc.0
IL_0021: ldsfld ""D<Derived> Program.<>c.<>9__0_1""
IL_0026: dup
IL_0027: brtrue.s IL_0040
IL_0029: pop
IL_002a: ldsfld ""Program.<>c Program.<>c.<>9""
IL_002f: ldftn ""void Program.<>c.<Main>b__0_1()""
IL_0035: newobj ""D<Derived>..ctor(object, System.IntPtr)""
IL_003a: dup
IL_003b: stsfld ""D<Derived> Program.<>c.<>9__0_1""
IL_0040: stloc.1
IL_0041: dup
IL_0042: brtrue.s IL_0047
IL_0044: ldloc.1
IL_0045: br.s IL_004a
IL_0047: ldloc.0
IL_0048: stloc.2
IL_0049: ldloc.2
IL_004a: callvirt ""void D<Derived>.Invoke()""
IL_004f: brtrue.s IL_0056
IL_0051: ldloc.0
IL_0052: stloc.2
IL_0053: ldloc.2
IL_0054: br.s IL_0057
IL_0056: ldloc.1
IL_0057: callvirt ""void D<Derived>.Invoke()""
IL_005c: ldloc.0
IL_005d: stloc.2
IL_005e: ldloc.2
IL_005f: dup
IL_0060: brtrue.s IL_0064
IL_0062: pop
IL_0063: ldloc.1
IL_0064: callvirt ""void D<Derived>.Invoke()""
IL_0069: ldloc.1
IL_006a: dup
IL_006b: brtrue.s IL_0071
IL_006d: pop
IL_006e: ldloc.0
IL_006f: stloc.2
IL_0070: ldloc.2
IL_0071: callvirt ""void D<Derived>.Invoke()""
IL_0076: ret
}");
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestInterfaceCovarianceConversions()
{
string source = @"
using System;
interface I<out T> { }
class Base { }
class Derived : Base { }
class B : I<Base> { }
class D : I<Derived> { }
class Program
{
static void Main()
{
bool testFlag = true;
I<Base> baseInstance = new B();
I<Derived> derivedInstance = new D();
I<Base> i;
i = testFlag ? baseInstance : derivedInstance;
Console.Write(i.GetType().Name);
i = testFlag ? derivedInstance : baseInstance;
Console.Write(i.GetType().Name);
i = baseInstance ?? derivedInstance;
Console.Write(i.GetType().Name);
i = derivedInstance ?? baseInstance;
Console.Write(i.GetType().Name);
}
}
";
string expectedIL = @"
{
// Code size 107 (0x6b)
.maxstack 2
.locals init (I<Base> V_0, //baseInstance
I<Derived> V_1, //derivedInstance
I<Base> V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""B..ctor()""
IL_0006: stloc.0
IL_0007: newobj ""D..ctor()""
IL_000c: stloc.1
IL_000d: dup
IL_000e: brtrue.s IL_0015
IL_0010: ldloc.1
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: br.s IL_0016
IL_0015: ldloc.0
IL_0016: callvirt ""System.Type object.GetType()""
IL_001b: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0020: call ""void System.Console.Write(string)""
IL_0025: brtrue.s IL_002a
IL_0027: ldloc.0
IL_0028: br.s IL_002d
IL_002a: ldloc.1
IL_002b: stloc.2
IL_002c: ldloc.2
IL_002d: callvirt ""System.Type object.GetType()""
IL_0032: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0037: call ""void System.Console.Write(string)""
IL_003c: ldloc.0
IL_003d: dup
IL_003e: brtrue.s IL_0044
IL_0040: pop
IL_0041: ldloc.1
IL_0042: stloc.2
IL_0043: ldloc.2
IL_0044: callvirt ""System.Type object.GetType()""
IL_0049: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_004e: call ""void System.Console.Write(string)""
IL_0053: ldloc.1
IL_0054: stloc.2
IL_0055: ldloc.2
IL_0056: dup
IL_0057: brtrue.s IL_005b
IL_0059: pop
IL_005a: ldloc.0
IL_005b: callvirt ""System.Type object.GetType()""
IL_0060: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0065: call ""void System.Console.Write(string)""
IL_006a: ret
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"BDBD");
verifier.VerifyIL("Program.Main", expectedIL);
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestInterfaceContravarianceConversions()
{
string source = @"
using System;
interface I<in T> { }
class Base { }
class Derived : Base { }
class B : I<Base> { }
class D : I<Derived> { }
class Program
{
static void Main()
{
bool testFlag = true;
I<Base> baseInstance = new B();
I<Derived> derivedInstance = new D();
I<Derived> i;
i = testFlag ? baseInstance : derivedInstance;
Console.Write(i.GetType().Name);
i = testFlag ? derivedInstance : baseInstance;
Console.Write(i.GetType().Name);
i = baseInstance ?? derivedInstance;
Console.Write(i.GetType().Name);
i = derivedInstance ?? baseInstance;
Console.Write(i.GetType().Name);
}
}
";
string expectedIL = @"
{
// Code size 107 (0x6b)
.maxstack 2
.locals init (I<Base> V_0, //baseInstance
I<Derived> V_1, //derivedInstance
I<Derived> V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""B..ctor()""
IL_0006: stloc.0
IL_0007: newobj ""D..ctor()""
IL_000c: stloc.1
IL_000d: dup
IL_000e: brtrue.s IL_0013
IL_0010: ldloc.1
IL_0011: br.s IL_0016
IL_0013: ldloc.0
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: callvirt ""System.Type object.GetType()""
IL_001b: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0020: call ""void System.Console.Write(string)""
IL_0025: brtrue.s IL_002c
IL_0027: ldloc.0
IL_0028: stloc.2
IL_0029: ldloc.2
IL_002a: br.s IL_002d
IL_002c: ldloc.1
IL_002d: callvirt ""System.Type object.GetType()""
IL_0032: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0037: call ""void System.Console.Write(string)""
IL_003c: ldloc.0
IL_003d: stloc.2
IL_003e: ldloc.2
IL_003f: dup
IL_0040: brtrue.s IL_0044
IL_0042: pop
IL_0043: ldloc.1
IL_0044: callvirt ""System.Type object.GetType()""
IL_0049: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_004e: call ""void System.Console.Write(string)""
IL_0053: ldloc.1
IL_0054: dup
IL_0055: brtrue.s IL_005b
IL_0057: pop
IL_0058: ldloc.0
IL_0059: stloc.2
IL_005a: ldloc.2
IL_005b: callvirt ""System.Type object.GetType()""
IL_0060: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0065: call ""void System.Console.Write(string)""
IL_006a: ret
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"BDBD");
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void TestBug7196()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = false;
static void Main()
{
IEnumerable<string> v1 = Enumerable.Repeat<string>(""string"", 1);
IEnumerable<object> v2 = Enumerable.Empty<object>();
IEnumerable<object> v3 = testFlag ? v2 : v1;
if (!testFlag){
Console.WriteLine(v3.Count());
}
}
}
";
string expectedIL = @"
{
// Code size 51 (0x33)
.maxstack 2
.locals init (System.Collections.Generic.IEnumerable<string> V_0, //v1
System.Collections.Generic.IEnumerable<object> V_1, //v2
System.Collections.Generic.IEnumerable<object> V_2, //v3
System.Collections.Generic.IEnumerable<object> V_3)
IL_0000: ldstr ""string""
IL_0005: ldc.i4.1
IL_0006: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_000b: stloc.0
IL_000c: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0011: stloc.1
IL_0012: ldsfld ""bool Program.testFlag""
IL_0017: brtrue.s IL_001e
IL_0019: ldloc.0
IL_001a: stloc.3
IL_001b: ldloc.3
IL_001c: br.s IL_001f
IL_001e: ldloc.1
IL_001f: stloc.2
IL_0020: ldsfld ""bool Program.testFlag""
IL_0025: brtrue.s IL_0032
IL_0027: ldloc.2
IL_0028: call ""int System.Linq.Enumerable.Count<object>(System.Collections.Generic.IEnumerable<object>)""
IL_002d: call ""void System.Console.WriteLine(int)""
IL_0032: ret
}
";
var verifier = CompileAndVerify(
new string[] { source },
expectedOutput: "1",
symbolValidator: validator,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All));
verifier.VerifyIL("Program.Main", expectedIL);
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Program");
Assert.Null(type.GetMember(".cctor"));
}
}
[Fact]
public void TestBug7196a()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = true;
static void Main()
{
IEnumerable<string> v1 = Enumerable.Repeat<string>(""string"", 1);
IEnumerable<object> v2 = Enumerable.Empty<object>();
IEnumerable<object> v3 = v1 ?? v2;
if (testFlag){
Console.WriteLine(v3.Count());
}
}
}
";
string expectedIL = @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (System.Collections.Generic.IEnumerable<object> V_0, //v2
System.Collections.Generic.IEnumerable<object> V_1, //v3
System.Collections.Generic.IEnumerable<object> V_2)
IL_0000: ldstr ""string""
IL_0005: ldc.i4.1
IL_0006: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_000b: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0010: stloc.0
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: dup
IL_0014: brtrue.s IL_0018
IL_0016: pop
IL_0017: ldloc.0
IL_0018: stloc.1
IL_0019: ldsfld ""bool Program.testFlag""
IL_001e: brfalse.s IL_002b
IL_0020: ldloc.1
IL_0021: call ""int System.Linq.Enumerable.Count<object>(System.Collections.Generic.IEnumerable<object>)""
IL_0026: call ""void System.Console.WriteLine(int)""
IL_002b: ret
}
";
var verifier = CompileAndVerify(new string[] { source }, expectedOutput: "1");
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void TestBug7196b()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = true;
static void Main()
{
string[] v1 = Enumerable.Repeat<string>(""string"", 1).ToArray();
object[] v2 = Enumerable.Empty<object>().ToArray();
object[] v3 = v1 ?? v2;
if (testFlag){
Console.WriteLine(v3.Length);
}
}
}
";
string expectedIL = @"
{
// Code size 51 (0x33)
.maxstack 2
.locals init (object[] V_0, //v2
object[] V_1, //v3
object[] V_2)
IL_0000: ldstr ""string""
IL_0005: ldc.i4.1
IL_0006: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_000b: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)""
IL_0010: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0015: call ""object[] System.Linq.Enumerable.ToArray<object>(System.Collections.Generic.IEnumerable<object>)""
IL_001a: stloc.0
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: dup
IL_001e: brtrue.s IL_0022
IL_0020: pop
IL_0021: ldloc.0
IL_0022: stloc.1
IL_0023: ldsfld ""bool Program.testFlag""
IL_0028: brfalse.s IL_0032
IL_002a: ldloc.1
IL_002b: ldlen
IL_002c: conv.i4
IL_002d: call ""void System.Console.WriteLine(int)""
IL_0032: ret
}
";
var verifier = CompileAndVerify(new string[] { source }, expectedOutput: "1");
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void TestBug7196c()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = true;
static void Main()
{
IEnumerable<string>[] v1 = new IEnumerable<string>[] { Enumerable.Repeat<string>(""string"", 1)};
IEnumerable<object>[] v2 = new IEnumerable<object>[] { Enumerable.Empty<object>()};
IEnumerable<object>[] v3 = v1 ?? v2;
if (testFlag){
Console.WriteLine(v3.Length);
}
}
}
";
string expectedIL = @"
{
// Code size 61 (0x3d)
.maxstack 5
.locals init (System.Collections.Generic.IEnumerable<string>[] V_0, //v1
System.Collections.Generic.IEnumerable<object>[] V_1, //v2
System.Collections.Generic.IEnumerable<object>[] V_2, //v3
System.Collections.Generic.IEnumerable<object>[] V_3)
IL_0000: ldc.i4.1
IL_0001: newarr ""System.Collections.Generic.IEnumerable<string>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldstr ""string""
IL_000d: ldc.i4.1
IL_000e: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_0013: stelem.ref
IL_0014: stloc.0
IL_0015: ldc.i4.1
IL_0016: newarr ""System.Collections.Generic.IEnumerable<object>""
IL_001b: dup
IL_001c: ldc.i4.0
IL_001d: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0022: stelem.ref
IL_0023: stloc.1
IL_0024: ldloc.0
IL_0025: stloc.3
IL_0026: ldloc.3
IL_0027: dup
IL_0028: brtrue.s IL_002c
IL_002a: pop
IL_002b: ldloc.1
IL_002c: stloc.2
IL_002d: ldsfld ""bool Program.testFlag""
IL_0032: brfalse.s IL_003c
IL_0034: ldloc.2
IL_0035: ldlen
IL_0036: conv.i4
IL_0037: call ""void System.Console.WriteLine(int)""
IL_003c: ret
}
";
var verifier = CompileAndVerify(new string[] { source }, expectedOutput: "1");
verifier.VerifyIL("Program.Main", expectedIL);
}
[Fact]
public void TestBug7196d()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool testFlag = true;
static void Main()
{
IEnumerable<string>[] v1 = new IEnumerable<string>[] { Enumerable.Repeat<string>(""string"", 1)};
IEnumerable[] v2 = new IEnumerable<object>[] { Enumerable.Empty<object>()};
IEnumerable[] v3 = v1 ?? v2;
if (testFlag){
Console.WriteLine(v3.Length);
}
}
}
";
string expectedIL = @"
{
// Code size 63 (0x3f)
.maxstack 5
.locals init (System.Collections.Generic.IEnumerable<string>[] V_0, //v1
System.Collections.IEnumerable[] V_1, //v2
System.Collections.IEnumerable[] V_2, //v3
System.Collections.IEnumerable[] V_3)
IL_0000: ldc.i4.1
IL_0001: newarr ""System.Collections.Generic.IEnumerable<string>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldstr ""string""
IL_000d: ldc.i4.1
IL_000e: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Repeat<string>(string, int)""
IL_0013: stelem.ref
IL_0014: stloc.0
IL_0015: ldc.i4.1
IL_0016: newarr ""System.Collections.Generic.IEnumerable<object>""
IL_001b: dup
IL_001c: ldc.i4.0
IL_001d: call ""System.Collections.Generic.IEnumerable<object> System.Linq.Enumerable.Empty<object>()""
IL_0022: stelem.ref
IL_0023: stloc.3
IL_0024: ldloc.3
IL_0025: stloc.1
IL_0026: ldloc.0
IL_0027: stloc.3
IL_0028: ldloc.3
IL_0029: dup
IL_002a: brtrue.s IL_002e
IL_002c: pop
IL_002d: ldloc.1
IL_002e: stloc.2
IL_002f: ldsfld ""bool Program.testFlag""
IL_0034: brfalse.s IL_003e
IL_0036: ldloc.2
IL_0037: ldlen
IL_0038: conv.i4
IL_0039: call ""void System.Console.WriteLine(int)""
IL_003e: ret
}
";
var verifier = CompileAndVerify(new string[] { source }, expectedOutput: "1");
verifier.VerifyIL("Program.Main", expectedIL);
}
[WorkItem(545408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545408")]
[Fact]
public void TestVarianceConversions()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
namespace TernaryAndVarianceConversion
{
delegate void CovariantDelegateWithVoidReturn<out T>();
delegate T CovariantDelegateWithValidReturn<out T>();
delegate void ContravariantDelegateVoidReturn<in T>();
delegate void ContravariantDelegateWithValidInParm<in T>(T inVal);
interface ICovariantInterface<out T>
{
void CovariantInterfaceMethodWithVoidReturn();
T CovariantInterfaceMethodWithValidReturn();
T CovariantInterfacePropertyWithValidGetter { get; }
void Test();
}
interface IContravariantInterface<in T>
{
void ContravariantInterfaceMethodWithVoidReturn();
void ContravariantInterfaceMethodWithValidInParm(T inVal);
T ContravariantInterfacePropertyWithValidSetter { set; }
void Test();
}
class CovariantInterfaceImpl<T> : ICovariantInterface<T>
{
public void CovariantInterfaceMethodWithVoidReturn() { }
public T CovariantInterfaceMethodWithValidReturn()
{
return default(T);
}
public T CovariantInterfacePropertyWithValidGetter
{
get { return default(T); }
}
public void Test()
{
Console.WriteLine(""{0}"", typeof(T));
}
}
class ContravariantInterfaceImpl<T> : IContravariantInterface<T>
{
public void ContravariantInterfaceMethodWithVoidReturn() { }
public void ContravariantInterfaceMethodWithValidInParm(T inVal) { }
public T ContravariantInterfacePropertyWithValidSetter
{
set { }
}
public void Test()
{
Console.WriteLine(""{0}"", typeof(T));
}
}
class Animal { }
class Mammal : Animal { }
class Program
{
static void Test(bool testFlag)
{
Console.WriteLine(""Testing with ternary test flag == {0}"", testFlag);
// Repro case for bug 7196
IEnumerable<object> EnumerableOfObject =
(testFlag ?
Enumerable.Repeat<string>(""string"", 1) :
Enumerable.Empty<object>());
Console.WriteLine(""{0}"", EnumerableOfObject.Count());
// Covariant implicit conversion for delegates
CovariantDelegateWithVoidReturn<Animal> covariantDelegateWithVoidReturnOfAnimal = () => { Console.WriteLine(""{0}"", typeof(Animal)); };
CovariantDelegateWithVoidReturn<Mammal> covariantDelegateWithVoidReturnOfMammal = () => { Console.WriteLine(""{0}"", typeof(Mammal)); };
CovariantDelegateWithVoidReturn<Animal> covariantDelegateWithVoidReturnOfAnimalTest;
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfMammal : covariantDelegateWithVoidReturnOfAnimal;
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfAnimal : covariantDelegateWithVoidReturnOfMammal;
covariantDelegateWithVoidReturnOfAnimalTest();
CovariantDelegateWithValidReturn<Animal> covariantDelegateWithValidReturnOfAnimal = () => { Console.WriteLine(""{0}"", typeof(Animal)); return default(Animal); };
CovariantDelegateWithValidReturn<Mammal> covariantDelegateWithValidReturnOfMammal = () => { Console.WriteLine(""{0}"", typeof(Mammal)); return default(Mammal); };
CovariantDelegateWithValidReturn<Animal> covariantDelegateWithValidReturnOfAnimalTest;
covariantDelegateWithValidReturnOfAnimalTest = testFlag ? covariantDelegateWithValidReturnOfMammal : covariantDelegateWithValidReturnOfAnimal;
covariantDelegateWithValidReturnOfAnimalTest();
covariantDelegateWithValidReturnOfAnimalTest = testFlag ? covariantDelegateWithValidReturnOfAnimal : covariantDelegateWithValidReturnOfMammal;
covariantDelegateWithValidReturnOfAnimalTest();
// Contravariant implicit conversion for delegates
ContravariantDelegateVoidReturn<Animal> contravariantDelegateVoidReturnOfAnimal = () => { Console.WriteLine(""{0}"", typeof(Animal)); };
ContravariantDelegateVoidReturn<Mammal> contravariantDelegateVoidReturnOfMammal = () => { Console.WriteLine(""{0}"", typeof(Mammal)); };
ContravariantDelegateVoidReturn<Mammal> contravariantDelegateVoidReturnOfMammalTest;
contravariantDelegateVoidReturnOfMammalTest = testFlag ? contravariantDelegateVoidReturnOfMammal : contravariantDelegateVoidReturnOfAnimal;
contravariantDelegateVoidReturnOfMammalTest();
contravariantDelegateVoidReturnOfMammalTest = testFlag ? contravariantDelegateVoidReturnOfAnimal : contravariantDelegateVoidReturnOfMammal;
contravariantDelegateVoidReturnOfMammalTest();
ContravariantDelegateWithValidInParm<Animal> contravariantDelegateWithValidInParmOfAnimal = (Animal) => { Console.WriteLine(""{0}"", typeof(Animal)); };
ContravariantDelegateWithValidInParm<Mammal> contravariantDelegateWithValidInParmOfMammal = (Mammal) => { Console.WriteLine(""{0}"", typeof(Mammal)); };
ContravariantDelegateWithValidInParm<Mammal> contravariantDelegateWithValidInParmOfMammalTest;
contravariantDelegateWithValidInParmOfMammalTest = testFlag ? contravariantDelegateWithValidInParmOfMammal : contravariantDelegateWithValidInParmOfAnimal;
contravariantDelegateWithValidInParmOfMammalTest(default(Mammal));
contravariantDelegateWithValidInParmOfMammalTest = testFlag ? contravariantDelegateWithValidInParmOfAnimal : contravariantDelegateWithValidInParmOfMammal;
contravariantDelegateWithValidInParmOfMammalTest(default(Mammal));
// Covariant implicit conversion for interfaces
ICovariantInterface<Animal> covariantInterfaceOfAnimal = new CovariantInterfaceImpl<Animal>();
ICovariantInterface<Mammal> covariantInterfaceOfMammal = new CovariantInterfaceImpl<Mammal>();
ICovariantInterface<Animal> covariantInterfaceOfAnimalTest;
covariantInterfaceOfAnimalTest = testFlag ? covariantInterfaceOfMammal : covariantInterfaceOfAnimal;
covariantInterfaceOfAnimalTest.Test();
covariantInterfaceOfAnimalTest = testFlag ? covariantInterfaceOfAnimal : covariantInterfaceOfMammal;
covariantInterfaceOfAnimalTest.Test();
// Contravariant implicit conversion for interfaces
IContravariantInterface<Animal> contravariantInterfaceOfAnimal = new ContravariantInterfaceImpl<Animal>();
IContravariantInterface<Mammal> contravariantInterfaceOfMammal = new ContravariantInterfaceImpl<Mammal>();
IContravariantInterface<Mammal> contravariantInterfaceOfMammalTest;
contravariantInterfaceOfMammalTest = testFlag ? contravariantInterfaceOfMammal : contravariantInterfaceOfAnimal;
contravariantInterfaceOfMammalTest.Test();
contravariantInterfaceOfMammalTest = testFlag ? contravariantInterfaceOfAnimal : contravariantInterfaceOfMammal;
contravariantInterfaceOfMammalTest.Test();
// With explicit casting
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? (CovariantDelegateWithVoidReturn<Animal>)covariantDelegateWithVoidReturnOfMammal : covariantDelegateWithVoidReturnOfAnimal;
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfAnimal : (CovariantDelegateWithVoidReturn<Animal>)covariantDelegateWithVoidReturnOfMammal;
covariantDelegateWithVoidReturnOfAnimalTest();
// With parens
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? (covariantDelegateWithVoidReturnOfMammal) : covariantDelegateWithVoidReturnOfAnimal;
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfAnimal : (covariantDelegateWithVoidReturnOfMammal);
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? ((CovariantDelegateWithVoidReturn<Animal>)covariantDelegateWithVoidReturnOfMammal) : covariantDelegateWithVoidReturnOfAnimal;
covariantDelegateWithVoidReturnOfAnimalTest();
covariantDelegateWithVoidReturnOfAnimalTest = testFlag ? covariantDelegateWithVoidReturnOfAnimal : ((CovariantDelegateWithVoidReturn<Animal>)covariantDelegateWithVoidReturnOfMammal);
covariantDelegateWithVoidReturnOfAnimalTest();
// Bug 291602
int[] intarr = { 1, 2, 3 };
IList<int> intlist = new List<int>(intarr);
IList<int> intternary = testFlag ? intarr : intlist;
Console.WriteLine(intternary);
}
static void Main(string[] args)
{
Test(true);
Test(false);
}
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: @"Testing with ternary test flag == True
1
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
System.Int32[]
Testing with ternary test flag == False
0
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
TernaryAndVarianceConversion.Animal
TernaryAndVarianceConversion.Mammal
System.Collections.Generic.List`1[System.Int32]
");
}
[WorkItem(528424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528424")]
[Fact()]
public void TestErrorOperand()
{
var source =
@"class C
{
static object M(bool b, C c, D d)
{
return b ? c : d;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,34): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D"));
}
private static void TestConditional(string conditionalExpression, string? expectedType, params DiagnosticDescription[] expectedDiagnostics)
{
TestConditional(conditionalExpression, expectedType, null, expectedDiagnostics);
}
private static void TestConditional(string conditionalExpression, string? expectedType, CSharpParseOptions? parseOptions, params DiagnosticDescription[] expectedDiagnostics)
{
if (parseOptions is null)
{
TestConditionalCore(conditionalExpression, expectedType, TestOptions.Regular8, expectedDiagnostics);
TestConditionalCore(conditionalExpression, expectedType, TestOptions.Regular8.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()), expectedDiagnostics);
}
else
{
TestConditionalCore(conditionalExpression, expectedType, parseOptions, expectedDiagnostics);
}
}
private static void TestConditionalCore(string conditionalExpression, string? expectedType, CSharpParseOptions parseOptions, params DiagnosticDescription[] expectedDiagnostics)
{
string source = $@"
class C
{{
void Test<T, U>()
{{
_ = {conditionalExpression};
}}
int GetInt() {{ return 1; }}
void GetVoid() {{ return ; }}
bool GetBool() {{ return true; }}
short GetShort() {{ return 1; }}
char GetChar() {{ return 'a'; }}
double GetDouble() {{ return 1.5; }}
string GetString() {{ return ""hello""; }}
object GetObject() {{ return new object(); }}
C GetUserNonGeneric() {{ return new C(); }}
D<T> GetUserGeneric<T>() {{ return new D<T>(); }}
T GetTypeParameter<T>() {{ return default(T); }}
I<T, U> GetVariantInterface<T, U>() {{ return null; }}
}}
class D<T> {{ }}
public enum color {{ Red, Blue, Green }};
interface I<in T, out U> {{ }}";
var tree = Parse(source, options: parseOptions);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics(expectedDiagnostics);
var compUnit = tree.GetCompilationUnitRoot();
var classC = (TypeDeclarationSyntax)compUnit.Members.First();
var methodTest = (MethodDeclarationSyntax)classC.Members.First();
var stmt = (ExpressionStatementSyntax)methodTest.Body!.Statements.First();
var assignment = (AssignmentExpressionSyntax)stmt.Expression;
var conditionalExpr = (ConditionalExpressionSyntax)assignment.Right;
var model = comp.GetSemanticModel(tree);
if (expectedType != null)
{
Assert.Equal(expectedType, model.GetTypeInfo(conditionalExpr).Type.ToTestDisplayString());
if (!expectedDiagnostics.Any())
{
Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(conditionalExpr.Condition).Type!.SpecialType);
Assert.Equal(expectedType, model.GetTypeInfo(conditionalExpr.WhenTrue).ConvertedType.ToTestDisplayString()); //in parent to catch conversion
Assert.Equal(expectedType, model.GetTypeInfo(conditionalExpr.WhenFalse).ConvertedType.ToTestDisplayString()); //in parent to catch conversion
}
}
}
[Fact, WorkItem(4028, "https://github.com/dotnet/roslyn/issues/4028")]
public void ConditionalAccessToEvent_01()
{
string source = @"
using System;
class TestClass
{
event Action test;
public static void Test(TestClass receiver)
{
Console.WriteLine(receiver?.test);
}
static void Main()
{
Console.WriteLine(""----"");
Test(null);
Console.WriteLine(""----"");
Test(new TestClass() {test = Main});
Console.WriteLine(""----"");
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput:
@"----
----
System.Action
----");
var tree = compilation.SyntaxTrees.Single();
var memberBinding = tree.GetRoot().DescendantNodes().OfType<MemberBindingExpressionSyntax>().Single();
var access = (ConditionalAccessExpressionSyntax)memberBinding.Parent!;
Assert.Equal(".test", memberBinding.ToString());
Assert.Equal("receiver?.test", access.ToString());
var model = compilation.GetSemanticModel(tree);
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding).Symbol.ToTestDisplayString());
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding.Name).Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(access).Symbol);
}
[Fact, WorkItem(4028, "https://github.com/dotnet/roslyn/issues/4028")]
public void ConditionalAccessToEvent_02()
{
string source = @"
using System;
class TestClass
{
event Action test;
public static void Test(TestClass receiver)
{
receiver?.test();
}
static void Main()
{
Console.WriteLine(""----"");
Test(null);
Console.WriteLine(""----"");
Test(new TestClass() {test = Target});
Console.WriteLine(""----"");
}
static void Target()
{
Console.WriteLine(""Target"");
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput:
@"----
----
Target
----");
var tree = compilation.SyntaxTrees.Single();
var memberBinding = tree.GetRoot().DescendantNodes().OfType<MemberBindingExpressionSyntax>().Single();
var invocation = (InvocationExpressionSyntax)memberBinding.Parent!;
var access = (ConditionalAccessExpressionSyntax)invocation.Parent!;
Assert.Equal(".test", memberBinding.ToString());
Assert.Equal(".test()", invocation.ToString());
Assert.Equal("receiver?.test()", access.ToString());
var model = compilation.GetSemanticModel(tree);
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding).Symbol.ToTestDisplayString());
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding.Name).Symbol.ToTestDisplayString());
Assert.Equal("void System.Action.Invoke()", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(access).Symbol);
}
[Fact, WorkItem(4028, "https://github.com/dotnet/roslyn/issues/4028")]
public void ConditionalAccessToEvent_03()
{
string source = @"
using System;
class TestClass
{
event Action test;
public static void Test(TestClass receiver)
{
receiver?.test += Main;
}
static void Main()
{
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// receiver?.test += Main;
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "receiver?.test").WithLocation(10, 9)
);
var tree = compilation.SyntaxTrees.Single();
var memberBinding = tree.GetRoot().DescendantNodes().OfType<MemberBindingExpressionSyntax>().Single();
var access = (ConditionalAccessExpressionSyntax)memberBinding.Parent!;
Assert.Equal(".test", memberBinding.ToString());
Assert.Equal("receiver?.test", access.ToString());
var model = compilation.GetSemanticModel(tree);
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding).Symbol.ToTestDisplayString());
Assert.Equal("event System.Action TestClass.test", model.GetSymbolInfo(memberBinding.Name).Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(access).Symbol);
}
[Fact(), WorkItem(4615, "https://github.com/dotnet/roslyn/issues/4615")]
public void ConditionalAndConditionalMethods()
{
string source = @"
class Program
{
static void Main(string[] args)
{
TestClass.Create().Test();
TestClass.Create().Self().Test();
System.Console.WriteLine(""---"");
TestClass.Create()?.Test();
TestClass.Create()?.Self().Test();
TestClass.Create()?.Self()?.Test();
}
}
class TestClass
{
[System.Diagnostics.Conditional(""DEBUG"")]
public void Test()
{
System.Console.WriteLine(""Test"");
}
public static TestClass Create()
{
System.Console.WriteLine(""Create"");
return new TestClass();
}
public TestClass Self()
{
System.Console.WriteLine(""Self"");
return this;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe,
parseOptions: CSharpParseOptions.Default.WithPreprocessorSymbols("DEBUG"));
CompileAndVerify(compilation, expectedOutput:
@"Create
Test
Create
Self
Test
---
Create
Test
Create
Self
Test
Create
Self
Test
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: "---");
}
[Fact, WorkItem(1198816, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1198816/")]
public void DefiniteAssignment_UnconvertedConditionalOperator()
{
var source =
@"class Program
{
static void Main()
{
_ = new(bad) ? null : new object();
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): error CS0103: The name 'bad' does not exist in the current context
// _ = new(bad) ? null : new object();
Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(5, 17)
);
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicArgumentProvider.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;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicArgumentProvider : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicArgumentProvider(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicArgumentProvider))
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.Workspace.SetArgumentCompletionSnippetsOption(true);
}
[WpfFact]
public void SimpleTabTabCompletion()
{
SetUpEditor(@"
Public Class Test
Private f As Object
Public Sub Method()$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompleteObjectEquals()
{
SetUpEditor(@"
Public Class Test
Public Sub Method()
$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys("Object.Equ");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Object.Equals$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Object.Equals(Nothing$$)", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompleteNewObject()
{
SetUpEditor(@"
Public Class Test
Public Sub Method()
Dim value = $$
End Sub
End Class
");
VisualStudio.Editor.SendKeys("New Obje");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object()$$", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompletionWithArguments()
{
SetUpEditor(@"
Imports System
Public Class Test
Private f As Integer
Public Sub Method(provider As IFormatProvider)$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(Nothing$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(Nothing$$, provider)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys("\"format\"");
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$, provider)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\", provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true);
}
[WpfFact]
public void FullCycle()
{
SetUpEditor(@"
Imports System
Public Class TestClass
Public Sub Method()$$
End Sub
Sub Test()
End Sub
Sub Test(x As Integer)
End Sub
Sub Test(x As Integer, y As Integer)
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("Tes");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Test$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
}
[WpfFact]
public void ImplicitArgumentSwitching()
{
SetUpEditor(@"
Imports System
Public Class TestClass
Public Sub Method()$$
End Sub
Sub Test()
End Sub
Sub Test(x As Integer)
End Sub
Sub Test(x As Integer, y As Integer)
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("Tes");
// Trigger the session and type '0' without waiting for the session to finish initializing
VisualStudio.Editor.SendKeys(VirtualKey.Tab, VirtualKey.Tab, '0');
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
}
[WpfFact]
public void SmartBreakLineWithTabTabCompletion()
{
SetUpEditor(@"
Public Class Test
Private f As Object
Public Sub Method()$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter));
VisualStudio.Editor.Verify.TextContains(@"
Public Class Test
Private f As Object
Public Sub Method()
f.ToString()
$$
End Sub
End Class
", assertCaretPosition: true);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicArgumentProvider : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicArgumentProvider(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicArgumentProvider))
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.Workspace.SetArgumentCompletionSnippetsOption(true);
}
[WpfFact]
public void SimpleTabTabCompletion()
{
SetUpEditor(@"
Public Class Test
Private f As Object
Public Sub Method()$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString()$$", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompleteObjectEquals()
{
SetUpEditor(@"
Public Class Test
Public Sub Method()
$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys("Object.Equ");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Object.Equals$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Object.Equals(Nothing$$)", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompleteNewObject()
{
SetUpEditor(@"
Public Class Test
Public Sub Method()
Dim value = $$
End Sub
End Class
");
VisualStudio.Editor.SendKeys("New Obje");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Dim value = New Object()$$", assertCaretPosition: true);
}
[WpfFact]
public void TabTabCompletionWithArguments()
{
SetUpEditor(@"
Imports System
Public Class Test
Private f As Integer
Public Sub Method(provider As IFormatProvider)$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(Nothing$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(Nothing$$, provider)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys("\"format\"");
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$, provider)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\", provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(provider$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString(\"format\"$$)", assertCaretPosition: true);
}
[WpfFact]
public void FullCycle()
{
SetUpEditor(@"
Imports System
Public Class TestClass
Public Sub Method()$$
End Sub
Sub Test()
End Sub
Sub Test(x As Integer)
End Sub
Sub Test(x As Integer, y As Integer)
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("Tes");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("Test$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
}
[WpfFact]
public void ImplicitArgumentSwitching()
{
SetUpEditor(@"
Imports System
Public Class TestClass
Public Sub Method()$$
End Sub
Sub Test()
End Sub
Sub Test(x As Integer)
End Sub
Sub Test(x As Integer, y As Integer)
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("Tes");
// Trigger the session and type '0' without waiting for the session to finish initializing
VisualStudio.Editor.SendKeys(VirtualKey.Tab, VirtualKey.Tab, '0');
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$, 0)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Up);
VisualStudio.Editor.Verify.CurrentLineText("Test(0$$)", assertCaretPosition: true);
}
[WpfFact]
public void SmartBreakLineWithTabTabCompletion()
{
SetUpEditor(@"
Public Class Test
Private f As Object
Public Sub Method()$$
End Sub
End Class
");
VisualStudio.Editor.SendKeys(VirtualKey.Enter);
VisualStudio.Editor.SendKeys("f.ToSt");
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString$$", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(VirtualKey.Tab);
VisualStudio.Workspace.WaitForAllAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SignatureHelp);
VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true);
VisualStudio.Editor.SendKeys(Shift(VirtualKey.Enter));
VisualStudio.Editor.Verify.TextContains(@"
Public Class Test
Private f As Object
Public Sub Method()
f.ToString()
$$
End Sub
End Class
", assertCaretPosition: true);
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Workspaces/Core/Portable/TodoComments/ITodoCommentsListener.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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.TodoComments
{
/// <summary>
/// Callback the host (VS) passes to the OOP service to allow it to send batch notifications about todo comments.
/// </summary>
internal interface ITodoCommentsListener
{
ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> data, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.TodoComments
{
/// <summary>
/// Callback the host (VS) passes to the OOP service to allow it to send batch notifications about todo comments.
/// </summary>
internal interface ITodoCommentsListener
{
ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> data, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpSignatureHelp.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;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpSignatureHelp : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpSignatureHelp(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpSignatureHelp))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void MethodSignatureHelp()
{
SetUpEditor(@"
using System;
class C
{
void M()
{
GenericMethod<string, int>(null, 1);
$$
}
C Method(int i) { return null; }
/// <summary>
/// Hello World 2.0!
/// </summary>
/// <param name=""i"">an integer, preferably 42.</param>
/// <param name=""i2"">an integer, anything you like.</param>
/// <returns>returns an object of type C</returns>
C Method(int i, int i2) { return null; }
/// <summary>
/// Hello Generic World!
/// </summary>
/// <typeparam name=""T1"">Type Param 1</typeparam>
/// <param name=""i"">Param 1 of type T1</param>
/// <returns>Null</returns>
C GenericMethod<T1>(T1 i) { return null; }
C GenericMethod<T1, T2>(T1 i, T2 i2) { return null; }
/// <summary>
/// Complex Method Params
/// </summary>
/// <param name=""strings"">Jagged MultiDimensional Array</param>
/// <param name=""outArr"">Out Array</param>
/// <param name=""d"">Dynamic and Params param</param>
/// <returns>Null</returns>
void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;}
}");
VisualStudio.SendKeys.Send("var m = Method(1,");
VisualStudio.Editor.InvokeSignatureHelp();
VisualStudio.Editor.Verify.CurrentSignature("C C.Method(int i, int i2)\r\nHello World 2.0!");
VisualStudio.Editor.Verify.CurrentParameter("i2", "an integer, anything you like.");
VisualStudio.Editor.Verify.Parameters(
("i", "an integer, preferably 42."),
("i2", "an integer, anything you like."));
VisualStudio.Editor.SendKeys(new object[] { VirtualKey.Home, new KeyPress(VirtualKey.End, ShiftState.Shift), VirtualKey.Delete });
VisualStudio.Editor.SendKeys("var op = OutAndParam(");
VisualStudio.Editor.Verify.CurrentSignature("void C.OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d)\r\nComplex Method Params");
VisualStudio.Editor.Verify.CurrentParameter("strings", "Jagged MultiDimensional Array");
VisualStudio.Editor.Verify.Parameters(
("strings", "Jagged MultiDimensional Array"),
("outArr", "Out Array"),
("d", "Dynamic and Params param"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericMethodSignatureHelp1()
{
SetUpEditor(@"
using System;
class C
{
void M()
{
GenericMethod<$$string, int>(null, 1);
}
C Method(int i) { return null; }
/// <summary>
/// Hello World 2.0!
/// </summary>
/// <param name=""i"">an integer, preferably 42.</param>
/// <param name=""i2"">an integer, anything you like.</param>
/// <returns>returns an object of type C</returns>
C Method(int i, int i2) { return null; }
/// <summary>
/// Hello Generic World!
/// </summary>
/// <typeparam name=""T1"">Type Param 1</typeparam>
/// <param name=""i"">Param 1 of type T1</param>
/// <returns>Null</returns>
C GenericMethod<T1>(T1 i) { return null; }
C GenericMethod<T1, T2>(T1 i, T2 i2) { return null; }
/// <summary>
/// Complex Method Params
/// </summary>
/// <param name=""strings"">Jagged MultiDimensional Array</param>
/// <param name=""outArr"">Out Array</param>
/// <param name=""d"">Dynamic and Params param</param>
/// <returns>Null</returns>
void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;}
}");
VisualStudio.Editor.InvokeSignatureHelp();
VisualStudio.Editor.Verify.CurrentSignature("C C.GenericMethod<T1, T2>(T1 i, T2 i2)");
VisualStudio.Editor.Verify.CurrentParameter("T1", "");
VisualStudio.Editor.Verify.Parameters(
("T1", ""),
("T2", ""));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericMethodSignatureHelp2()
{
SetUpEditor(@"
using System;
class C
{
void M()
{
GenericMethod<string, int>($$null, 1);
}
C Method(int i) { return null; }
/// <summary>
/// Hello World 2.0!
/// </summary>
/// <param name=""i"">an integer, preferably 42.</param>
/// <param name=""i2"">an integer, anything you like.</param>
/// <returns>returns an object of type C</returns>
C Method(int i, int i2) { return null; }
/// <summary>
/// Hello Generic World!
/// </summary>
/// <typeparam name=""T1"">Type Param 1</typeparam>
/// <param name=""i"">Param 1 of type T1</param>
/// <returns>Null</returns>
C GenericMethod<T1>(T1 i) { return null; }
C GenericMethod<T1, T2>(T1 i, T2 i2) { return null; }
/// <summary>
/// Complex Method Params
/// </summary>
/// <param name=""strings"">Jagged MultiDimensional Array</param>
/// <param name=""outArr"">Out Array</param>
/// <param name=""d"">Dynamic and Params param</param>
/// <returns>Null</returns>
void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;}
}");
VisualStudio.Editor.InvokeSignatureHelp();
VisualStudio.Editor.Verify.CurrentSignature("C C.GenericMethod<string, int>(string i, int i2)");
VisualStudio.Editor.Verify.CurrentParameter("i", "");
VisualStudio.Editor.Verify.Parameters(
("i", ""),
("i2", ""));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
[WorkItem(42484, "https://github.com/dotnet/roslyn/issues/42484")]
public void ExplicitSignatureHelpDismissesCompletion()
{
SetUpEditor(@"
class C
{
void M()
{
Test$$
}
void Test() { }
void Test(int x) { }
void Test(int x, int y) { }
void Test(int x, int y, int z) { }
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(true);
VisualStudio.Editor.SendKeys("(");
Assert.True(VisualStudio.Editor.IsCompletionActive());
Assert.True(VisualStudio.Editor.IsSignatureHelpActive());
VisualStudio.Editor.InvokeSignatureHelp();
Assert.False(VisualStudio.Editor.IsCompletionActive());
Assert.True(VisualStudio.Editor.IsSignatureHelpActive());
VisualStudio.Editor.Verify.CurrentSignature("void C.Test()");
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentSignature("void C.Test(int x)");
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpSignatureHelp : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpSignatureHelp(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpSignatureHelp))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void MethodSignatureHelp()
{
SetUpEditor(@"
using System;
class C
{
void M()
{
GenericMethod<string, int>(null, 1);
$$
}
C Method(int i) { return null; }
/// <summary>
/// Hello World 2.0!
/// </summary>
/// <param name=""i"">an integer, preferably 42.</param>
/// <param name=""i2"">an integer, anything you like.</param>
/// <returns>returns an object of type C</returns>
C Method(int i, int i2) { return null; }
/// <summary>
/// Hello Generic World!
/// </summary>
/// <typeparam name=""T1"">Type Param 1</typeparam>
/// <param name=""i"">Param 1 of type T1</param>
/// <returns>Null</returns>
C GenericMethod<T1>(T1 i) { return null; }
C GenericMethod<T1, T2>(T1 i, T2 i2) { return null; }
/// <summary>
/// Complex Method Params
/// </summary>
/// <param name=""strings"">Jagged MultiDimensional Array</param>
/// <param name=""outArr"">Out Array</param>
/// <param name=""d"">Dynamic and Params param</param>
/// <returns>Null</returns>
void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;}
}");
VisualStudio.SendKeys.Send("var m = Method(1,");
VisualStudio.Editor.InvokeSignatureHelp();
VisualStudio.Editor.Verify.CurrentSignature("C C.Method(int i, int i2)\r\nHello World 2.0!");
VisualStudio.Editor.Verify.CurrentParameter("i2", "an integer, anything you like.");
VisualStudio.Editor.Verify.Parameters(
("i", "an integer, preferably 42."),
("i2", "an integer, anything you like."));
VisualStudio.Editor.SendKeys(new object[] { VirtualKey.Home, new KeyPress(VirtualKey.End, ShiftState.Shift), VirtualKey.Delete });
VisualStudio.Editor.SendKeys("var op = OutAndParam(");
VisualStudio.Editor.Verify.CurrentSignature("void C.OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d)\r\nComplex Method Params");
VisualStudio.Editor.Verify.CurrentParameter("strings", "Jagged MultiDimensional Array");
VisualStudio.Editor.Verify.Parameters(
("strings", "Jagged MultiDimensional Array"),
("outArr", "Out Array"),
("d", "Dynamic and Params param"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericMethodSignatureHelp1()
{
SetUpEditor(@"
using System;
class C
{
void M()
{
GenericMethod<$$string, int>(null, 1);
}
C Method(int i) { return null; }
/// <summary>
/// Hello World 2.0!
/// </summary>
/// <param name=""i"">an integer, preferably 42.</param>
/// <param name=""i2"">an integer, anything you like.</param>
/// <returns>returns an object of type C</returns>
C Method(int i, int i2) { return null; }
/// <summary>
/// Hello Generic World!
/// </summary>
/// <typeparam name=""T1"">Type Param 1</typeparam>
/// <param name=""i"">Param 1 of type T1</param>
/// <returns>Null</returns>
C GenericMethod<T1>(T1 i) { return null; }
C GenericMethod<T1, T2>(T1 i, T2 i2) { return null; }
/// <summary>
/// Complex Method Params
/// </summary>
/// <param name=""strings"">Jagged MultiDimensional Array</param>
/// <param name=""outArr"">Out Array</param>
/// <param name=""d"">Dynamic and Params param</param>
/// <returns>Null</returns>
void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;}
}");
VisualStudio.Editor.InvokeSignatureHelp();
VisualStudio.Editor.Verify.CurrentSignature("C C.GenericMethod<T1, T2>(T1 i, T2 i2)");
VisualStudio.Editor.Verify.CurrentParameter("T1", "");
VisualStudio.Editor.Verify.Parameters(
("T1", ""),
("T2", ""));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericMethodSignatureHelp2()
{
SetUpEditor(@"
using System;
class C
{
void M()
{
GenericMethod<string, int>($$null, 1);
}
C Method(int i) { return null; }
/// <summary>
/// Hello World 2.0!
/// </summary>
/// <param name=""i"">an integer, preferably 42.</param>
/// <param name=""i2"">an integer, anything you like.</param>
/// <returns>returns an object of type C</returns>
C Method(int i, int i2) { return null; }
/// <summary>
/// Hello Generic World!
/// </summary>
/// <typeparam name=""T1"">Type Param 1</typeparam>
/// <param name=""i"">Param 1 of type T1</param>
/// <returns>Null</returns>
C GenericMethod<T1>(T1 i) { return null; }
C GenericMethod<T1, T2>(T1 i, T2 i2) { return null; }
/// <summary>
/// Complex Method Params
/// </summary>
/// <param name=""strings"">Jagged MultiDimensional Array</param>
/// <param name=""outArr"">Out Array</param>
/// <param name=""d"">Dynamic and Params param</param>
/// <returns>Null</returns>
void OutAndParam(ref string[][,] strings, out string[] outArr, params dynamic d) {outArr = null;}
}");
VisualStudio.Editor.InvokeSignatureHelp();
VisualStudio.Editor.Verify.CurrentSignature("C C.GenericMethod<string, int>(string i, int i2)");
VisualStudio.Editor.Verify.CurrentParameter("i", "");
VisualStudio.Editor.Verify.Parameters(
("i", ""),
("i2", ""));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
[WorkItem(42484, "https://github.com/dotnet/roslyn/issues/42484")]
public void ExplicitSignatureHelpDismissesCompletion()
{
SetUpEditor(@"
class C
{
void M()
{
Test$$
}
void Test() { }
void Test(int x) { }
void Test(int x, int y) { }
void Test(int x, int y, int z) { }
}");
VisualStudio.Workspace.SetTriggerCompletionInArgumentLists(true);
VisualStudio.Editor.SendKeys("(");
Assert.True(VisualStudio.Editor.IsCompletionActive());
Assert.True(VisualStudio.Editor.IsSignatureHelpActive());
VisualStudio.Editor.InvokeSignatureHelp();
Assert.False(VisualStudio.Editor.IsCompletionActive());
Assert.True(VisualStudio.Editor.IsSignatureHelpActive());
VisualStudio.Editor.Verify.CurrentSignature("void C.Test()");
VisualStudio.Editor.SendKeys(VirtualKey.Down);
VisualStudio.Editor.Verify.CurrentSignature("void C.Test(int x)");
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/VisualStudio/Core/Def/EditorConfigSettings/Common/SettingsEntriesSnapshotBase.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 Microsoft.VisualStudio.Shell.TableControl;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal abstract class SettingsEntriesSnapshotBase<T> : WpfTableEntriesSnapshotBase
{
private readonly ImmutableArray<T> _data;
private readonly int _currentVersionNumber;
public SettingsEntriesSnapshotBase(ImmutableArray<T> data, int currentVersionNumber)
{
_data = data;
_currentVersionNumber = currentVersionNumber;
}
public override int VersionNumber => _currentVersionNumber;
public override int Count => _data.Length;
public override bool TryGetValue(int index, string keyName, out object? content)
{
T? result;
try
{
if (index < 0 || index > _data.Length)
{
content = null;
return false;
}
result = _data[index];
if (result == null)
{
content = null;
return false;
}
}
catch (Exception)
{
content = null;
return false;
}
return TryGetValue(result, keyName, out content);
}
protected abstract bool TryGetValue(T result, string keyName, out object? content);
}
}
| // Licensed to the .NET Foundation under one or more 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 Microsoft.VisualStudio.Shell.TableControl;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal abstract class SettingsEntriesSnapshotBase<T> : WpfTableEntriesSnapshotBase
{
private readonly ImmutableArray<T> _data;
private readonly int _currentVersionNumber;
public SettingsEntriesSnapshotBase(ImmutableArray<T> data, int currentVersionNumber)
{
_data = data;
_currentVersionNumber = currentVersionNumber;
}
public override int VersionNumber => _currentVersionNumber;
public override int Count => _data.Length;
public override bool TryGetValue(int index, string keyName, out object? content)
{
T? result;
try
{
if (index < 0 || index > _data.Length)
{
content = null;
return false;
}
result = _data[index];
if (result == null)
{
content = null;
return false;
}
}
catch (Exception)
{
content = null;
return false;
}
return TryGetValue(result, keyName, out content);
}
protected abstract bool TryGetValue(T result, string keyName, out object? content);
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ImmutableArrayExtensions.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;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class ImmutableArrayExtensions
{
internal static int IndexOf<TItem, TArg>(this ImmutableArray<TItem> array, Func<TItem, TArg, bool> predicate, TArg arg)
{
for (int i = 0; i < array.Length; i++)
{
if (predicate(array[i], arg))
{
return i;
}
}
return -1;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class ImmutableArrayExtensions
{
internal static int IndexOf<TItem, TArg>(this ImmutableArray<TItem> array, Func<TItem, TArg, bool> predicate, TArg arg)
{
for (int i = 0; i < array.Length; i++)
{
if (predicate(array[i], arg))
{
return i;
}
}
return -1;
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/Test/Core/Diagnostics/SuppressMessageAttributeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics
{
public abstract partial class SuppressMessageAttributeTests
{
#region Local Suppression
public static IEnumerable<string[]> QualifiedAttributeNames { get; } = new[] {
new[] { "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute" },
new[] { "System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute" },
};
public static IEnumerable<string[]> SimpleAttributeNames { get; } = new[] {
new[] { "SuppressMessage" },
new[] { "UnconditionalSuppressMessage" }
};
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task LocalSuppressionOnType(string attrName)
{
await VerifyCSharpAsync(@"
[" + attrName + @"(""Test"", ""Declaration"")]
public class C
{
}
public class C1
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C1"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MultipleLocalSuppressionsOnSingleSymbol(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"")]
[" + attrName + @"(""Test"", ""TypeDeclaration"")]
public class C
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C"), new WarningOnTypeDeclarationAnalyzer() });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task DuplicateLocalSuppressions(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"")]
[" + attrName + @"(""Test"", ""Declaration"")]
public class C
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task LocalSuppressionOnMember(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
public void Goo() {}
public void Goo1() {}
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("Goo") },
Diagnostic("Declaration", "Goo1"));
}
#endregion
#region Global Suppression
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNamespaces(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N.N1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N4"")]
namespace N
{
namespace N1
{
namespace N2.N3
{
}
}
}
namespace N4
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N2"),
Diagnostic("Declaration", "N3"));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNamespaces_NamespaceAndDescendants(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""namespaceanddescendants"", Target=""N4"")]
namespace N
{
namespace N1
{
namespace N2.N3
{
}
}
}
namespace N4
{
namespace N5
{
}
}
namespace N.N1.N6.N7
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N"));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnTypesAndNamespaces_NamespaceAndDescendants(string attrName)
{
var source = @"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1.N2"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N4"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C2"")]
namespace N
{
namespace N1
{
class C1
{
}
namespace N2.N3
{
class C2
{
}
class C3
{
class C4
{
}
}
}
}
}
namespace N4
{
namespace N5
{
class C5
{
}
}
class C6
{
}
}
namespace N.N1.N2.N7
{
class C7
{
}
}
";
await VerifyCSharpAsync(source,
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N"),
Diagnostic("Declaration", "N1"));
await VerifyCSharpAsync(source,
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C1"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnTypes(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ef"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Egg"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ele`2"")]
public class E
{
}
public interface Ef
{
}
public struct Egg
{
}
public delegate void Ele<T1,T2>(T1 x, T2 y);
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNestedTypes(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C.A1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C+A2"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C+A3"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C.A4"")]
public class C
{
public class A1 { }
public class A2 { }
public class A3 { }
public delegate void A4();
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("A") },
Diagnostic("Declaration", "A1"),
Diagnostic("Declaration", "A3"),
Diagnostic("Declaration", "A4"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GlobalSuppressionOnBasicModule(string attrName)
{
await VerifyBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""M"")>
Module M
Class C
End Class
End Module
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnMembers(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M3`1()"")]
public class C
{
int M1;
public void M2() {}
public static void M3<T>() {}
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") },
new[] { Diagnostic("Declaration", "M2") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnValueTupleMemberWithDocId(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""~M:C.M~System.Threading.Tasks.Task{System.ValueTuple{System.Boolean,ErrorCode}}"")]
enum ErrorCode {}
class C
{
Task<(bool status, ErrorCode errorCode)> M() => null;
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MultipleGlobalSuppressionsOnSingleSymbol(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[assembly: " + attrName + @"(""Test"", ""TypeDeclaration"", Scope=""Type"", Target=""E"")]
public class E
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("E"), new WarningOnTypeDeclarationAnalyzer() });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task DuplicateGlobalSuppressions(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
public class E
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") });
}
#endregion
#region Syntax Semantics
[Fact]
public async Task WarningOnCommentAnalyzerCSharp()
{
await VerifyCSharpAsync("// Comment\r\n /* Comment */",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// Comment"),
Diagnostic("Comment", "/* Comment */"));
}
[Fact]
public async Task WarningOnCommentAnalyzerBasic()
{
await VerifyBasicAsync("' Comment",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "' Comment"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"")]
// before class
public class C
{
// before method
public void Goo() // after method declaration
{
// inside method
}
}
// after class
",
new[] { new WarningOnCommentAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsBasic(string attrName)
{
await VerifyBasicAsync(@"
' before module attributes
<Module: " + attrName + @"(""Test"", ""Comment"")>
' before class
Public Class C
' before sub
Public Sub Goo() ' after sub statement
' inside sub
End Sub
End Class
' after class
",
new[] { new WarningOnCommentAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsOnTargetCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""C.Goo():System.Void"")]
// before class
public class C
{
// before method
public void Goo() // after method declaration
{
// inside method
}
}
// after class
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// before module attributes"),
Diagnostic("Comment", "// before class"),
Diagnostic("Comment", "// after class"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsOnTargetBasic(string attrName)
{
await VerifyBasicAsync(@"
' before module attributes
<Module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Member"", Target:=""C.Goo():System.Void"")>
' before class
Public Class C
' before sub
Public Sub Goo() ' after sub statement
' inside sub
End Sub
End Class
' after class
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "' before module attributes"),
Diagnostic("Comment", "' before class"),
Diagnostic("Comment", "' after class"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
[assembly: " + attrName + @"(""Test"", ""Token"", Scope=""namespace"", Target=""A.B"")]
namespace A
[|{
namespace B
{
class C {}
}
}|]
",
Diagnostic("Token", "{").WithLocation(4, 1),
Diagnostic("Token", "class").WithLocation(7, 9),
Diagnostic("Token", "C").WithLocation(7, 15),
Diagnostic("Token", "{").WithLocation(7, 17),
Diagnostic("Token", "}").WithLocation(7, 18),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceAndChildDeclarationCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
[assembly: " + attrName + @"(""Test"", ""Token"", Scope=""NamespaceAndDescendants"", Target=""A.B"")]
namespace A
[|{
namespace B
{
class C {}
}
}|]
",
Diagnostic("Token", "{").WithLocation(4, 1),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""Namespace"", Target:=""A.B"")>
Namespace [|A
Namespace B
Class C
End Class
End Namespace
End|] Namespace
",
Diagnostic("Token", "A").WithLocation(3, 11),
Diagnostic("Token", "Class").WithLocation(5, 9),
Diagnostic("Token", "C").WithLocation(5, 15),
Diagnostic("Token", "End").WithLocation(6, 9),
Diagnostic("Token", "Class").WithLocation(6, 13),
Diagnostic("Token", "End").WithLocation(8, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceAndDescendantsDeclarationBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""NamespaceAndDescendants"", Target:=""A.B"")>
Namespace [|A
Namespace B
Class C
End Class
End Namespace
End|] Namespace
",
Diagnostic("Token", "A").WithLocation(3, 11),
Diagnostic("Token", "End").WithLocation(8, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[InlineData("Namespace")]
[InlineData("NamespaceAndDescendants")]
public async Task DontSuppressSyntaxDiagnosticsInRootNamespaceBasic(string scope)
{
await VerifyBasicAsync($@"
<module: System.Diagnostics.SuppressMessage(""Test"", ""Comment"", Scope:=""{scope}"", Target:=""RootNamespace"")>
' In root namespace
",
rootNamespace: "RootNamespace",
analyzers: new[] { new WarningOnCommentAnalyzer() },
diagnostics: Diagnostic("Comment", "' In root namespace").WithLocation(3, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnTypesCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
namespace N
[|{
[" + attrName + @"(""Test"", ""Token"")]
class C<T> {}
[" + attrName + @"(""Test"", ""Token"")]
struct S<T> {}
[" + attrName + @"(""Test"", ""Token"")]
interface I<T>{}
[" + attrName + @"(""Test"", ""Token"")]
enum E {}
[" + attrName + @"(""Test"", ""Token"")]
delegate void D();
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(20, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnTypesBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Namespace [|N
<" + attrName + @"(""Test"", ""Token"")>
Module M
End Module
<" + attrName + @"(""Test"", ""Token"")>
Class C
End Class
<" + attrName + @"(""Test"", ""Token"")>
Structure S
End Structure
<" + attrName + @"(""Test"", ""Token"")>
Interface I
End Interface
<" + attrName + @"(""Test"", ""Token"")>
Enum E
None
End Enum
<" + attrName + @"(""Test"", ""Token"")>
Delegate Sub D()
End|] Namespace
",
Diagnostic("Token", "N").WithLocation(4, 11),
Diagnostic("Token", "End").WithLocation(28, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnFieldsCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
int field1 = 1, field2 = 2;
[" + attrName + @"(""Test"", ""Token"")]
int field3 = 3;
}|]
",
Diagnostic("Token", "{"),
Diagnostic("Token", "}"));
}
[Theory]
[WorkItem(6379, "https://github.com/dotnet/roslyn/issues/6379")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEnumFieldsCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""E.Field1"")]
// before enum
public enum E
{
// before Field1 declaration
Field1, // after Field1 declaration
Field2 // after Field2 declaration
}
// after enum
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// before module attributes"),
Diagnostic("Comment", "// before enum"),
Diagnostic("Comment", "// after Field1 declaration"),
Diagnostic("Comment", "// after Field2 declaration"),
Diagnostic("Comment", "// after enum"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnFieldsBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public field1 As Integer = 1,
field2 As Double = 2.0
<" + attrName + @"(""Test"", ""Token"")>
Public field3 As Integer = 3
End|] Class
",
Diagnostic("Token", "C"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventsCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public event System.Action<int> E1;
[" + attrName + @"(""Test"", ""Token"")]
public event System.Action<int> E2, E3;
}|]
",
Diagnostic("Token", "{"),
Diagnostic("Token", "}"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventsBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Event E1 As System.Action(Of Integer)
<" + attrName + @"(""Test"", ""Token"")>
Public Event E2(ByVal arg As Integer)
End|] Class
",
Diagnostic("Token", "C"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
public event System.Action<int> E
[|{
[" + attrName + @"(""Test"", ""Token"")]
add {}
remove|] {}
}
}
",
Diagnostic("Token", "{").WithLocation(5, 5),
Diagnostic("Token", "remove").WithLocation(8, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer[|)
<" + attrName + @"(""Test"", ""Token"")>
AddHandler(value As Action(Of Integer))
End AddHandler
RemoveHandler|](value As Action(Of Integer))
End RemoveHandler
RaiseEvent(obj As Integer)
End RaiseEvent
End Event
End Class
",
Diagnostic("Token", ")"),
Diagnostic("Token", "RemoveHandler"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
public event System.Action<int> E
{
add {[|}
[" + attrName + @"(""Test"", ""Token"")]
remove {}
}|]
}
",
Diagnostic("Token", "}").WithLocation(6, 14),
Diagnostic("Token", "}").WithLocation(9, 5));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer)
AddHandler(value As Action(Of Integer))
End [|AddHandler
<" + attrName + @"(""Test"", ""Token"")>
RemoveHandler(value As Action(Of Integer))
End RemoveHandler
RaiseEvent|](obj As Integer)
End RaiseEvent
End Event
End Class
",
Diagnostic("Token", "AddHandler"),
Diagnostic("Token", "RaiseEvent"));
}
[WorkItem(1103442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103442")]
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnRaiseEventAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer)
AddHandler(value As Action(Of Integer))
End AddHandler
RemoveHandler(value As Action(Of Integer))
End [|RemoveHandler
<" + attrName + @"(""Test"", ""Token"")>
RaiseEvent(obj As Integer)
End RaiseEvent
End|] Event
End Class
",
Diagnostic("Token", "RemoveHandler"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
int Property1 { get; set; }
[" + attrName + @"(""Test"", ""Token"")]
int Property2
{
get { return 2; }
set { Property1 = 2; }
}
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(15, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Property Property1 As Integer
<" + attrName + @"(""Test"", ""Token"")>
Property Property2 As Integer
Get
Return 2
End Get
Set(value As Integer)
Property1 = value
End Set
End Property
End|] Class
",
Diagnostic("Token", "C").WithLocation(4, 7),
Diagnostic("Token", "End").WithLocation(17, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyGetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int Property
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyGetterBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Private x As Integer
Property [Property] As [|Integer
<" + attrName + @"(""Test"", ""Token"")>
Get
Return 2
End Get
Set|](value As Integer)
x = value
End Set
End Property
End Class
",
Diagnostic("Token", "Integer").WithLocation(4, 28),
Diagnostic("Token", "Set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertySetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int Property
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertySetterBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Private x As Integer
Property [Property] As Integer
Get
Return 2
End [|Get
<" + attrName + @"(""Test"", ""Token"")>
Set(value As Integer)
x = value
End Set
End|] Property
End Class
",
Diagnostic("Token", "Get").WithLocation(7, 13),
Diagnostic("Token", "End").WithLocation(12, 5));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x[|;
[" + attrName + @"(""Test"", ""Token"")]
int this[int i]
{
get { return 2; }
set { x = 2; }
}
}|]
",
Diagnostic("Token", ";").WithLocation(4, 10),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerGetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int this[int i]
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerSetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int this[int i]
{
get { return 2; [|}
[" + attrName + @"(""Test"", ""Token"")]
set { x = 2; }
}|]
}
",
Diagnostic("Token", "}").WithLocation(7, 25),
Diagnostic("Token", "}").WithLocation(10, 5));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnMethodCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
abstract class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public void M1<T>() {}
[" + attrName + @"(""Test"", ""Token"")]
public abstract void M2();
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnMethodBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Public MustInherit Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Function M2(Of T)() As Integer
Return 0
End Function
<" + attrName + @"(""Test"", ""Token"")>
Public MustOverride Sub M3()
End|] Class
",
Diagnostic("Token", "C").WithLocation(4, 26),
Diagnostic("Token", "End").WithLocation(12, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnOperatorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public static C operator +(C a, C b)
{
return null;
}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnOperatorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Shared Operator +(ByVal a As C, ByVal b As C) As C
Return Nothing
End Operator
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(7, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnConstructorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class Base
{
public Base(int x) {}
}
class C : Base
[|{
[" + attrName + @"(""Test"", ""Token"")]
public C() : base(0) {}
}|]
",
Diagnostic("Token", "{").WithLocation(8, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnConstructorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Sub New()
End Sub
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(6, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnDestructorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
~C() {}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(6, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNestedTypeCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
class D
{
class E
{
}
}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNestedTypeBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Class D
Class E
End Class
End Class
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(8, 1));
}
#endregion
#region Special Cases
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageCompilationEnded(string attrName)
{
await VerifyCSharpAsync(
@"[module: " + attrName + @"(""Test"", ""CompilationEnded"")]",
new[] { new WarningOnCompilationEndedAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnPropertyAccessor(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
public string P { get; private set; }
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("get_") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnDelegateInvoke(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
delegate void D();
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("Invoke") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnCodeBodyCSharp(string attrName)
{
await VerifyCSharpAsync(
@"
public class C
{
[" + attrName + @"(""Test"", ""CodeBody"")]
void Goo()
{
Goo();
}
}
",
new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.CSharp) });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnCodeBodyBasic(string attrName)
{
await VerifyBasicAsync(
@"
Public Class C
<" + attrName + @"(""Test"", ""CodeBody"")>
Sub Goo()
Goo()
End Sub
End Class
",
new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.VisualBasic) });
}
#endregion
#region Attribute Decoding
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task UnnecessaryScopeAndTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")]
public class C1
{
}
[" + attrName + @"(""Test"", ""Declaration"", Target=""C"")]
public class C2
{
}
[" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C"")]
public class C3
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task InvalidScopeOrTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""C"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""E"")]
public class C
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MissingScopeOrTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[module: " + attrName + @"(""Test"", ""Declaration"", Target=""C"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")]
public class C
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task InvalidAttributeConstructorParameters(string attrName)
{
await VerifyBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
<module: " + attrName + @"UndeclaredIdentifier, ""Comment"")>
<module: " + attrName + @"(""Test"", UndeclaredIdentifier)>
<module: " + attrName + @"(""Test"", ""Comment"", Scope:=UndeclaredIdentifier, Target:=""C"")>
<module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Type"", Target:=UndeclaredIdentifier)>
Class C
End Class
",
new[] { new WarningOnTypeDeclarationAnalyzer() },
Diagnostic("TypeDeclaration", "C").WithLocation(9, 7));
}
#endregion
protected async Task VerifyCSharpAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
await VerifyAsync(source, LanguageNames.CSharp, analyzers, diagnostics);
}
protected Task VerifyTokenDiagnosticsCSharpAsync(string markup, params DiagnosticDescription[] diagnostics)
{
return VerifyTokenDiagnosticsAsync(markup, LanguageNames.CSharp, diagnostics);
}
protected async Task VerifyBasicAsync(string source, string rootNamespace, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
Assert.False(string.IsNullOrWhiteSpace(rootNamespace), string.Format("Invalid root namespace '{0}'", rootNamespace));
await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics, rootNamespace: rootNamespace);
}
protected async Task VerifyBasicAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics);
}
protected Task VerifyTokenDiagnosticsBasicAsync(string markup, params DiagnosticDescription[] diagnostics)
{
return VerifyTokenDiagnosticsAsync(markup, LanguageNames.VisualBasic, diagnostics);
}
protected abstract Task VerifyAsync(string source, string language, DiagnosticAnalyzer[] analyzers, DiagnosticDescription[] diagnostics, string rootNamespace = null);
// Generate a diagnostic on every token in the specified spans, and verify that only the specified diagnostics are not suppressed
private Task VerifyTokenDiagnosticsAsync(string markup, string language, DiagnosticDescription[] diagnostics)
{
MarkupTestFile.GetSpans(markup, out var source, out ImmutableArray<TextSpan> spans);
Assert.True(spans.Length > 0, "Must specify a span within which to generate diagnostics on each token");
return VerifyAsync(source, language, new DiagnosticAnalyzer[] { new WarningOnTokenAnalyzer(spans) }, diagnostics);
}
protected abstract bool ConsiderArgumentsForComparingDiagnostics { get; }
protected DiagnosticDescription Diagnostic(string id, string squiggledText)
{
var arguments = this.ConsiderArgumentsForComparingDiagnostics && squiggledText != null
? new[] { squiggledText }
: null;
return new DiagnosticDescription(id, false, squiggledText, arguments, null, null, false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics
{
public abstract partial class SuppressMessageAttributeTests
{
#region Local Suppression
public static IEnumerable<string[]> QualifiedAttributeNames { get; } = new[] {
new[] { "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute" },
new[] { "System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute" },
};
public static IEnumerable<string[]> SimpleAttributeNames { get; } = new[] {
new[] { "SuppressMessage" },
new[] { "UnconditionalSuppressMessage" }
};
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task LocalSuppressionOnType(string attrName)
{
await VerifyCSharpAsync(@"
[" + attrName + @"(""Test"", ""Declaration"")]
public class C
{
}
public class C1
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C1"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MultipleLocalSuppressionsOnSingleSymbol(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"")]
[" + attrName + @"(""Test"", ""TypeDeclaration"")]
public class C
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C"), new WarningOnTypeDeclarationAnalyzer() });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task DuplicateLocalSuppressions(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"")]
[" + attrName + @"(""Test"", ""Declaration"")]
public class C
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task LocalSuppressionOnMember(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
public void Goo() {}
public void Goo1() {}
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("Goo") },
Diagnostic("Declaration", "Goo1"));
}
#endregion
#region Global Suppression
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNamespaces(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N.N1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N4"")]
namespace N
{
namespace N1
{
namespace N2.N3
{
}
}
}
namespace N4
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N2"),
Diagnostic("Declaration", "N3"));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNamespaces_NamespaceAndDescendants(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""namespaceanddescendants"", Target=""N4"")]
namespace N
{
namespace N1
{
namespace N2.N3
{
}
}
}
namespace N4
{
namespace N5
{
}
}
namespace N.N1.N6.N7
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N"));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnTypesAndNamespaces_NamespaceAndDescendants(string attrName)
{
var source = @"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1.N2"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N4"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C2"")]
namespace N
{
namespace N1
{
class C1
{
}
namespace N2.N3
{
class C2
{
}
class C3
{
class C4
{
}
}
}
}
}
namespace N4
{
namespace N5
{
class C5
{
}
}
class C6
{
}
}
namespace N.N1.N2.N7
{
class C7
{
}
}
";
await VerifyCSharpAsync(source,
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N"),
Diagnostic("Declaration", "N1"));
await VerifyCSharpAsync(source,
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C1"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnTypes(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ef"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Egg"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ele`2"")]
public class E
{
}
public interface Ef
{
}
public struct Egg
{
}
public delegate void Ele<T1,T2>(T1 x, T2 y);
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNestedTypes(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C.A1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C+A2"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C+A3"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C.A4"")]
public class C
{
public class A1 { }
public class A2 { }
public class A3 { }
public delegate void A4();
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("A") },
Diagnostic("Declaration", "A1"),
Diagnostic("Declaration", "A3"),
Diagnostic("Declaration", "A4"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GlobalSuppressionOnBasicModule(string attrName)
{
await VerifyBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""M"")>
Module M
Class C
End Class
End Module
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnMembers(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M3`1()"")]
public class C
{
int M1;
public void M2() {}
public static void M3<T>() {}
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") },
new[] { Diagnostic("Declaration", "M2") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnValueTupleMemberWithDocId(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""~M:C.M~System.Threading.Tasks.Task{System.ValueTuple{System.Boolean,ErrorCode}}"")]
enum ErrorCode {}
class C
{
Task<(bool status, ErrorCode errorCode)> M() => null;
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MultipleGlobalSuppressionsOnSingleSymbol(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[assembly: " + attrName + @"(""Test"", ""TypeDeclaration"", Scope=""Type"", Target=""E"")]
public class E
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("E"), new WarningOnTypeDeclarationAnalyzer() });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task DuplicateGlobalSuppressions(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
public class E
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") });
}
#endregion
#region Syntax Semantics
[Fact]
public async Task WarningOnCommentAnalyzerCSharp()
{
await VerifyCSharpAsync("// Comment\r\n /* Comment */",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// Comment"),
Diagnostic("Comment", "/* Comment */"));
}
[Fact]
public async Task WarningOnCommentAnalyzerBasic()
{
await VerifyBasicAsync("' Comment",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "' Comment"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"")]
// before class
public class C
{
// before method
public void Goo() // after method declaration
{
// inside method
}
}
// after class
",
new[] { new WarningOnCommentAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsBasic(string attrName)
{
await VerifyBasicAsync(@"
' before module attributes
<Module: " + attrName + @"(""Test"", ""Comment"")>
' before class
Public Class C
' before sub
Public Sub Goo() ' after sub statement
' inside sub
End Sub
End Class
' after class
",
new[] { new WarningOnCommentAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsOnTargetCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""C.Goo():System.Void"")]
// before class
public class C
{
// before method
public void Goo() // after method declaration
{
// inside method
}
}
// after class
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// before module attributes"),
Diagnostic("Comment", "// before class"),
Diagnostic("Comment", "// after class"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsOnTargetBasic(string attrName)
{
await VerifyBasicAsync(@"
' before module attributes
<Module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Member"", Target:=""C.Goo():System.Void"")>
' before class
Public Class C
' before sub
Public Sub Goo() ' after sub statement
' inside sub
End Sub
End Class
' after class
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "' before module attributes"),
Diagnostic("Comment", "' before class"),
Diagnostic("Comment", "' after class"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
[assembly: " + attrName + @"(""Test"", ""Token"", Scope=""namespace"", Target=""A.B"")]
namespace A
[|{
namespace B
{
class C {}
}
}|]
",
Diagnostic("Token", "{").WithLocation(4, 1),
Diagnostic("Token", "class").WithLocation(7, 9),
Diagnostic("Token", "C").WithLocation(7, 15),
Diagnostic("Token", "{").WithLocation(7, 17),
Diagnostic("Token", "}").WithLocation(7, 18),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceAndChildDeclarationCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
[assembly: " + attrName + @"(""Test"", ""Token"", Scope=""NamespaceAndDescendants"", Target=""A.B"")]
namespace A
[|{
namespace B
{
class C {}
}
}|]
",
Diagnostic("Token", "{").WithLocation(4, 1),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""Namespace"", Target:=""A.B"")>
Namespace [|A
Namespace B
Class C
End Class
End Namespace
End|] Namespace
",
Diagnostic("Token", "A").WithLocation(3, 11),
Diagnostic("Token", "Class").WithLocation(5, 9),
Diagnostic("Token", "C").WithLocation(5, 15),
Diagnostic("Token", "End").WithLocation(6, 9),
Diagnostic("Token", "Class").WithLocation(6, 13),
Diagnostic("Token", "End").WithLocation(8, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceAndDescendantsDeclarationBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""NamespaceAndDescendants"", Target:=""A.B"")>
Namespace [|A
Namespace B
Class C
End Class
End Namespace
End|] Namespace
",
Diagnostic("Token", "A").WithLocation(3, 11),
Diagnostic("Token", "End").WithLocation(8, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[InlineData("Namespace")]
[InlineData("NamespaceAndDescendants")]
public async Task DontSuppressSyntaxDiagnosticsInRootNamespaceBasic(string scope)
{
await VerifyBasicAsync($@"
<module: System.Diagnostics.SuppressMessage(""Test"", ""Comment"", Scope:=""{scope}"", Target:=""RootNamespace"")>
' In root namespace
",
rootNamespace: "RootNamespace",
analyzers: new[] { new WarningOnCommentAnalyzer() },
diagnostics: Diagnostic("Comment", "' In root namespace").WithLocation(3, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnTypesCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
namespace N
[|{
[" + attrName + @"(""Test"", ""Token"")]
class C<T> {}
[" + attrName + @"(""Test"", ""Token"")]
struct S<T> {}
[" + attrName + @"(""Test"", ""Token"")]
interface I<T>{}
[" + attrName + @"(""Test"", ""Token"")]
enum E {}
[" + attrName + @"(""Test"", ""Token"")]
delegate void D();
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(20, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnTypesBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Namespace [|N
<" + attrName + @"(""Test"", ""Token"")>
Module M
End Module
<" + attrName + @"(""Test"", ""Token"")>
Class C
End Class
<" + attrName + @"(""Test"", ""Token"")>
Structure S
End Structure
<" + attrName + @"(""Test"", ""Token"")>
Interface I
End Interface
<" + attrName + @"(""Test"", ""Token"")>
Enum E
None
End Enum
<" + attrName + @"(""Test"", ""Token"")>
Delegate Sub D()
End|] Namespace
",
Diagnostic("Token", "N").WithLocation(4, 11),
Diagnostic("Token", "End").WithLocation(28, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnFieldsCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
int field1 = 1, field2 = 2;
[" + attrName + @"(""Test"", ""Token"")]
int field3 = 3;
}|]
",
Diagnostic("Token", "{"),
Diagnostic("Token", "}"));
}
[Theory]
[WorkItem(6379, "https://github.com/dotnet/roslyn/issues/6379")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEnumFieldsCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""E.Field1"")]
// before enum
public enum E
{
// before Field1 declaration
Field1, // after Field1 declaration
Field2 // after Field2 declaration
}
// after enum
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// before module attributes"),
Diagnostic("Comment", "// before enum"),
Diagnostic("Comment", "// after Field1 declaration"),
Diagnostic("Comment", "// after Field2 declaration"),
Diagnostic("Comment", "// after enum"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnFieldsBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public field1 As Integer = 1,
field2 As Double = 2.0
<" + attrName + @"(""Test"", ""Token"")>
Public field3 As Integer = 3
End|] Class
",
Diagnostic("Token", "C"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventsCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public event System.Action<int> E1;
[" + attrName + @"(""Test"", ""Token"")]
public event System.Action<int> E2, E3;
}|]
",
Diagnostic("Token", "{"),
Diagnostic("Token", "}"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventsBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Event E1 As System.Action(Of Integer)
<" + attrName + @"(""Test"", ""Token"")>
Public Event E2(ByVal arg As Integer)
End|] Class
",
Diagnostic("Token", "C"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
public event System.Action<int> E
[|{
[" + attrName + @"(""Test"", ""Token"")]
add {}
remove|] {}
}
}
",
Diagnostic("Token", "{").WithLocation(5, 5),
Diagnostic("Token", "remove").WithLocation(8, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer[|)
<" + attrName + @"(""Test"", ""Token"")>
AddHandler(value As Action(Of Integer))
End AddHandler
RemoveHandler|](value As Action(Of Integer))
End RemoveHandler
RaiseEvent(obj As Integer)
End RaiseEvent
End Event
End Class
",
Diagnostic("Token", ")"),
Diagnostic("Token", "RemoveHandler"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
public event System.Action<int> E
{
add {[|}
[" + attrName + @"(""Test"", ""Token"")]
remove {}
}|]
}
",
Diagnostic("Token", "}").WithLocation(6, 14),
Diagnostic("Token", "}").WithLocation(9, 5));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer)
AddHandler(value As Action(Of Integer))
End [|AddHandler
<" + attrName + @"(""Test"", ""Token"")>
RemoveHandler(value As Action(Of Integer))
End RemoveHandler
RaiseEvent|](obj As Integer)
End RaiseEvent
End Event
End Class
",
Diagnostic("Token", "AddHandler"),
Diagnostic("Token", "RaiseEvent"));
}
[WorkItem(1103442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103442")]
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnRaiseEventAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer)
AddHandler(value As Action(Of Integer))
End AddHandler
RemoveHandler(value As Action(Of Integer))
End [|RemoveHandler
<" + attrName + @"(""Test"", ""Token"")>
RaiseEvent(obj As Integer)
End RaiseEvent
End|] Event
End Class
",
Diagnostic("Token", "RemoveHandler"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
int Property1 { get; set; }
[" + attrName + @"(""Test"", ""Token"")]
int Property2
{
get { return 2; }
set { Property1 = 2; }
}
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(15, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Property Property1 As Integer
<" + attrName + @"(""Test"", ""Token"")>
Property Property2 As Integer
Get
Return 2
End Get
Set(value As Integer)
Property1 = value
End Set
End Property
End|] Class
",
Diagnostic("Token", "C").WithLocation(4, 7),
Diagnostic("Token", "End").WithLocation(17, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyGetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int Property
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyGetterBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Private x As Integer
Property [Property] As [|Integer
<" + attrName + @"(""Test"", ""Token"")>
Get
Return 2
End Get
Set|](value As Integer)
x = value
End Set
End Property
End Class
",
Diagnostic("Token", "Integer").WithLocation(4, 28),
Diagnostic("Token", "Set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertySetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int Property
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertySetterBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Private x As Integer
Property [Property] As Integer
Get
Return 2
End [|Get
<" + attrName + @"(""Test"", ""Token"")>
Set(value As Integer)
x = value
End Set
End|] Property
End Class
",
Diagnostic("Token", "Get").WithLocation(7, 13),
Diagnostic("Token", "End").WithLocation(12, 5));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x[|;
[" + attrName + @"(""Test"", ""Token"")]
int this[int i]
{
get { return 2; }
set { x = 2; }
}
}|]
",
Diagnostic("Token", ";").WithLocation(4, 10),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerGetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int this[int i]
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerSetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int this[int i]
{
get { return 2; [|}
[" + attrName + @"(""Test"", ""Token"")]
set { x = 2; }
}|]
}
",
Diagnostic("Token", "}").WithLocation(7, 25),
Diagnostic("Token", "}").WithLocation(10, 5));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnMethodCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
abstract class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public void M1<T>() {}
[" + attrName + @"(""Test"", ""Token"")]
public abstract void M2();
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnMethodBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Public MustInherit Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Function M2(Of T)() As Integer
Return 0
End Function
<" + attrName + @"(""Test"", ""Token"")>
Public MustOverride Sub M3()
End|] Class
",
Diagnostic("Token", "C").WithLocation(4, 26),
Diagnostic("Token", "End").WithLocation(12, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnOperatorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public static C operator +(C a, C b)
{
return null;
}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnOperatorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Shared Operator +(ByVal a As C, ByVal b As C) As C
Return Nothing
End Operator
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(7, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnConstructorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class Base
{
public Base(int x) {}
}
class C : Base
[|{
[" + attrName + @"(""Test"", ""Token"")]
public C() : base(0) {}
}|]
",
Diagnostic("Token", "{").WithLocation(8, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnConstructorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Sub New()
End Sub
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(6, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnDestructorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
~C() {}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(6, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNestedTypeCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
class D
{
class E
{
}
}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNestedTypeBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Class D
Class E
End Class
End Class
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(8, 1));
}
#endregion
#region Special Cases
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageCompilationEnded(string attrName)
{
await VerifyCSharpAsync(
@"[module: " + attrName + @"(""Test"", ""CompilationEnded"")]",
new[] { new WarningOnCompilationEndedAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnPropertyAccessor(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
public string P { get; private set; }
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("get_") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnDelegateInvoke(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
delegate void D();
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("Invoke") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnCodeBodyCSharp(string attrName)
{
await VerifyCSharpAsync(
@"
public class C
{
[" + attrName + @"(""Test"", ""CodeBody"")]
void Goo()
{
Goo();
}
}
",
new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.CSharp) });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnCodeBodyBasic(string attrName)
{
await VerifyBasicAsync(
@"
Public Class C
<" + attrName + @"(""Test"", ""CodeBody"")>
Sub Goo()
Goo()
End Sub
End Class
",
new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.VisualBasic) });
}
#endregion
#region Attribute Decoding
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task UnnecessaryScopeAndTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")]
public class C1
{
}
[" + attrName + @"(""Test"", ""Declaration"", Target=""C"")]
public class C2
{
}
[" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C"")]
public class C3
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task InvalidScopeOrTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""C"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""E"")]
public class C
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MissingScopeOrTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[module: " + attrName + @"(""Test"", ""Declaration"", Target=""C"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")]
public class C
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task InvalidAttributeConstructorParameters(string attrName)
{
await VerifyBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
<module: " + attrName + @"UndeclaredIdentifier, ""Comment"")>
<module: " + attrName + @"(""Test"", UndeclaredIdentifier)>
<module: " + attrName + @"(""Test"", ""Comment"", Scope:=UndeclaredIdentifier, Target:=""C"")>
<module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Type"", Target:=UndeclaredIdentifier)>
Class C
End Class
",
new[] { new WarningOnTypeDeclarationAnalyzer() },
Diagnostic("TypeDeclaration", "C").WithLocation(9, 7));
}
#endregion
protected async Task VerifyCSharpAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
await VerifyAsync(source, LanguageNames.CSharp, analyzers, diagnostics);
}
protected Task VerifyTokenDiagnosticsCSharpAsync(string markup, params DiagnosticDescription[] diagnostics)
{
return VerifyTokenDiagnosticsAsync(markup, LanguageNames.CSharp, diagnostics);
}
protected async Task VerifyBasicAsync(string source, string rootNamespace, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
Assert.False(string.IsNullOrWhiteSpace(rootNamespace), string.Format("Invalid root namespace '{0}'", rootNamespace));
await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics, rootNamespace: rootNamespace);
}
protected async Task VerifyBasicAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics);
}
protected Task VerifyTokenDiagnosticsBasicAsync(string markup, params DiagnosticDescription[] diagnostics)
{
return VerifyTokenDiagnosticsAsync(markup, LanguageNames.VisualBasic, diagnostics);
}
protected abstract Task VerifyAsync(string source, string language, DiagnosticAnalyzer[] analyzers, DiagnosticDescription[] diagnostics, string rootNamespace = null);
// Generate a diagnostic on every token in the specified spans, and verify that only the specified diagnostics are not suppressed
private Task VerifyTokenDiagnosticsAsync(string markup, string language, DiagnosticDescription[] diagnostics)
{
MarkupTestFile.GetSpans(markup, out var source, out ImmutableArray<TextSpan> spans);
Assert.True(spans.Length > 0, "Must specify a span within which to generate diagnostics on each token");
return VerifyAsync(source, language, new DiagnosticAnalyzer[] { new WarningOnTokenAnalyzer(spans) }, diagnostics);
}
protected abstract bool ConsiderArgumentsForComparingDiagnostics { get; }
protected DiagnosticDescription Diagnostic(string id, string squiggledText)
{
var arguments = this.ConsiderArgumentsForComparingDiagnostics && squiggledText != null
? new[] { squiggledText }
: null;
return new DiagnosticDescription(id, false, squiggledText, arguments, null, null, false);
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Interactive/HostTest/InteractiveHostDesktopTests.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.
extern alias InteractiveHost;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
[Trait(Traits.Feature, Traits.Features.InteractiveHost)]
public sealed class InteractiveHostDesktopTests : AbstractInteractiveHostTests
{
internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop64;
internal override bool UseDefaultInitializationFile => false;
[Fact]
public async Task OutputRedirection()
{
await Execute(@"
System.Console.WriteLine(""hello-\u4567!"");
System.Console.Error.WriteLine(""error-\u7890!"");
1+1");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("hello-\u4567!\r\n2\r\n", output);
Assert.Equal("error-\u7890!\r\n", error);
}
[Fact]
public async Task OutputRedirection2()
{
await Execute(@"System.Console.WriteLine(1);");
await Execute(@"System.Console.Error.WriteLine(2);");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("1\r\n", output);
Assert.Equal("2\r\n", error);
RedirectOutput();
await Execute(@"System.Console.WriteLine(3);");
await Execute(@"System.Console.Error.WriteLine(4);");
output = await ReadOutputToEnd();
error = await ReadErrorOutputToEnd();
Assert.Equal("3\r\n", output);
Assert.Equal("4\r\n", error);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/46414")]
public async Task StackOverflow()
{
var process = Host.TryGetProcess();
await Execute(@"
int goo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9)
{
return goo(0,1,2,3,4,5,6,7,8,9) + goo(0,1,2,3,4,5,6,7,8,9);
}
goo(0,1,2,3,4,5,6,7,8,9)
");
var output = await ReadOutputToEnd();
Assert.Equal("", output);
// Hosting process exited with exit code ###.
var errorOutput = (await ReadErrorOutputToEnd()).Trim();
AssertEx.AssertEqualToleratingWhitespaceDifferences(
"Process is terminated due to StackOverflowException.\n" + string.Format(InteractiveHostResources.Hosting_process_exited_with_exit_code_0, process!.ExitCode), errorOutput);
await Execute(@"1+1");
output = await ReadOutputToEnd();
Assert.Equal("2\r\n", output.ToString());
}
private const string MethodWithInfiniteLoop = @"
void goo()
{
int i = 0;
while (true)
{
if (i < 10)
{
i = i + 1;
}
else if (i == 10)
{
System.Console.Error.WriteLine(""in the loop"");
i = i + 1;
}
}
}
";
[Fact]
public async Task AsyncExecute_InfiniteLoop()
{
var mayTerminate = new ManualResetEvent(false);
Host.ErrorOutputReceived += (_, __) => mayTerminate.Set();
await Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()");
Assert.True(mayTerminate.WaitOne());
await RestartHost();
await Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()");
var execution = await Execute(@"1+1");
var output = await ReadOutputToEnd();
Assert.True(execution);
Assert.Equal("2\r\n", output);
}
[Fact(Skip = "529027")]
public async Task AsyncExecute_HangingForegroundThreads()
{
var mayTerminate = new ManualResetEvent(false);
Host.OutputReceived += (_, __) =>
{
mayTerminate.Set();
};
var executeTask = Host.ExecuteAsync(@"
using System.Threading;
int i1 = 0;
Thread t1 = new Thread(() => { while(true) { i1++; } });
t1.Name = ""TestThread-1"";
t1.IsBackground = false;
t1.Start();
int i2 = 0;
Thread t2 = new Thread(() => { while(true) { i2++; } });
t2.Name = ""TestThread-2"";
t2.IsBackground = true;
t2.Start();
Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite));
t3.Name = ""TestThread-3"";
t3.Start();
while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { }
System.Console.WriteLine(""terminate!"");
while(true) {}
");
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error);
Assert.True(mayTerminate.WaitOne());
// TODO: var service = _host.TryGetService();
// Assert.NotNull(service);
var process = Host.TryGetProcess();
Assert.NotNull(process);
// service!.EmulateClientExit();
// the process should terminate with exit code 0:
process!.WaitForExit();
Assert.Equal(0, process.ExitCode);
}
[Fact]
public async Task AsyncExecuteFile_InfiniteLoop()
{
var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path;
var mayTerminate = new ManualResetEvent(false);
Host.ErrorOutputReceived += (_, __) => mayTerminate.Set();
await Host.ExecuteFileAsync(file);
mayTerminate.WaitOne();
await RestartHost();
var execution = await Execute(@"1+1");
var output = await ReadOutputToEnd();
Assert.True(execution);
Assert.Equal("2\r\n", output);
}
[Fact]
public async Task AsyncExecuteFile_SourceKind()
{
var file = Temp.CreateFile().WriteAllText("1 1").Path;
var task = await Host.ExecuteFileAsync(file);
Assert.False(task.Success);
var errorOut = (await ReadErrorOutputToEnd()).Trim();
Assert.True(errorOut.StartsWith(file + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column");
Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002");
}
[Fact]
public async Task AsyncExecuteFile_NonExistingFile()
{
var result = await Host.ExecuteFileAsync("non existing file");
Assert.False(result.Success);
var errorOut = (await ReadErrorOutputToEnd()).Trim();
Assert.Contains(InteractiveHostResources.Specified_file_not_found, errorOut, StringComparison.Ordinal);
Assert.Contains(InteractiveHostResources.Searched_in_directory_colon, errorOut, StringComparison.Ordinal);
}
[Fact]
public async Task AsyncExecuteFile()
{
var file = Temp.CreateFile().WriteAllText(@"
using static System.Console;
public class C
{
public int field = 4;
public int Goo(int i) { return i; }
}
public int Goo(int i) { return i; }
WriteLine(5);
").Path;
var task = await Host.ExecuteFileAsync(file);
var output = await ReadOutputToEnd();
Assert.True(task.Success);
Assert.Equal("5", output.Trim());
await Execute("Goo(2)");
output = await ReadOutputToEnd();
Assert.Equal("2", output.Trim());
await Execute("new C().Goo(3)");
output = await ReadOutputToEnd();
Assert.Equal("3", output.Trim());
await Execute("new C().field");
output = await ReadOutputToEnd();
Assert.Equal("4", output.Trim());
}
[Fact]
public async Task AsyncExecuteFile_InvalidFileContent()
{
await Host.ExecuteFileAsync(typeof(Process).Assembly.Location);
var errorOut = (await ReadErrorOutputToEnd()).Trim();
Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column");
Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056");
Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002");
}
[Fact]
public async Task AsyncExecuteFile_ScriptFileWithBuildErrors()
{
var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}");
await Host.ExecuteFileAsync(file.Path);
var errorOut = (await ReadErrorOutputToEnd()).Trim();
Assert.True(errorOut.StartsWith(file.Path + "(1,7):", StringComparison.Ordinal), "Error output should start with file name, line and column");
Assert.True(errorOut.Contains("CS7010"), "Error output should include error CS7010");
}
/// <summary>
/// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be
/// even invoked since we resolve the assembly via Fusion.
/// </summary>
[Fact(Skip = "987032")]
public async Task UserDefinedAssemblyResolve_InfiniteLoop()
{
var mayTerminate = new ManualResetEvent(false);
Host.ErrorOutputReceived += (_, __) => mayTerminate.Set();
// TODO: _host.TryGetService()!.HookMaliciousAssemblyResolve();
Assert.True(mayTerminate.WaitOne());
await Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid());
Assert.True(await Execute(@"1+1"));
var output = await ReadOutputToEnd();
Assert.Equal("2\r\n", output);
}
[Fact]
public async Task AddReference_Path()
{
var fxDir = await GetHostRuntimeDirectoryAsync();
Assert.False(await Execute("new System.Data.DataSet()"));
Assert.True(await LoadReference(Path.Combine(fxDir, "System.Data.dll")));
Assert.True(await Execute("new System.Data.DataSet()"));
}
[Fact]
public async Task AddReference_PartialName()
{
Assert.False(await Execute("new System.Data.DataSet()"));
Assert.True(await LoadReference("System.Data"));
Assert.True(await Execute("new System.Data.DataSet()"));
}
[Fact]
public async Task AddReference_PartialName_LatestVersion()
{
// there might be two versions of System.Data - v2 and v4, we should get the latter:
Assert.True(await LoadReference("System.Data"));
Assert.True(await LoadReference("System"));
Assert.True(await LoadReference("System.Xml"));
await Execute(@"new System.Data.DataSet().GetType().Assembly.GetName().Version");
var output = await ReadOutputToEnd();
Assert.Equal("[4.0.0.0]\r\n", output);
}
[Fact]
public async Task AddReference_FullName()
{
Assert.False(await Execute("new System.Data.DataSet()"));
Assert.True(await LoadReference("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
Assert.True(await Execute("new System.Data.DataSet()"));
}
[ConditionalFact(typeof(Framework35Installed), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/5167")]
public async Task AddReference_VersionUnification1()
{
// V3.5 unifies with the current Framework version:
var result = await LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("", output.Trim());
Assert.True(result);
result = await LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
output = await ReadOutputToEnd();
error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("", output.Trim());
Assert.True(result);
result = await LoadReference("System.Core");
output = await ReadOutputToEnd();
error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("", output.Trim());
Assert.True(result);
}
// Caused by submission not inheriting references.
[Fact(Skip = "101161")]
public async Task AddReference_ShadowCopy()
{
var dir = Temp.CreateDirectory();
// create C.dll
var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }");
// load C.dll:
var output = await ReadOutputToEnd();
Assert.True(await LoadReference(c.Path));
Assert.True(await Execute("new C()"));
Assert.Equal("C { }", output.Trim());
// rewrite C.dll:
File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 });
// we can still run code:
var result = await Execute("new C()");
output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("C { }", output.Trim());
Assert.True(result);
}
#if TODO
/// <summary>
/// Tests that a dependency is correctly resolved and loaded at runtime.
/// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded.
/// </summary>
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")]
public void AddReference_Dependencies()
{
var dir = Temp.CreateDirectory();
var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }");
var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image));
var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image));
AssemblyLoadResult result;
result = LoadReference(a.Path);
Assert.Equal(a.Path, result.OriginalPath);
Assert.True(IsShadowCopy(result.Path));
Assert.True(result.IsSuccessful);
Assert.True(Execute("A.CallB()"));
// c.dll is loaded as a dependency, so #r should be successful:
result = LoadReference(c.Path);
Assert.Equal(c.Path, result.OriginalPath);
Assert.True(IsShadowCopy(result.Path));
Assert.True(result.IsSuccessful);
// c.dll was already loaded explicitly via #r so we should fail now:
result = LoadReference(c.Path);
Assert.False(result.IsSuccessful);
Assert.Equal(c.Path, result.OriginalPath);
Assert.True(IsShadowCopy(result.Path));
Assert.Equal("", ReadErrorOutputToEnd().Trim());
Assert.Equal("1", ReadOutputToEnd().Trim());
}
#endif
/// <summary>
/// When two files of the same version are in the same directory, prefer .dll over .exe.
/// </summary>
[Fact]
public async Task AddReference_Dependencies_DllExe()
{
var dir = Temp.CreateDirectory();
var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }");
var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }");
var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }",
MetadataReference.CreateFromImage(dll.Image));
Assert.True(await LoadReference(main.Path));
Assert.True(await Execute("Program.Main()"));
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("1", output.Trim());
}
[Fact]
public async Task AddReference_Dependencies_Versions()
{
var dir1 = Temp.CreateDirectory();
var dir2 = Temp.CreateDirectory();
var dir3 = Temp.CreateDirectory();
// [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }");
var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1);
// [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }");
var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2);
Assert.True(await LoadReference(file1.Path));
Assert.True(await LoadReference(file2.Path));
var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }",
MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull()));
Assert.True(await LoadReference(main.Path));
Assert.True(await Execute("Program.Main()"));
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("2", output.Trim());
}
[Fact]
public async Task AddReference_AlreadyLoadedDependencies()
{
var dir = Temp.CreateDirectory();
var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }");
var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }",
MetadataReference.CreateFromFile(lib1.Path));
await Execute("#r \"" + lib1.Path + "\"");
await Execute("#r \"" + lib2.Path + "\"");
await Execute("new C().M()");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences("1", output);
}
[Fact(Skip = "101161")]
public async Task AddReference_LoadUpdatedReference()
{
var dir = Temp.CreateDirectory();
var source1 = "public class C { public int X = 1; }";
var c1 = CreateCompilation(source1, assemblyName: "C");
var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray());
// use:
await Execute($@"
#r ""{file.Path}""
C goo() => new C();
new C().X
");
// update:
var source2 = "public class D { public int Y = 2; }";
var c2 = CreateCompilation(source2, assemblyName: "C");
file.WriteAllBytes(c2.EmitToArray());
// add the reference again:
await Execute($@"
#r ""{file.Path}""
new D().Y
");
// TODO: We should report an error that assembly named 'a' was already loaded with different content.
// In future we can let it load and improve error reporting around type conversions.
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal(@"1
2", output.Trim());
}
[Fact(Skip = "129388")]
public async Task AddReference_MultipleReferencesWithSameWeakIdentity()
{
var dir = Temp.CreateDirectory();
var dir1 = dir.CreateDirectory("1");
var dir2 = dir.CreateDirectory("2");
var source1 = "public class C1 { }";
var c1 = CreateCompilation(source1, assemblyName: "C");
var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray());
var source2 = "public class C2 { }";
var c2 = CreateCompilation(source2, assemblyName: "C");
var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray());
await Execute($@"
#r ""{file1.Path}""
#r ""{file2.Path}""
");
await Execute("new C1()");
await Execute("new C2()");
// TODO: We should report an error that assembly named 'c' was already loaded with different content.
// In future we can let it load and let the compiler report the error CS1704: "An assembly with the same simple name 'C' has already been imported".
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal(@"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side.
(1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?)
(1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", error.Trim());
Assert.Equal("", output.Trim());
}
[Fact(Skip = "129388")]
public async Task AddReference_MultipleReferencesWeakVersioning()
{
var dir = Temp.CreateDirectory();
var dir1 = dir.CreateDirectory("1");
var dir2 = dir.CreateDirectory("2");
var source1 = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C1 { }";
var c1 = CreateCompilation(source1, assemblyName: "C");
var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray());
var source2 = @"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C2 { }";
var c2 = CreateCompilation(source2, assemblyName: "C");
var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray());
await Execute($@"
#r ""{file1.Path}""
#r ""{file2.Path}""
");
await Execute("new C1()");
await Execute("new C2()");
// TODO: We should report an error that assembly named 'c' was already loaded with different content.
// In future we can let it load and improve error reporting around type conversions.
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("TODO: error", error.Trim());
Assert.Equal("", output.Trim());
}
//// TODO (987032):
//// [Fact]
//// public void AsyncInitializeContextWithDotNETLibraries()
//// {
//// var rspFile = Temp.CreateFile();
//// var rspDisplay = Path.GetFileName(rspFile.Path);
//// var initScript = Temp.CreateFile();
//// rspFile.WriteAllText(@"
/////r:System.Core
////""" + initScript.Path + @"""
////");
//// initScript.WriteAllText(@"
////using static System.Console;
////using System.Linq.Expressions;
////WriteLine(Expression.Constant(123));
////");
//// // override default "is restarting" behavior (the REPL is already initialized):
//// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true);
//// task.Wait();
//// var output = SplitLines(ReadOutputToEnd());
//// var errorOutput = ReadErrorOutputToEnd();
//// Assert.Equal(4, output.Length);
//// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]);
//// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]);
//// Assert.Equal("Type \"#help\" for more information.", output[2]);
//// Assert.Equal("123", output[3]);
//// Assert.Equal("", errorOutput);
//// Host.InitializeContextAsync(rspFile.Path).Wait();
//// output = SplitLines(ReadOutputToEnd());
//// errorOutput = ReadErrorOutputToEnd();
//// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines.");
//// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]);
//// Assert.Equal("123", output[1]);
//// Assert.Equal("", errorOutput);
//// }
//// [Fact]
//// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries()
//// {
//// var dir = Temp.CreateDirectory();
//// var rspFile = Temp.CreateFile();
//// var initScript = Temp.CreateFile();
//// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }");
//// rspFile.WriteAllText(@"
/////r:System.Numerics
/////r:" + dll.Path + @"
////""" + initScript.Path + @"""
////");
//// initScript.WriteAllText(@"
////using static System.Console;
////using System.Numerics;
////WriteLine(new Complex(12, 6).Real + C.Main());
////");
//// // override default "is restarting" behavior (the REPL is already initialized):
//// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true);
//// task.Wait();
//// var errorOutput = ReadErrorOutputToEnd();
//// Assert.Equal("", errorOutput);
//// var output = SplitLines(ReadOutputToEnd());
//// Assert.Equal(4, output.Length);
//// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]);
//// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]);
//// Assert.Equal("Type \"#help\" for more information.", output[2]);
//// Assert.Equal("13", output[3]);
//// }
[Fact]
public async Task ReferencePathsRsp()
{
var directory1 = Temp.CreateDirectory();
CompileLibrary(directory1, "Assembly0.dll", "Assembly0", @"public class C0 { }");
CompileLibrary(directory1, "Assembly1.dll", "Assembly1", @"public class C1 { }");
var initDirectory = Temp.CreateDirectory();
var initFile = initDirectory.CreateFile("init.csx");
initFile.WriteAllText(@"
#r ""Assembly0.dll""
System.Console.WriteLine(typeof(C0).Assembly.GetName());
System.Console.WriteLine(typeof(C2).Assembly.GetName());
Print(ReferencePaths);
");
var rspDirectory = Temp.CreateDirectory();
CompileLibrary(rspDirectory, "Assembly2.dll", "Assembly2", @"public class C2 { }");
CompileLibrary(rspDirectory, "Assembly3.dll", "Assembly3", @"public class C3 { }");
var rspFile = rspDirectory.CreateFile("init.rsp");
rspFile.WriteAllText($"/lib:{directory1.Path} /r:Assembly2.dll {initFile.Path}");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, culture: CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
var fxDir = await GetHostRuntimeDirectoryAsync();
await Execute(@"
#r ""Assembly1.dll""
System.Console.WriteLine(typeof(C1).Assembly.GetName());
Print(ReferencePaths);
");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
var expectedSearchPaths = PrintSearchPaths(fxDir, directory1.Path);
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences($@"
{string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path))}
Assembly0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
Assembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
{expectedSearchPaths}
Assembly1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
{expectedSearchPaths}
", output);
}
[Fact]
public async Task ReferencePathsRsp_Error()
{
var initDirectory = Temp.CreateDirectory();
var initFile = initDirectory.CreateFile("init.csx");
initFile.WriteAllText(@"#r ""Assembly.dll""");
var rspDirectory = Temp.CreateDirectory();
CompileLibrary(rspDirectory, "Assembly.dll", "Assembly", "public class C { }");
var rspFile = rspDirectory.CreateFile("init.rsp");
rspFile.WriteAllText($"{initFile.Path}");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, culture: CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(
@$"{initFile.Path}(1,1): error CS0006: {string.Format(CSharpResources.ERR_NoMetadataFile, "Assembly.dll")}", error);
}
[Fact]
public async Task DefaultUsings()
{
var rspFile = Temp.CreateFile();
rspFile.WriteAllText(@"
/r:System
/r:System.Core
/r:Microsoft.CSharp
/u:System
/u:System.IO
/u:System.Collections.Generic
/u:System.Diagnostics
/u:System.Dynamic
/u:System.Linq
/u:System.Linq.Expressions
/u:System.Text
/u:System.Threading.Tasks
");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
await Execute(@"
dynamic d = new ExpandoObject();
");
await Execute(@"
Process p = new Process();
");
await Execute(@"
Expression<Func<int>> e = () => 1;
");
await Execute(@"
var squares = from x in new[] { 1, 2, 3 } select x * x;
");
await Execute(@"
var sb = new StringBuilder();
");
await Execute(@"
var list = new List<int>();
");
await Execute(@"
var stream = new MemoryStream();
await Task.Delay(10);
p = new Process();
Console.Write(""OK"")
");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences(
$@"{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) }
OK
", output);
}
[Fact]
public async Task InitialScript_Error()
{
var initFile = Temp.CreateFile(extension: ".csx").WriteAllText("1 1");
var rspFile = Temp.CreateFile();
rspFile.WriteAllText($@"
/r:System
/u:System.Diagnostics
{initFile.Path}
");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
await Execute("new Process()");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences($@"{initFile.Path}(1,3): error CS1002: { CSharpResources.ERR_SemicolonExpected }
", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences($@"
{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) }
[System.Diagnostics.Process]
", output);
}
[Fact]
public async Task ScriptAndArguments()
{
var scriptFile = Temp.CreateFile(extension: ".csx").WriteAllText("foreach (var arg in Args) Print(arg);");
var rspFile = Temp.CreateFile();
rspFile.WriteAllText($@"
{scriptFile}
a
b
c
");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences(
$@"{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) }
""a""
""b""
""c""
", await ReadOutputToEnd());
}
[Fact]
public async Task Script_NoHostNamespaces()
{
await Execute("nameof(Microsoft.Missing)");
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences($@"(1,8): error CS0234: { string.Format(CSharpResources.ERR_DottedTypeNameNotFoundInNS, "Missing", "Microsoft") }",
error);
var output = await ReadOutputToEnd();
Assert.Equal("", output);
}
[Fact]
public async Task ExecutesOnStaThread()
{
await Execute(@"
#r ""System""
#r ""System.Xaml""
#r ""WindowsBase""
#r ""PresentationCore""
#r ""PresentationFramework""
new System.Windows.Window();
System.Console.WriteLine(""OK"");
");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
Assert.Equal("", error);
Assert.Equal("OK\r\n", output);
}
/// <summary>
/// Execution of expressions should be
/// sequential, even await expressions.
/// </summary>
[Fact]
public async Task ExecuteSequentially()
{
await Execute(@"using System;
using System.Threading.Tasks;");
await Execute(@"await Task.Delay(1000).ContinueWith(t => 1)");
await Execute(@"await Task.Delay(500).ContinueWith(t => 2)");
await Execute(@"3");
var output = await ReadOutputToEnd();
Assert.Equal("1\r\n2\r\n3\r\n", output);
}
[Fact]
public async Task MultiModuleAssembly()
{
var dir = Temp.CreateDirectory();
var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll);
dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2);
dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3);
await Execute(@"
#r """ + dll.Path + @"""
new object[] { new Class1(), new Class2(), new Class3() }
");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
Assert.Equal("", error);
Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output);
}
[Fact, WorkItem(6457, "https://github.com/dotnet/roslyn/issues/6457")]
public async Task MissingReferencesReuse()
{
var source = @"
public class C
{
public System.Diagnostics.Process P;
}
";
var lib = CSharpCompilation.Create(
"Lib",
new[] { SyntaxFactory.ParseSyntaxTree(source) },
new[] { Net451.mscorlib, Net451.System },
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var libFile = Temp.CreateFile("lib").WriteAllBytes(lib.EmitToArray());
await Execute($@"#r ""{libFile.Path}""");
await Execute("C c;");
await Execute("c = new C()");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
Assert.Equal("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences("C { P=null }", output);
}
[Fact, WorkItem(7280, "https://github.com/dotnet/roslyn/issues/7280")]
public async Task AsyncContinueOnDifferentThread()
{
await Execute(@"
using System;
using System.Threading;
using System.Threading.Tasks;
Console.Write(Task.Run(() => { Thread.CurrentThread.Join(100); return 42; }).ContinueWith(t => t.Result).Result)");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("42", output);
Assert.Empty(error);
}
[Fact]
public async Task Exception()
{
await Execute(@"throw new System.Exception();");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", output);
Assert.DoesNotContain("Unexpected", error, StringComparison.OrdinalIgnoreCase);
Assert.True(error.StartsWith($"{new Exception().GetType()}: {new Exception().Message}"));
}
[Fact, WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")]
public async Task PreservingDeclarationsOnException()
{
await Execute(@"int i = 100;");
await Execute(@"int j = 20; throw new System.Exception(""Bang!""); int k = 3;");
await Execute(@"i + j + k");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("120", output);
AssertEx.AssertEqualToleratingWhitespaceDifferences("System.Exception: Bang!", error);
}
[Fact]
public async Task Bitness()
{
await Host.ExecuteAsync(@"System.IntPtr.Size");
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("8\r\n", await ReadOutputToEnd());
await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop32));
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadOutputToEnd());
await Host.ExecuteAsync(@"System.IntPtr.Size");
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("4\r\n", await ReadOutputToEnd());
var result = await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Core));
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadOutputToEnd());
await Host.ExecuteAsync(@"System.IntPtr.Size");
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("8\r\n", await ReadOutputToEnd());
}
#region Submission result printing - null/void/value.
[Fact]
public async Task SubmissionResult_PrintingNull()
{
await Execute(@"
string s;
s
");
var output = await ReadOutputToEnd();
Assert.Equal("null\r\n", output);
}
[Fact]
public async Task SubmissionResult_PrintingVoid()
{
await Execute(@"System.Console.WriteLine(2)");
var output = await ReadOutputToEnd();
Assert.Equal("2\r\n", output);
await Execute(@"
void goo() { }
goo()
");
output = await ReadOutputToEnd();
Assert.Equal("", output);
}
// TODO (https://github.com/dotnet/roslyn/issues/7976): delete this
[WorkItem(7976, "https://github.com/dotnet/roslyn/issues/7976")]
[Fact]
public void Workaround7976()
{
Thread.Sleep(TimeSpan.FromSeconds(10));
}
#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.
extern alias InteractiveHost;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
[Trait(Traits.Feature, Traits.Features.InteractiveHost)]
public sealed class InteractiveHostDesktopTests : AbstractInteractiveHostTests
{
internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop64;
internal override bool UseDefaultInitializationFile => false;
[Fact]
public async Task OutputRedirection()
{
await Execute(@"
System.Console.WriteLine(""hello-\u4567!"");
System.Console.Error.WriteLine(""error-\u7890!"");
1+1");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("hello-\u4567!\r\n2\r\n", output);
Assert.Equal("error-\u7890!\r\n", error);
}
[Fact]
public async Task OutputRedirection2()
{
await Execute(@"System.Console.WriteLine(1);");
await Execute(@"System.Console.Error.WriteLine(2);");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("1\r\n", output);
Assert.Equal("2\r\n", error);
RedirectOutput();
await Execute(@"System.Console.WriteLine(3);");
await Execute(@"System.Console.Error.WriteLine(4);");
output = await ReadOutputToEnd();
error = await ReadErrorOutputToEnd();
Assert.Equal("3\r\n", output);
Assert.Equal("4\r\n", error);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/46414")]
public async Task StackOverflow()
{
var process = Host.TryGetProcess();
await Execute(@"
int goo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9)
{
return goo(0,1,2,3,4,5,6,7,8,9) + goo(0,1,2,3,4,5,6,7,8,9);
}
goo(0,1,2,3,4,5,6,7,8,9)
");
var output = await ReadOutputToEnd();
Assert.Equal("", output);
// Hosting process exited with exit code ###.
var errorOutput = (await ReadErrorOutputToEnd()).Trim();
AssertEx.AssertEqualToleratingWhitespaceDifferences(
"Process is terminated due to StackOverflowException.\n" + string.Format(InteractiveHostResources.Hosting_process_exited_with_exit_code_0, process!.ExitCode), errorOutput);
await Execute(@"1+1");
output = await ReadOutputToEnd();
Assert.Equal("2\r\n", output.ToString());
}
private const string MethodWithInfiniteLoop = @"
void goo()
{
int i = 0;
while (true)
{
if (i < 10)
{
i = i + 1;
}
else if (i == 10)
{
System.Console.Error.WriteLine(""in the loop"");
i = i + 1;
}
}
}
";
[Fact]
public async Task AsyncExecute_InfiniteLoop()
{
var mayTerminate = new ManualResetEvent(false);
Host.ErrorOutputReceived += (_, __) => mayTerminate.Set();
await Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()");
Assert.True(mayTerminate.WaitOne());
await RestartHost();
await Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()");
var execution = await Execute(@"1+1");
var output = await ReadOutputToEnd();
Assert.True(execution);
Assert.Equal("2\r\n", output);
}
[Fact(Skip = "529027")]
public async Task AsyncExecute_HangingForegroundThreads()
{
var mayTerminate = new ManualResetEvent(false);
Host.OutputReceived += (_, __) =>
{
mayTerminate.Set();
};
var executeTask = Host.ExecuteAsync(@"
using System.Threading;
int i1 = 0;
Thread t1 = new Thread(() => { while(true) { i1++; } });
t1.Name = ""TestThread-1"";
t1.IsBackground = false;
t1.Start();
int i2 = 0;
Thread t2 = new Thread(() => { while(true) { i2++; } });
t2.Name = ""TestThread-2"";
t2.IsBackground = true;
t2.Start();
Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite));
t3.Name = ""TestThread-3"";
t3.Start();
while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { }
System.Console.WriteLine(""terminate!"");
while(true) {}
");
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error);
Assert.True(mayTerminate.WaitOne());
// TODO: var service = _host.TryGetService();
// Assert.NotNull(service);
var process = Host.TryGetProcess();
Assert.NotNull(process);
// service!.EmulateClientExit();
// the process should terminate with exit code 0:
process!.WaitForExit();
Assert.Equal(0, process.ExitCode);
}
[Fact]
public async Task AsyncExecuteFile_InfiniteLoop()
{
var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path;
var mayTerminate = new ManualResetEvent(false);
Host.ErrorOutputReceived += (_, __) => mayTerminate.Set();
await Host.ExecuteFileAsync(file);
mayTerminate.WaitOne();
await RestartHost();
var execution = await Execute(@"1+1");
var output = await ReadOutputToEnd();
Assert.True(execution);
Assert.Equal("2\r\n", output);
}
[Fact]
public async Task AsyncExecuteFile_SourceKind()
{
var file = Temp.CreateFile().WriteAllText("1 1").Path;
var task = await Host.ExecuteFileAsync(file);
Assert.False(task.Success);
var errorOut = (await ReadErrorOutputToEnd()).Trim();
Assert.True(errorOut.StartsWith(file + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column");
Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002");
}
[Fact]
public async Task AsyncExecuteFile_NonExistingFile()
{
var result = await Host.ExecuteFileAsync("non existing file");
Assert.False(result.Success);
var errorOut = (await ReadErrorOutputToEnd()).Trim();
Assert.Contains(InteractiveHostResources.Specified_file_not_found, errorOut, StringComparison.Ordinal);
Assert.Contains(InteractiveHostResources.Searched_in_directory_colon, errorOut, StringComparison.Ordinal);
}
[Fact]
public async Task AsyncExecuteFile()
{
var file = Temp.CreateFile().WriteAllText(@"
using static System.Console;
public class C
{
public int field = 4;
public int Goo(int i) { return i; }
}
public int Goo(int i) { return i; }
WriteLine(5);
").Path;
var task = await Host.ExecuteFileAsync(file);
var output = await ReadOutputToEnd();
Assert.True(task.Success);
Assert.Equal("5", output.Trim());
await Execute("Goo(2)");
output = await ReadOutputToEnd();
Assert.Equal("2", output.Trim());
await Execute("new C().Goo(3)");
output = await ReadOutputToEnd();
Assert.Equal("3", output.Trim());
await Execute("new C().field");
output = await ReadOutputToEnd();
Assert.Equal("4", output.Trim());
}
[Fact]
public async Task AsyncExecuteFile_InvalidFileContent()
{
await Host.ExecuteFileAsync(typeof(Process).Assembly.Location);
var errorOut = (await ReadErrorOutputToEnd()).Trim();
Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column");
Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056");
Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002");
}
[Fact]
public async Task AsyncExecuteFile_ScriptFileWithBuildErrors()
{
var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}");
await Host.ExecuteFileAsync(file.Path);
var errorOut = (await ReadErrorOutputToEnd()).Trim();
Assert.True(errorOut.StartsWith(file.Path + "(1,7):", StringComparison.Ordinal), "Error output should start with file name, line and column");
Assert.True(errorOut.Contains("CS7010"), "Error output should include error CS7010");
}
/// <summary>
/// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be
/// even invoked since we resolve the assembly via Fusion.
/// </summary>
[Fact(Skip = "987032")]
public async Task UserDefinedAssemblyResolve_InfiniteLoop()
{
var mayTerminate = new ManualResetEvent(false);
Host.ErrorOutputReceived += (_, __) => mayTerminate.Set();
// TODO: _host.TryGetService()!.HookMaliciousAssemblyResolve();
Assert.True(mayTerminate.WaitOne());
await Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid());
Assert.True(await Execute(@"1+1"));
var output = await ReadOutputToEnd();
Assert.Equal("2\r\n", output);
}
[Fact]
public async Task AddReference_Path()
{
var fxDir = await GetHostRuntimeDirectoryAsync();
Assert.False(await Execute("new System.Data.DataSet()"));
Assert.True(await LoadReference(Path.Combine(fxDir, "System.Data.dll")));
Assert.True(await Execute("new System.Data.DataSet()"));
}
[Fact]
public async Task AddReference_PartialName()
{
Assert.False(await Execute("new System.Data.DataSet()"));
Assert.True(await LoadReference("System.Data"));
Assert.True(await Execute("new System.Data.DataSet()"));
}
[Fact]
public async Task AddReference_PartialName_LatestVersion()
{
// there might be two versions of System.Data - v2 and v4, we should get the latter:
Assert.True(await LoadReference("System.Data"));
Assert.True(await LoadReference("System"));
Assert.True(await LoadReference("System.Xml"));
await Execute(@"new System.Data.DataSet().GetType().Assembly.GetName().Version");
var output = await ReadOutputToEnd();
Assert.Equal("[4.0.0.0]\r\n", output);
}
[Fact]
public async Task AddReference_FullName()
{
Assert.False(await Execute("new System.Data.DataSet()"));
Assert.True(await LoadReference("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
Assert.True(await Execute("new System.Data.DataSet()"));
}
[ConditionalFact(typeof(Framework35Installed), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/5167")]
public async Task AddReference_VersionUnification1()
{
// V3.5 unifies with the current Framework version:
var result = await LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("", output.Trim());
Assert.True(result);
result = await LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
output = await ReadOutputToEnd();
error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("", output.Trim());
Assert.True(result);
result = await LoadReference("System.Core");
output = await ReadOutputToEnd();
error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("", output.Trim());
Assert.True(result);
}
// Caused by submission not inheriting references.
[Fact(Skip = "101161")]
public async Task AddReference_ShadowCopy()
{
var dir = Temp.CreateDirectory();
// create C.dll
var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }");
// load C.dll:
var output = await ReadOutputToEnd();
Assert.True(await LoadReference(c.Path));
Assert.True(await Execute("new C()"));
Assert.Equal("C { }", output.Trim());
// rewrite C.dll:
File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 });
// we can still run code:
var result = await Execute("new C()");
output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("C { }", output.Trim());
Assert.True(result);
}
#if TODO
/// <summary>
/// Tests that a dependency is correctly resolved and loaded at runtime.
/// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded.
/// </summary>
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")]
public void AddReference_Dependencies()
{
var dir = Temp.CreateDirectory();
var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }");
var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image));
var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image));
AssemblyLoadResult result;
result = LoadReference(a.Path);
Assert.Equal(a.Path, result.OriginalPath);
Assert.True(IsShadowCopy(result.Path));
Assert.True(result.IsSuccessful);
Assert.True(Execute("A.CallB()"));
// c.dll is loaded as a dependency, so #r should be successful:
result = LoadReference(c.Path);
Assert.Equal(c.Path, result.OriginalPath);
Assert.True(IsShadowCopy(result.Path));
Assert.True(result.IsSuccessful);
// c.dll was already loaded explicitly via #r so we should fail now:
result = LoadReference(c.Path);
Assert.False(result.IsSuccessful);
Assert.Equal(c.Path, result.OriginalPath);
Assert.True(IsShadowCopy(result.Path));
Assert.Equal("", ReadErrorOutputToEnd().Trim());
Assert.Equal("1", ReadOutputToEnd().Trim());
}
#endif
/// <summary>
/// When two files of the same version are in the same directory, prefer .dll over .exe.
/// </summary>
[Fact]
public async Task AddReference_Dependencies_DllExe()
{
var dir = Temp.CreateDirectory();
var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }");
var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }");
var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }",
MetadataReference.CreateFromImage(dll.Image));
Assert.True(await LoadReference(main.Path));
Assert.True(await Execute("Program.Main()"));
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("1", output.Trim());
}
[Fact]
public async Task AddReference_Dependencies_Versions()
{
var dir1 = Temp.CreateDirectory();
var dir2 = Temp.CreateDirectory();
var dir3 = Temp.CreateDirectory();
// [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }");
var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1);
// [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }");
var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2);
Assert.True(await LoadReference(file1.Path));
Assert.True(await LoadReference(file2.Path));
var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }",
MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull()));
Assert.True(await LoadReference(main.Path));
Assert.True(await Execute("Program.Main()"));
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal("2", output.Trim());
}
[Fact]
public async Task AddReference_AlreadyLoadedDependencies()
{
var dir = Temp.CreateDirectory();
var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }");
var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }",
MetadataReference.CreateFromFile(lib1.Path));
await Execute("#r \"" + lib1.Path + "\"");
await Execute("#r \"" + lib2.Path + "\"");
await Execute("new C().M()");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences("1", output);
}
[Fact(Skip = "101161")]
public async Task AddReference_LoadUpdatedReference()
{
var dir = Temp.CreateDirectory();
var source1 = "public class C { public int X = 1; }";
var c1 = CreateCompilation(source1, assemblyName: "C");
var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray());
// use:
await Execute($@"
#r ""{file.Path}""
C goo() => new C();
new C().X
");
// update:
var source2 = "public class D { public int Y = 2; }";
var c2 = CreateCompilation(source2, assemblyName: "C");
file.WriteAllBytes(c2.EmitToArray());
// add the reference again:
await Execute($@"
#r ""{file.Path}""
new D().Y
");
// TODO: We should report an error that assembly named 'a' was already loaded with different content.
// In future we can let it load and improve error reporting around type conversions.
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error.Trim());
Assert.Equal(@"1
2", output.Trim());
}
[Fact(Skip = "129388")]
public async Task AddReference_MultipleReferencesWithSameWeakIdentity()
{
var dir = Temp.CreateDirectory();
var dir1 = dir.CreateDirectory("1");
var dir2 = dir.CreateDirectory("2");
var source1 = "public class C1 { }";
var c1 = CreateCompilation(source1, assemblyName: "C");
var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray());
var source2 = "public class C2 { }";
var c2 = CreateCompilation(source2, assemblyName: "C");
var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray());
await Execute($@"
#r ""{file1.Path}""
#r ""{file2.Path}""
");
await Execute("new C1()");
await Execute("new C2()");
// TODO: We should report an error that assembly named 'c' was already loaded with different content.
// In future we can let it load and let the compiler report the error CS1704: "An assembly with the same simple name 'C' has already been imported".
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal(@"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side.
(1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?)
(1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", error.Trim());
Assert.Equal("", output.Trim());
}
[Fact(Skip = "129388")]
public async Task AddReference_MultipleReferencesWeakVersioning()
{
var dir = Temp.CreateDirectory();
var dir1 = dir.CreateDirectory("1");
var dir2 = dir.CreateDirectory("2");
var source1 = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C1 { }";
var c1 = CreateCompilation(source1, assemblyName: "C");
var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray());
var source2 = @"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C2 { }";
var c2 = CreateCompilation(source2, assemblyName: "C");
var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray());
await Execute($@"
#r ""{file1.Path}""
#r ""{file2.Path}""
");
await Execute("new C1()");
await Execute("new C2()");
// TODO: We should report an error that assembly named 'c' was already loaded with different content.
// In future we can let it load and improve error reporting around type conversions.
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("TODO: error", error.Trim());
Assert.Equal("", output.Trim());
}
//// TODO (987032):
//// [Fact]
//// public void AsyncInitializeContextWithDotNETLibraries()
//// {
//// var rspFile = Temp.CreateFile();
//// var rspDisplay = Path.GetFileName(rspFile.Path);
//// var initScript = Temp.CreateFile();
//// rspFile.WriteAllText(@"
/////r:System.Core
////""" + initScript.Path + @"""
////");
//// initScript.WriteAllText(@"
////using static System.Console;
////using System.Linq.Expressions;
////WriteLine(Expression.Constant(123));
////");
//// // override default "is restarting" behavior (the REPL is already initialized):
//// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true);
//// task.Wait();
//// var output = SplitLines(ReadOutputToEnd());
//// var errorOutput = ReadErrorOutputToEnd();
//// Assert.Equal(4, output.Length);
//// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]);
//// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]);
//// Assert.Equal("Type \"#help\" for more information.", output[2]);
//// Assert.Equal("123", output[3]);
//// Assert.Equal("", errorOutput);
//// Host.InitializeContextAsync(rspFile.Path).Wait();
//// output = SplitLines(ReadOutputToEnd());
//// errorOutput = ReadErrorOutputToEnd();
//// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines.");
//// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]);
//// Assert.Equal("123", output[1]);
//// Assert.Equal("", errorOutput);
//// }
//// [Fact]
//// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries()
//// {
//// var dir = Temp.CreateDirectory();
//// var rspFile = Temp.CreateFile();
//// var initScript = Temp.CreateFile();
//// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }");
//// rspFile.WriteAllText(@"
/////r:System.Numerics
/////r:" + dll.Path + @"
////""" + initScript.Path + @"""
////");
//// initScript.WriteAllText(@"
////using static System.Console;
////using System.Numerics;
////WriteLine(new Complex(12, 6).Real + C.Main());
////");
//// // override default "is restarting" behavior (the REPL is already initialized):
//// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true);
//// task.Wait();
//// var errorOutput = ReadErrorOutputToEnd();
//// Assert.Equal("", errorOutput);
//// var output = SplitLines(ReadOutputToEnd());
//// Assert.Equal(4, output.Length);
//// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]);
//// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]);
//// Assert.Equal("Type \"#help\" for more information.", output[2]);
//// Assert.Equal("13", output[3]);
//// }
[Fact]
public async Task ReferencePathsRsp()
{
var directory1 = Temp.CreateDirectory();
CompileLibrary(directory1, "Assembly0.dll", "Assembly0", @"public class C0 { }");
CompileLibrary(directory1, "Assembly1.dll", "Assembly1", @"public class C1 { }");
var initDirectory = Temp.CreateDirectory();
var initFile = initDirectory.CreateFile("init.csx");
initFile.WriteAllText(@"
#r ""Assembly0.dll""
System.Console.WriteLine(typeof(C0).Assembly.GetName());
System.Console.WriteLine(typeof(C2).Assembly.GetName());
Print(ReferencePaths);
");
var rspDirectory = Temp.CreateDirectory();
CompileLibrary(rspDirectory, "Assembly2.dll", "Assembly2", @"public class C2 { }");
CompileLibrary(rspDirectory, "Assembly3.dll", "Assembly3", @"public class C3 { }");
var rspFile = rspDirectory.CreateFile("init.rsp");
rspFile.WriteAllText($"/lib:{directory1.Path} /r:Assembly2.dll {initFile.Path}");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, culture: CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
var fxDir = await GetHostRuntimeDirectoryAsync();
await Execute(@"
#r ""Assembly1.dll""
System.Console.WriteLine(typeof(C1).Assembly.GetName());
Print(ReferencePaths);
");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
var expectedSearchPaths = PrintSearchPaths(fxDir, directory1.Path);
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences($@"
{string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path))}
Assembly0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
Assembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
{expectedSearchPaths}
Assembly1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
{expectedSearchPaths}
", output);
}
[Fact]
public async Task ReferencePathsRsp_Error()
{
var initDirectory = Temp.CreateDirectory();
var initFile = initDirectory.CreateFile("init.csx");
initFile.WriteAllText(@"#r ""Assembly.dll""");
var rspDirectory = Temp.CreateDirectory();
CompileLibrary(rspDirectory, "Assembly.dll", "Assembly", "public class C { }");
var rspFile = rspDirectory.CreateFile("init.rsp");
rspFile.WriteAllText($"{initFile.Path}");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, culture: CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences(
@$"{initFile.Path}(1,1): error CS0006: {string.Format(CSharpResources.ERR_NoMetadataFile, "Assembly.dll")}", error);
}
[Fact]
public async Task DefaultUsings()
{
var rspFile = Temp.CreateFile();
rspFile.WriteAllText(@"
/r:System
/r:System.Core
/r:Microsoft.CSharp
/u:System
/u:System.IO
/u:System.Collections.Generic
/u:System.Diagnostics
/u:System.Dynamic
/u:System.Linq
/u:System.Linq.Expressions
/u:System.Text
/u:System.Threading.Tasks
");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
await Execute(@"
dynamic d = new ExpandoObject();
");
await Execute(@"
Process p = new Process();
");
await Execute(@"
Expression<Func<int>> e = () => 1;
");
await Execute(@"
var squares = from x in new[] { 1, 2, 3 } select x * x;
");
await Execute(@"
var sb = new StringBuilder();
");
await Execute(@"
var list = new List<int>();
");
await Execute(@"
var stream = new MemoryStream();
await Task.Delay(10);
p = new Process();
Console.Write(""OK"")
");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences(
$@"{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) }
OK
", output);
}
[Fact]
public async Task InitialScript_Error()
{
var initFile = Temp.CreateFile(extension: ".csx").WriteAllText("1 1");
var rspFile = Temp.CreateFile();
rspFile.WriteAllText($@"
/r:System
/u:System.Diagnostics
{initFile.Path}
");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
await Execute("new Process()");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences($@"{initFile.Path}(1,3): error CS1002: { CSharpResources.ERR_SemicolonExpected }
", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences($@"
{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) }
[System.Diagnostics.Process]
", output);
}
[Fact]
public async Task ScriptAndArguments()
{
var scriptFile = Temp.CreateFile(extension: ".csx").WriteAllText("foreach (var arg in Args) Print(arg);");
var rspFile = Temp.CreateFile();
rspFile.WriteAllText($@"
{scriptFile}
a
b
c
");
await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform));
var error = await ReadErrorOutputToEnd();
Assert.Equal("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences(
$@"{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) }
""a""
""b""
""c""
", await ReadOutputToEnd());
}
[Fact]
public async Task Script_NoHostNamespaces()
{
await Execute("nameof(Microsoft.Missing)");
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences($@"(1,8): error CS0234: { string.Format(CSharpResources.ERR_DottedTypeNameNotFoundInNS, "Missing", "Microsoft") }",
error);
var output = await ReadOutputToEnd();
Assert.Equal("", output);
}
[Fact]
public async Task ExecutesOnStaThread()
{
await Execute(@"
#r ""System""
#r ""System.Xaml""
#r ""WindowsBase""
#r ""PresentationCore""
#r ""PresentationFramework""
new System.Windows.Window();
System.Console.WriteLine(""OK"");
");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
Assert.Equal("", error);
Assert.Equal("OK\r\n", output);
}
/// <summary>
/// Execution of expressions should be
/// sequential, even await expressions.
/// </summary>
[Fact]
public async Task ExecuteSequentially()
{
await Execute(@"using System;
using System.Threading.Tasks;");
await Execute(@"await Task.Delay(1000).ContinueWith(t => 1)");
await Execute(@"await Task.Delay(500).ContinueWith(t => 2)");
await Execute(@"3");
var output = await ReadOutputToEnd();
Assert.Equal("1\r\n2\r\n3\r\n", output);
}
[Fact]
public async Task MultiModuleAssembly()
{
var dir = Temp.CreateDirectory();
var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll);
dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2);
dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3);
await Execute(@"
#r """ + dll.Path + @"""
new object[] { new Class1(), new Class2(), new Class3() }
");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
Assert.Equal("", error);
Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output);
}
[Fact, WorkItem(6457, "https://github.com/dotnet/roslyn/issues/6457")]
public async Task MissingReferencesReuse()
{
var source = @"
public class C
{
public System.Diagnostics.Process P;
}
";
var lib = CSharpCompilation.Create(
"Lib",
new[] { SyntaxFactory.ParseSyntaxTree(source) },
new[] { Net451.mscorlib, Net451.System },
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var libFile = Temp.CreateFile("lib").WriteAllBytes(lib.EmitToArray());
await Execute($@"#r ""{libFile.Path}""");
await Execute("C c;");
await Execute("c = new C()");
var error = await ReadErrorOutputToEnd();
var output = await ReadOutputToEnd();
Assert.Equal("", error);
AssertEx.AssertEqualToleratingWhitespaceDifferences("C { P=null }", output);
}
[Fact, WorkItem(7280, "https://github.com/dotnet/roslyn/issues/7280")]
public async Task AsyncContinueOnDifferentThread()
{
await Execute(@"
using System;
using System.Threading;
using System.Threading.Tasks;
Console.Write(Task.Run(() => { Thread.CurrentThread.Join(100); return 42; }).ContinueWith(t => t.Result).Result)");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("42", output);
Assert.Empty(error);
}
[Fact]
public async Task Exception()
{
await Execute(@"throw new System.Exception();");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
Assert.Equal("", output);
Assert.DoesNotContain("Unexpected", error, StringComparison.OrdinalIgnoreCase);
Assert.True(error.StartsWith($"{new Exception().GetType()}: {new Exception().Message}"));
}
[Fact, WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")]
public async Task PreservingDeclarationsOnException()
{
await Execute(@"int i = 100;");
await Execute(@"int j = 20; throw new System.Exception(""Bang!""); int k = 3;");
await Execute(@"i + j + k");
var output = await ReadOutputToEnd();
var error = await ReadErrorOutputToEnd();
AssertEx.AssertEqualToleratingWhitespaceDifferences("120", output);
AssertEx.AssertEqualToleratingWhitespaceDifferences("System.Exception: Bang!", error);
}
[Fact]
public async Task Bitness()
{
await Host.ExecuteAsync(@"System.IntPtr.Size");
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("8\r\n", await ReadOutputToEnd());
await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop32));
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadOutputToEnd());
await Host.ExecuteAsync(@"System.IntPtr.Size");
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("4\r\n", await ReadOutputToEnd());
var result = await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Core));
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadOutputToEnd());
await Host.ExecuteAsync(@"System.IntPtr.Size");
AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd());
AssertEx.AssertEqualToleratingWhitespaceDifferences("8\r\n", await ReadOutputToEnd());
}
#region Submission result printing - null/void/value.
[Fact]
public async Task SubmissionResult_PrintingNull()
{
await Execute(@"
string s;
s
");
var output = await ReadOutputToEnd();
Assert.Equal("null\r\n", output);
}
[Fact]
public async Task SubmissionResult_PrintingVoid()
{
await Execute(@"System.Console.WriteLine(2)");
var output = await ReadOutputToEnd();
Assert.Equal("2\r\n", output);
await Execute(@"
void goo() { }
goo()
");
output = await ReadOutputToEnd();
Assert.Equal("", output);
}
// TODO (https://github.com/dotnet/roslyn/issues/7976): delete this
[WorkItem(7976, "https://github.com/dotnet/roslyn/issues/7976")]
[Fact]
public void Workaround7976()
{
Thread.Sleep(TimeSpan.FromSeconds(10));
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Analyzers/CSharp/CodeFixes/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableCodeFixProvider.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 System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.MakeStructFieldsWritable
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeStructFieldsWritable), Shared]
internal class CSharpMakeStructFieldsWritableCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpMakeStructFieldsWritableCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.MakeStructFieldsWritable);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document,
ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor,
CancellationToken cancellationToken)
{
foreach (var diagnostic in diagnostics)
{
var diagnosticNode = diagnostic.Location.FindNode(cancellationToken);
if (!(diagnosticNode is StructDeclarationSyntax structDeclaration))
{
continue;
}
var fieldDeclarations = structDeclaration.Members
.OfType<FieldDeclarationSyntax>();
foreach (var fieldDeclaration in fieldDeclarations)
{
var fieldDeclarationModifiers = editor.Generator.GetModifiers(fieldDeclaration);
var containsReadonlyModifier =
(fieldDeclarationModifiers & DeclarationModifiers.ReadOnly) == DeclarationModifiers.ReadOnly;
if (containsReadonlyModifier)
{
editor.SetModifiers(fieldDeclaration, fieldDeclarationModifiers.WithIsReadOnly(false));
}
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Make_readonly_fields_writable, createChangedDocument, nameof(CSharpAnalyzersResources.Make_readonly_fields_writable))
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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 System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.MakeStructFieldsWritable
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeStructFieldsWritable), Shared]
internal class CSharpMakeStructFieldsWritableCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpMakeStructFieldsWritableCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.MakeStructFieldsWritable);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document,
ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor,
CancellationToken cancellationToken)
{
foreach (var diagnostic in diagnostics)
{
var diagnosticNode = diagnostic.Location.FindNode(cancellationToken);
if (!(diagnosticNode is StructDeclarationSyntax structDeclaration))
{
continue;
}
var fieldDeclarations = structDeclaration.Members
.OfType<FieldDeclarationSyntax>();
foreach (var fieldDeclaration in fieldDeclarations)
{
var fieldDeclarationModifiers = editor.Generator.GetModifiers(fieldDeclaration);
var containsReadonlyModifier =
(fieldDeclarationModifiers & DeclarationModifiers.ReadOnly) == DeclarationModifiers.ReadOnly;
if (containsReadonlyModifier)
{
editor.SetModifiers(fieldDeclaration, fieldDeclarationModifiers.WithIsReadOnly(false));
}
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Make_readonly_fields_writable, createChangedDocument, nameof(CSharpAnalyzersResources.Make_readonly_fields_writable))
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/VisualStudio/Core/Def/Implementation/LanguageClient/VisualStudioLspWorkspaceRegistrationEventListener.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;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient
{
[ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host, WorkspaceKind.MiscellaneousFiles, WorkspaceKind.MetadataAsSource), Shared]
internal class VisualStudioLspWorkspaceRegistrationEventListener : IEventListener<object>
{
private readonly ILspWorkspaceRegistrationService _lspWorkspaceRegistrationService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioLspWorkspaceRegistrationEventListener(ILspWorkspaceRegistrationService lspWorkspaceRegistrationService)
{
_lspWorkspaceRegistrationService = lspWorkspaceRegistrationService;
}
public void StartListening(Workspace workspace, object _)
{
_lspWorkspaceRegistrationService.Register(workspace);
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient
{
[ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host, WorkspaceKind.MiscellaneousFiles, WorkspaceKind.MetadataAsSource), Shared]
internal class VisualStudioLspWorkspaceRegistrationEventListener : IEventListener<object>
{
private readonly ILspWorkspaceRegistrationService _lspWorkspaceRegistrationService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioLspWorkspaceRegistrationEventListener(ILspWorkspaceRegistrationService lspWorkspaceRegistrationService)
{
_lspWorkspaceRegistrationService = lspWorkspaceRegistrationService;
}
public void StartListening(Workspace workspace, object _)
{
_lspWorkspaceRegistrationService.Register(workspace);
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/EditorFeatures/VisualBasicTest/Diagnostics/CorrectNextControlVariable/CorrectNextControlVariableTests.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.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.CorrectNextControlVariable
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.CorrectNextControlVariable
Public Class CorrectNextControlVariableTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New CorrectNextControlVariableCodeFixProvider)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForLoopBoundIdentifier() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
Dim y As Integer
For x = 1 To 10
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
Dim y As Integer
For x = 1 To 10
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForLoopUnboundIdentifier() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For x = 1 To 10
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For x = 1 To 10
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachLoopBoundIdentifier() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
Dim y As Integer
For Each x In {1, 2, 3}
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
Dim y As Integer
For Each x In {1, 2, 3}
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachLoopUnboundIdentifier() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x In {1, 2, 3}
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x In {1, 2, 3}
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachNested() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x In {1, 2, 3}
For Each y In {1, 2, 3}
Next [|x|]
Next x
End Sub
End Module",
"Module M1
Sub Main()
For Each x In {1, 2, 3}
For Each y In {1, 2, 3}
Next y
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachNestedOuter() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x In {1, 2, 3}
For Each y In {1, 2, 3}
Next y
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x In {1, 2, 3}
For Each y In {1, 2, 3}
Next y
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForLoopWithDeclarator() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
Dim y As Integer
For x As Integer = 1 To 10
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
Dim y As Integer
For x As Integer = 1 To 10
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachLoopWithDeclarator() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMultipleControl1() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For Each y In {1, 2, 3}
Next [|x|], y
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For Each y In {1, 2, 3}
Next y, y
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMultipleControl2() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For Each y In {1, 2, 3}
Next x, [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For Each y In {1, 2, 3}
Next x, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMixedNestedLoop() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestThreeLevels() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
For Each z As Integer In {1, 2, 3}
Next z
Next y, [|z|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
For Each z As Integer In {1, 2, 3}
Next z
Next y, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestExtraVariable() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, [|z|], x
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, x, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMethodCall() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y
Next [|y|]()
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestLongExpressions() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next [|x + 10 + 11|], x
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestNoLoop() As Task
Await TestMissingInRegularAndScriptAsync(
"Module M1
Sub Main()
Next [|y|]
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMissingNesting() As Task
Await TestMissingInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x In {1, 2, 3}
Next x, [|y|]
End Sub
End Module")
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 Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.CorrectNextControlVariable
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.CorrectNextControlVariable
Public Class CorrectNextControlVariableTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New CorrectNextControlVariableCodeFixProvider)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForLoopBoundIdentifier() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
Dim y As Integer
For x = 1 To 10
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
Dim y As Integer
For x = 1 To 10
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForLoopUnboundIdentifier() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For x = 1 To 10
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For x = 1 To 10
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachLoopBoundIdentifier() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
Dim y As Integer
For Each x In {1, 2, 3}
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
Dim y As Integer
For Each x In {1, 2, 3}
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachLoopUnboundIdentifier() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x In {1, 2, 3}
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x In {1, 2, 3}
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachNested() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x In {1, 2, 3}
For Each y In {1, 2, 3}
Next [|x|]
Next x
End Sub
End Module",
"Module M1
Sub Main()
For Each x In {1, 2, 3}
For Each y In {1, 2, 3}
Next y
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachNestedOuter() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x In {1, 2, 3}
For Each y In {1, 2, 3}
Next y
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x In {1, 2, 3}
For Each y In {1, 2, 3}
Next y
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForLoopWithDeclarator() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
Dim y As Integer
For x As Integer = 1 To 10
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
Dim y As Integer
For x As Integer = 1 To 10
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestForEachLoopWithDeclarator() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
Next [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMultipleControl1() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For Each y In {1, 2, 3}
Next [|x|], y
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For Each y In {1, 2, 3}
Next y, y
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMultipleControl2() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For Each y In {1, 2, 3}
Next x, [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For Each y In {1, 2, 3}
Next x, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMixedNestedLoop() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, [|y|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestThreeLevels() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
For Each z As Integer In {1, 2, 3}
Next z
Next y, [|z|]
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
For Each z As Integer In {1, 2, 3}
Next z
Next y, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestExtraVariable() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, [|z|], x
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, x, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMethodCall() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y
Next [|y|]()
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y
Next x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestLongExpressions() As Task
Await TestInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next [|x + 10 + 11|], x
End Sub
End Module",
"Module M1
Sub Main()
For Each x As Integer In {1, 2, 4}
For y = 1 To 10
Next y, x
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestNoLoop() As Task
Await TestMissingInRegularAndScriptAsync(
"Module M1
Sub Main()
Next [|y|]
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsCorrectNextControlVariable)>
Public Async Function TestMissingNesting() As Task
Await TestMissingInRegularAndScriptAsync(
"Module M1
Sub Main()
For Each x In {1, 2, 3}
Next x, [|y|]
End Sub
End Module")
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/EditorFeatures/CSharpTest/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_DotnetNegativeTests.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.Text.RegularExpressions;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions
{
// These tests came from tests found at:
// https://github.com/dotnet/corefx/blob/main/src/System.Text.RegularExpressions/tests/
public partial class CSharpRegexParserTests
{
[Fact]
public void NegativeTest0()
{
Test(@"@""cat([a-\d]*)dog""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "d")}"" Span=""[17..19)"" Text=""\d"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""cat([a-\d]*)dog"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([a-\d]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest1()
{
Test(@"@""\k<1""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken><1</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""\k<1"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest2()
{
Test(@"@""\k<""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken><</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[10..12)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\k<"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest3()
{
Test(@"@""\k""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[10..12)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\k"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest4()
{
Test(@"@""\1""", $@"<Tree>
<CompilationUnit>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "1")}"" Span=""[11..12)"" Text=""1"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\1"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest5()
{
Test(@"@""(?')""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken />
<SingleQuoteToken />
<Sequence />
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?')"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest6()
{
Test(@"@""(?<)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken />
<GreaterThanToken />
<Sequence />
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?<)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest7()
{
Test(@"@""(?)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest8()
{
Test(@"@""(?>""", $@"<Tree>
<CompilationUnit>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence />
<CloseParenToken />
</AtomicGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?>"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest9()
{
Test(@"@""(?<!""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NegativeLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<ExclamationToken>!</ExclamationToken>
<Sequence />
<CloseParenToken />
</NegativeLookbehindGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?<!"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest10()
{
Test(@"@""(?<=""", $@"<Tree>
<CompilationUnit>
<Sequence>
<PositiveLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<EqualsToken>=</EqualsToken>
<Sequence />
<CloseParenToken />
</PositiveLookbehindGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?<="" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest11()
{
Test(@"@""(?!""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NegativeLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ExclamationToken>!</ExclamationToken>
<Sequence />
<CloseParenToken />
</NegativeLookaheadGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?!"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest12()
{
Test(@"@""(?=""", $@"<Tree>
<CompilationUnit>
<Sequence>
<PositiveLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<EqualsToken>=</EqualsToken>
<Sequence />
<CloseParenToken />
</PositiveLookaheadGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?="" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest13()
{
Test(@"@""(?imn )""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>imn</OptionsToken>
<CloseParenToken />
</SimpleOptionsGrouping>
<Text>
<TextToken> </TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[16..17)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?imn )"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest14()
{
Test(@"@""(?imn""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>imn</OptionsToken>
<CloseParenToken />
</SimpleOptionsGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""(?imn"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest15()
{
Test(@"@""(?:""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence />
<CloseParenToken />
</NonCapturingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?:"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest16()
{
Test(@"@""(?'cat'""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence />
<CloseParenToken />
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?'cat'"" />
<Capture Name=""1"" Span=""[10..17)"" Text=""(?'cat'"" />
<Capture Name=""cat"" Span=""[10..17)"" Text=""(?'cat'"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest17()
{
Test(@"@""(?'""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken />
<SingleQuoteToken />
<Sequence />
<CloseParenToken />
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..13)"" Text=""(?'"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?'"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest18()
{
Test(@"@""[^""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence />
<CloseBracketToken />
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""[^"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest19()
{
Test(@"@""[cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""[cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest20()
{
Test(@"@""[^cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[15..15)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""[^cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest21()
{
Test(@"@""[a-""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken />
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""[a-"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest22()
{
Test(@"@""\p{""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\p{{"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest23()
{
Test(@"@""\p{cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\p{{cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest24()
{
Test(@"@""\k<cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken><cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\k<cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest25()
{
Test(@"@""\p{cat}""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>cat</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "cat")}"" Span=""[13..16)"" Text=""cat"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\p{{cat}}"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest26()
{
Test(@"@""\P{cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\P{{cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest27()
{
Test(@"@""\P{cat}""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>cat</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "cat")}"" Span=""[13..16)"" Text=""cat"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\P{{cat}}"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest28()
{
Test(@"@""(""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..11)"" Text=""("" />
<Capture Name=""1"" Span=""[10..11)"" Text=""("" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest29()
{
Test(@"@""(?""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""(?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest30()
{
Test(@"@""(?<""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken />
<GreaterThanToken />
<Sequence />
<CloseParenToken />
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..13)"" Text=""(?<"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?<"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest31()
{
Test(@"@""(?<cat>""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence />
<CloseParenToken />
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?<cat>"" />
<Capture Name=""1"" Span=""[10..17)"" Text=""(?<cat>"" />
<Capture Name=""cat"" Span=""[10..17)"" Text=""(?<cat>"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest32()
{
Test(@"@""\P{""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\P{{"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest33()
{
Test(@"@""\k<>""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""\k<>"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest34()
{
Test(@"@""(?(""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken />
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?("" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest35()
{
Test(@"@""(?()|""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Alternation>
<Sequence />
<BarToken>|</BarToken>
<Sequence />
</Alternation>
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""(?()|"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest36()
{
Test(@"@""?(a|b)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>b</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""?(a|b)"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""(a|b)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest37()
{
Test(@"@""?((a)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""?((a)"" />
<Capture Name=""1"" Span=""[11..15)"" Text=""((a)"" />
<Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest38()
{
Test(@"@""?((a)a""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""?((a)a"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""((a)a"" />
<Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest39()
{
Test(@"@""?((a)a|""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence />
</Alternation>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""?((a)a|"" />
<Capture Name=""1"" Span=""[11..17)"" Text=""((a)a|"" />
<Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest40()
{
Test(@"@""?((a)a|b""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>b</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[18..18)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""?((a)a|b"" />
<Capture Name=""1"" Span=""[11..18)"" Text=""((a)a|b"" />
<Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest41()
{
Test(@"@""(?(?i))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>i</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?i))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest42()
{
Test(@"@""?(a)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""?(a)"" />
<Capture Name=""1"" Span=""[11..14)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest43()
{
Test(@"@""(?(?I))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>I</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?I))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest44()
{
Test(@"@""(?(?M))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>M</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?M))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest45()
{
Test(@"@""(?(?s))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>s</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?s))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest46()
{
Test(@"@""(?(?S))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>S</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?S))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest47()
{
Test(@"@""(?(?x))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>x</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?x))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest48()
{
Test(@"@""(?(?X))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>X</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?X))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest49()
{
Test(@"@""(?(?n))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>n</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?n))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest50()
{
Test(@"@""(?(?m))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>m</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?m))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest51()
{
Test(@"@""[a""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""[a"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest52()
{
Test(@"@""?(a:b)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a:b</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""?(a:b)"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""(a:b)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest53()
{
Test(@"@""(?(?""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?(?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest54()
{
Test(@"@""(?(cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(?(cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest55()
{
Test(@"@""(?(cat)|""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Alternation>
<Sequence />
<BarToken>|</BarToken>
<Sequence />
</Alternation>
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[18..18)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""(?(cat)|"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest56()
{
Test(@"@""foo(?<0>bar)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>foo</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""0"">0</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>bar</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""foo(?<0>bar)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest57()
{
Test(@"@""foo(?'0'bar)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>foo</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<NumberToken value=""0"">0</NumberToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>bar</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""foo(?'0'bar)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest58()
{
Test(@"@""foo(?<1bar)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>foo</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken>bar</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""b"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""foo(?<1bar)"" />
<Capture Name=""1"" Span=""[13..21)"" Text=""(?<1bar)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest59()
{
Test(@"@""foo(?'1bar)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>foo</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<NumberToken value=""1"">1</NumberToken>
<SingleQuoteToken />
<Sequence>
<Text>
<TextToken>bar</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""b"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""foo(?'1bar)"" />
<Capture Name=""1"" Span=""[13..21)"" Text=""(?'1bar)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest60()
{
Test(@"@""(?(""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken />
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?("" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest61()
{
Test(@"@""\p{klsak""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{klsak</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""\p{{klsak"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest62()
{
Test(@"@""(?c:cat)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>c:cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""(?c:cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest63()
{
Test(@"@""(??e:cat)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<Text>
<TextToken>?</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>e:cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""(??e:cat)"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""(??e:cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest64()
{
Test(@"@""[a-f-[]]+""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>f</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>]</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
<Text>
<TextToken>+</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class}"" Span=""[14..14)"" Text="""" />
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[19..19)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""[a-f-[]]+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest65()
{
Test(@"@""[A-[]+""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>A</TextToken>
</Text>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>]+</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""[A-[]+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest66()
{
Test(@"@""(?(?e))""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>e</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?e))"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest67()
{
Test(@"@""(?(?a)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(?(?a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest68()
{
Test(@"@""(?r:cat)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>r:cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""(?r:cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest69()
{
Test(@"@""(?(?N))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>N</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?N))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest70()
{
Test(@"@""[]""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>]</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""[]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest71()
{
Test(@"@""\x2""", $@"<Tree>
<CompilationUnit>
<Sequence>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>2</TextToken>
</HexEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\x2"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\x2"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest72()
{
Test(@"@""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
<CommentTrivia>(?#cat)</CommentTrivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
<CommentTrivia>(?#followed by 1 or more whitespace</CommentTrivia>
</Trivia>
</EndOfFile>
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[31..66)"" Text=""(?#followed by 1 or more whitespace"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..66)"" Text=""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
</Captures>
</Tree>", RegexOptions.IgnorePatternWhitespace);
}
[Fact]
public void NegativeTest73()
{
Test(@"@""cat(?(?afdcat)dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>afdcat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[15..16)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[16..17)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..28)"" Text=""cat(?(?afdcat)dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest74()
{
Test(@"@""cat(?(?<cat>cat)dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[13..14)"" Text=""("" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?<cat>cat)dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest75()
{
Test(@"@""cat(?(?'cat'cat)dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[13..14)"" Text=""("" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?'cat'cat)dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest76()
{
Test(@"@""cat(?(?#COMMENT)cat)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>#COMMENT</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Alternation_conditions_cannot_be_comments}"" Span=""[13..14)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[15..16)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[16..17)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?#COMMENT)cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest77()
{
Test(@"@""(?<cat>cat)\w+(?<dog-()*!@>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken />
<GreaterThanToken />
<Sequence>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>!@>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[31..32)"" Text=""("" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..41)"" Text=""(?<cat>cat)\w+(?<dog-()*!@>dog)"" />
<Capture Name=""1"" Span=""[31..33)"" Text=""()"" />
<Capture Name=""2"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""3"" Span=""[24..41)"" Text=""(?<dog-()*!@>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..41)"" Text=""(?<dog-()*!@>dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest78()
{
Test(@"@""(?<cat>cat)\w+(?<dog-catdog>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""catdog"">catdog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "catdog")}"" Span=""[31..37)"" Text=""catdog"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..42)"" Text=""(?<cat>cat)\w+(?<dog-catdog>dog)"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..42)"" Text=""(?<dog-catdog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..42)"" Text=""(?<dog-catdog>dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest79()
{
Test(@"@""(?<cat>cat)\w+(?<dog-1uosn>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<MinusToken>-</MinusToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken>uosn>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[32..33)"" Text=""u"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..41)"" Text=""(?<cat>cat)\w+(?<dog-1uosn>dog)"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..41)"" Text=""(?<dog-1uosn>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..41)"" Text=""(?<dog-1uosn>dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest80()
{
Test(@"@""(?<cat>cat)\w+(?<dog-16>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<MinusToken>-</MinusToken>
<NumberToken value=""16"">16</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "16")}"" Span=""[31..33)"" Text=""16"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..38)"" Text=""(?<cat>cat)\w+(?<dog-16>dog)"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..38)"" Text=""(?<dog-16>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..38)"" Text=""(?<dog-16>dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest81()
{
Test(@"@""cat(?<->dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken />
<MinusToken>-</MinusToken>
<CaptureNameToken />
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text="">"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""cat(?<->dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest82()
{
Test(@"@""cat(?<>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken />
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[16..17)"" Text="">"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""cat(?<>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest83()
{
Test(@"@""cat(?<dog<>)_*>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>_</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>>dog</TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text=""<"" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""cat(?<dog<>)_*>dog)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""(?<dog<>)"" />
<Capture Name=""dog"" Span=""[13..22)"" Text=""(?<dog<>)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest84()
{
Test(@"@""cat(?<dog >)_*>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken> ></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>_</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>>dog</TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text="" "" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""cat(?<dog >)_*>dog)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""(?<dog >)"" />
<Capture Name=""dog"" Span=""[13..22)"" Text=""(?<dog >)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest85()
{
Test(@"@""cat(?<dog!>)_*>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken>!></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>_</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>>dog</TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text=""!"" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""cat(?<dog!>)_*>dog)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""(?<dog!>)"" />
<Capture Name=""dog"" Span=""[13..22)"" Text=""(?<dog!>)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest86()
{
Test(@"@""cat(?<dog)_*>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken />
<Sequence />
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>_</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>>dog</TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text="")"" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[26..27)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""cat(?<dog)_*>dog)"" />
<Capture Name=""1"" Span=""[13..20)"" Text=""(?<dog)"" />
<Capture Name=""dog"" Span=""[13..20)"" Text=""(?<dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest87()
{
Test(@"@""cat(?<1dog>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken>dog>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""d"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""cat(?<1dog>dog)"" />
<Capture Name=""1"" Span=""[13..25)"" Text=""(?<1dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest88()
{
Test(@"@""cat(?<0>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""0"">0</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""cat(?<0>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest89()
{
Test(@"@""([5-\D]*)dog""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>5</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "D")}"" Span=""[14..16)"" Text=""\D"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""([5-\D]*)dog"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""([5-\D]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest90()
{
Test(@"@""cat([6-\s]*)dog""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>6</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "s")}"" Span=""[17..19)"" Text=""\s"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""cat([6-\s]*)dog"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([6-\s]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest91()
{
Test(@"@""cat([c-\S]*)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>c</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>S</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "S")}"" Span=""[17..19)"" Text=""\S"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""cat([c-\S]*)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([c-\S]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest92()
{
Test(@"@""cat([7-\w]*)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>7</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "w")}"" Span=""[17..19)"" Text=""\w"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""cat([7-\w]*)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([7-\w]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest93()
{
Test(@"@""cat([a-\W]*)dog""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "W")}"" Span=""[17..19)"" Text=""\W"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""cat([a-\W]*)dog"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([a-\W]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest94()
{
Test(@"@""([f-\p{Lu}]\w*)\s([\p{Lu}]\w*)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>f</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "p")}"" Span=""[14..16)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""([f-\p{{Lu}}]\w*)\s([\p{{Lu}}]\w*)"" />
<Capture Name=""1"" Span=""[10..25)"" Text=""([f-\p{{Lu}}]\w*)"" />
<Capture Name=""2"" Span=""[27..40)"" Text=""([\p{{Lu}}]\w*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest95()
{
Test(@"@""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken> </TextToken>
</Text>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?#cat)</CommentTrivia>
</Trivia> </TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Text>
<TextToken> </TextToken>
</Text>
</Sequence>
<EndOfFile>
<Trivia>
<CommentTrivia>(?#followed by 1 or more whitespace</CommentTrivia>
</Trivia>
</EndOfFile>
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[31..66)"" Text=""(?#followed by 1 or more whitespace"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..66)"" Text=""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest96()
{
Test(@"@""([1-\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>1</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "P")}"" Span=""[14..16)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..52)"" Text=""([1-\P{{Ll}}][\p{{Ll}}]*)\s([\P{{Ll}}][\p{{Ll}}]*)"" />
<Capture Name=""1"" Span=""[10..31)"" Text=""([1-\P{{Ll}}][\p{{Ll}}]*)"" />
<Capture Name=""2"" Span=""[33..52)"" Text=""([\P{{Ll}}][\p{{Ll}}]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest97()
{
Test(@"@""[\P]""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""[\P]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest98()
{
Test(@"@""([\pcat])""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[12..14)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""([\pcat])"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""([\pcat])"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest99()
{
Test(@"@""([\Pcat])""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
</SimpleEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[12..14)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""([\Pcat])"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""([\Pcat])"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest100()
{
Test(@"@""(\p{""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(\p{{"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\p{{"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest101()
{
Test(@"@""(\p{Ll""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{Ll</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(\p{{Ll"" />
<Capture Name=""1"" Span=""[10..16)"" Text=""(\p{{Ll"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest102()
{
Test(@"@""(cat)([\o]*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>o</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "o")}"" Span=""[18..19)"" Text=""o"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(cat)([\o]*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..22)"" Text=""([\o]*)"" />
<Capture Name=""3"" Span=""[22..27)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest103()
{
Test(@"@""[\p]""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""[\p]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest104()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\kcat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[35..37)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""(?<cat>cat)\s+(?<dog>dog)\kcat"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest105()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<cat2>""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat2"">cat2</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "cat2")}"" Span=""[38..42)"" Text=""cat2"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k<cat2>"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest106()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<8>cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""8"">8</NumberToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "8")}"" Span=""[38..39)"" Text=""8"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k<8>cat"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest107()
{
Test(@"@""^[abcd]{1}?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<ExactNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CloseBraceToken>}}</CloseBraceToken>
</ExactNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[21..22)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""^[abcd]{{1}}?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest108()
{
Test(@"@""^[abcd]*+$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>+</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[18..19)"" Text=""+"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]*+$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest109()
{
Test(@"@""^[abcd]+*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[18..19)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]+*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest110()
{
Test(@"@""^[abcd]?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[18..19)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest111()
{
Test(@"@""^[abcd]*?+$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>+</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[19..20)"" Text=""+"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]*?+$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest112()
{
Test(@"@""^[abcd]+?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]+?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest113()
{
Test(@"@""^[abcd]{1,}?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<OpenRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[22..23)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]{{1,}}?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest114()
{
Test(@"@""^[abcd]??*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]??*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest115()
{
Test(@"@""^[abcd]+{0,5}$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Text>
<TextToken>{{</TextToken>
</Text>
<Text>
<TextToken>0,5}}</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]+{{0,5}}$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest116()
{
Test(@"@""^[abcd]?{0,5}$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>{{</TextToken>
</Text>
<Text>
<TextToken>0,5}}</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]?{{0,5}}$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest117()
{
Test(@"@""\u""", $@"<Tree>
<CompilationUnit>
<Sequence>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken />
</UnicodeEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\u"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest118()
{
Test(@"@""\ua""", $@"<Tree>
<CompilationUnit>
<Sequence>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken>a</TextToken>
</UnicodeEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\ua"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\ua"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest119()
{
Test(@"@""\u0""", $@"<Tree>
<CompilationUnit>
<Sequence>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken>0</TextToken>
</UnicodeEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\u0"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\u0"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest120()
{
Test(@"@""\x""", $@"<Tree>
<CompilationUnit>
<Sequence>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken />
</HexEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\x"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest121()
{
Test(@"@""^[abcd]*{0,5}$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>{{</TextToken>
</Text>
<Text>
<TextToken>0,5}}</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]*{{0,5}}$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest122()
{
Test(@"@""[""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence />
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[11..11)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..11)"" Text=""["" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest123()
{
Test(@"@""^[abcd]{0,16}?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<ClosedRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""0"">0</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""16"">16</NumberToken>
<CloseBraceToken>}}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[24..25)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""^[abcd]{{0,16}}?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest124()
{
Test(@"@""^[abcd]{1,}*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OpenRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[21..22)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""^[abcd]{{1,}}*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest125()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<8>cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""8"">8</NumberToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "8")}"" Span=""[38..39)"" Text=""8"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k<8>cat"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.ECMAScript);
}
[Fact]
public void NegativeTest126()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k8""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken>8</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[35..37)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..38)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k8"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest127()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k8""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken>8</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[35..37)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..38)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k8"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.ECMAScript);
}
[Fact]
public void NegativeTest128()
{
Test(@"@""(cat)(\7)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""7"">7</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "7")}"" Span=""[17..18)"" Text=""7"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""(cat)(\7)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..19)"" Text=""(\7)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest129()
{
Test(@"@""(cat)\s+(?<2147483648>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""-2147483648"">2147483648</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[21..31)"" Text=""2147483648"" />
</Diagnostics>
<Captures>
<Capture Name=""-2147483648"" Span=""[18..36)"" Text=""(?<2147483648>dog)"" />
<Capture Name=""0"" Span=""[10..36)"" Text=""(cat)\s+(?<2147483648>dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest130()
{
Test(@"@""(cat)\s+(?<21474836481097>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1097"">21474836481097</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[21..35)"" Text=""21474836481097"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""(cat)\s+(?<21474836481097>dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""1097"" Span=""[18..40)"" Text=""(?<21474836481097>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest131()
{
Test(@"@""^[abcd]{1}*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ExactNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CloseBraceToken>}}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[20..21)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""^[abcd]{{1}}*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest132()
{
Test(@"@""(cat)(\c*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""(cat)(\c*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..20)"" Text=""(\c*)"" />
<Capture Name=""3"" Span=""[20..25)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest133()
{
Test(@"@""(cat)(\c *)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
<ZeroOrMoreQuantifier>
<Text>
<TextToken> </TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text="" "" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c *)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..21)"" Text=""(\c *)"" />
<Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest134()
{
Test(@"@""(cat)(\c?*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""?"" />
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c?*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..21)"" Text=""(\c?*)"" />
<Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest135()
{
Test(@"@""(cat)(\c`*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>`</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""`"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c`*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..21)"" Text=""(\c`*)"" />
<Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest136()
{
Test(@"@""(cat)(\c\|*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken>\</TextToken>
</ControlEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>*</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[20..21)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(cat)(\c\|*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..22)"" Text=""(\c\|*)"" />
<Capture Name=""3"" Span=""[22..27)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest137()
{
Test(@"@""(cat)(\c\[*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken>\</TextToken>
</ControlEscape>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>*)(dog)</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[27..27)"" Text="""" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[27..27)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(cat)(\c\[*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..27)"" Text=""(\c\[*)(dog)"" />
</Captures>
</Tree>", RegexOptions.None, runSubTreeTests: false);
}
[Fact]
public void NegativeTest138()
{
Test(@"@""^[abcd]{0,16}*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ClosedRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""0"">0</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""16"">16</NumberToken>
<CloseBraceToken>}}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[23..24)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""^[abcd]{{0,16}}*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest139()
{
Test(@"@""(cat)\c""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Missing_control_character}"" Span=""[16..17)"" Text=""c"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(cat)\c"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Text.RegularExpressions;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions
{
// These tests came from tests found at:
// https://github.com/dotnet/corefx/blob/main/src/System.Text.RegularExpressions/tests/
public partial class CSharpRegexParserTests
{
[Fact]
public void NegativeTest0()
{
Test(@"@""cat([a-\d]*)dog""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>d</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "d")}"" Span=""[17..19)"" Text=""\d"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""cat([a-\d]*)dog"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([a-\d]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest1()
{
Test(@"@""\k<1""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken><1</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""\k<1"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest2()
{
Test(@"@""\k<""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken><</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[10..12)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\k<"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest3()
{
Test(@"@""\k""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[10..12)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\k"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest4()
{
Test(@"@""\1""", $@"<Tree>
<CompilationUnit>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""1"">1</NumberToken>
</BackreferenceEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "1")}"" Span=""[11..12)"" Text=""1"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\1"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest5()
{
Test(@"@""(?')""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken />
<SingleQuoteToken />
<Sequence />
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?')"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest6()
{
Test(@"@""(?<)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken />
<GreaterThanToken />
<Sequence />
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?<)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest7()
{
Test(@"@""(?)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest8()
{
Test(@"@""(?>""", $@"<Tree>
<CompilationUnit>
<Sequence>
<AtomicGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence />
<CloseParenToken />
</AtomicGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?>"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest9()
{
Test(@"@""(?<!""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NegativeLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<ExclamationToken>!</ExclamationToken>
<Sequence />
<CloseParenToken />
</NegativeLookbehindGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?<!"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest10()
{
Test(@"@""(?<=""", $@"<Tree>
<CompilationUnit>
<Sequence>
<PositiveLookbehindGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<EqualsToken>=</EqualsToken>
<Sequence />
<CloseParenToken />
</PositiveLookbehindGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?<="" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest11()
{
Test(@"@""(?!""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NegativeLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ExclamationToken>!</ExclamationToken>
<Sequence />
<CloseParenToken />
</NegativeLookaheadGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?!"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest12()
{
Test(@"@""(?=""", $@"<Tree>
<CompilationUnit>
<Sequence>
<PositiveLookaheadGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<EqualsToken>=</EqualsToken>
<Sequence />
<CloseParenToken />
</PositiveLookaheadGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?="" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest13()
{
Test(@"@""(?imn )""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>imn</OptionsToken>
<CloseParenToken />
</SimpleOptionsGrouping>
<Text>
<TextToken> </TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[16..17)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?imn )"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest14()
{
Test(@"@""(?imn""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>imn</OptionsToken>
<CloseParenToken />
</SimpleOptionsGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""(?imn"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest15()
{
Test(@"@""(?:""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NonCapturingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<ColonToken>:</ColonToken>
<Sequence />
<CloseParenToken />
</NonCapturingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?:"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest16()
{
Test(@"@""(?'cat'""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence />
<CloseParenToken />
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?'cat'"" />
<Capture Name=""1"" Span=""[10..17)"" Text=""(?'cat'"" />
<Capture Name=""cat"" Span=""[10..17)"" Text=""(?'cat'"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest17()
{
Test(@"@""(?'""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken />
<SingleQuoteToken />
<Sequence />
<CloseParenToken />
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..13)"" Text=""(?'"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?'"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest18()
{
Test(@"@""[^""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence />
<CloseBracketToken />
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""[^"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest19()
{
Test(@"@""[cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""[cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest20()
{
Test(@"@""[^cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<NegatedCharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<CaretToken>^</CaretToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</NegatedCharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[15..15)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""[^cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest21()
{
Test(@"@""[a-""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken />
</Text>
</CharacterClassRange>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""[a-"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest22()
{
Test(@"@""\p{""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\p{{"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest23()
{
Test(@"@""\p{cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\p{{cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest24()
{
Test(@"@""\k<cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken><cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\k<cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest25()
{
Test(@"@""\p{cat}""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>cat</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "cat")}"" Span=""[13..16)"" Text=""cat"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\p{{cat}}"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest26()
{
Test(@"@""\P{cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""\P{{cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest27()
{
Test(@"@""\P{cat}""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>cat</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "cat")}"" Span=""[13..16)"" Text=""cat"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""\P{{cat}}"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest28()
{
Test(@"@""(""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..11)"" Text=""("" />
<Capture Name=""1"" Span=""[10..11)"" Text=""("" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest29()
{
Test(@"@""(?""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""(?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest30()
{
Test(@"@""(?<""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken />
<GreaterThanToken />
<Sequence />
<CloseParenToken />
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..13)"" Text=""(?<"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?<"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest31()
{
Test(@"@""(?<cat>""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence />
<CloseParenToken />
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?<cat>"" />
<Capture Name=""1"" Span=""[10..17)"" Text=""(?<cat>"" />
<Capture Name=""cat"" Span=""[10..17)"" Text=""(?<cat>"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest32()
{
Test(@"@""\P{""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\P{{"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest33()
{
Test(@"@""\k<>""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""\k<>"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest34()
{
Test(@"@""(?(""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken />
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?("" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest35()
{
Test(@"@""(?()|""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Alternation>
<Sequence />
<BarToken>|</BarToken>
<Sequence />
</Alternation>
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""(?()|"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest36()
{
Test(@"@""?(a|b)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>b</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""?(a|b)"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""(a|b)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest37()
{
Test(@"@""?((a)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..15)"" Text=""?((a)"" />
<Capture Name=""1"" Span=""[11..15)"" Text=""((a)"" />
<Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest38()
{
Test(@"@""?((a)a""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""?((a)a"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""((a)a"" />
<Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest39()
{
Test(@"@""?((a)a|""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence />
</Alternation>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""?((a)a|"" />
<Capture Name=""1"" Span=""[11..17)"" Text=""((a)a|"" />
<Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest40()
{
Test(@"@""?((a)a|b""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>b</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[18..18)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""?((a)a|b"" />
<Capture Name=""1"" Span=""[11..18)"" Text=""((a)a|b"" />
<Capture Name=""2"" Span=""[12..15)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest41()
{
Test(@"@""(?(?i))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>i</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?i))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest42()
{
Test(@"@""?(a)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""?(a)"" />
<Capture Name=""1"" Span=""[11..14)"" Text=""(a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest43()
{
Test(@"@""(?(?I))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>I</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?I))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest44()
{
Test(@"@""(?(?M))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>M</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?M))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest45()
{
Test(@"@""(?(?s))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>s</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?s))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest46()
{
Test(@"@""(?(?S))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>S</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?S))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest47()
{
Test(@"@""(?(?x))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>x</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?x))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest48()
{
Test(@"@""(?(?X))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>X</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?X))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest49()
{
Test(@"@""(?(?n))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>n</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?n))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest50()
{
Test(@"@""(?(?m))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>m</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?m))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest51()
{
Test(@"@""[a""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""[a"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest52()
{
Test(@"@""?(a:b)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>a:b</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""?(a:b)"" />
<Capture Name=""1"" Span=""[11..16)"" Text=""(a:b)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest53()
{
Test(@"@""(?(?""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(?(?"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest54()
{
Test(@"@""(?(cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(?(cat"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest55()
{
Test(@"@""(?(cat)|""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Alternation>
<Sequence />
<BarToken>|</BarToken>
<Sequence />
</Alternation>
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[18..18)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""(?(cat)|"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest56()
{
Test(@"@""foo(?<0>bar)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>foo</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""0"">0</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>bar</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""foo(?<0>bar)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest57()
{
Test(@"@""foo(?'0'bar)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>foo</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<NumberToken value=""0"">0</NumberToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>bar</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""foo(?'0'bar)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest58()
{
Test(@"@""foo(?<1bar)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>foo</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken>bar</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""b"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""foo(?<1bar)"" />
<Capture Name=""1"" Span=""[13..21)"" Text=""(?<1bar)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest59()
{
Test(@"@""foo(?'1bar)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>foo</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<NumberToken value=""1"">1</NumberToken>
<SingleQuoteToken />
<Sequence>
<Text>
<TextToken>bar</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""b"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""foo(?'1bar)"" />
<Capture Name=""1"" Span=""[13..21)"" Text=""(?'1bar)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest60()
{
Test(@"@""(?(""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken />
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""(?("" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest61()
{
Test(@"@""\p{klsak""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{klsak</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[10..12)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""\p{{klsak"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest62()
{
Test(@"@""(?c:cat)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>c:cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""(?c:cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest63()
{
Test(@"@""(??e:cat)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<Text>
<TextToken>?</TextToken>
</Text>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>e:cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""(??e:cat)"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""(??e:cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest64()
{
Test(@"@""[a-f-[]]+""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<Text>
<TextToken>f</TextToken>
</Text>
</CharacterClassRange>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>]</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</CharacterClassSubtraction>
<Text>
<TextToken>+</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class}"" Span=""[14..14)"" Text="""" />
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[19..19)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""[a-f-[]]+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest65()
{
Test(@"@""[A-[]+""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>A</TextToken>
</Text>
<CharacterClassSubtraction>
<MinusToken>-</MinusToken>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>]+</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</CharacterClassSubtraction>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""[A-[]+"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest66()
{
Test(@"@""(?(?e))""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>e</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?e))"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest67()
{
Test(@"@""(?(?a)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>a</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Sequence />
<CloseParenToken />
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[12..13)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[13..14)"" Text=""?"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(?(?a)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest68()
{
Test(@"@""(?r:cat)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>r:cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[10..11)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[11..12)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..18)"" Text=""(?r:cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest69()
{
Test(@"@""(?(?N))""", @"<Tree>
<CompilationUnit>
<Sequence>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleOptionsGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<OptionsToken>N</OptionsToken>
<CloseParenToken>)</CloseParenToken>
</SimpleOptionsGrouping>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(?(?N))"" />
</Captures>
</Tree>", RegexOptions.None, allowNullReference: true);
}
[Fact]
public void NegativeTest70()
{
Test(@"@""[]""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>]</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""[]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest71()
{
Test(@"@""\x2""", $@"<Tree>
<CompilationUnit>
<Sequence>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken>2</TextToken>
</HexEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\x2"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\x2"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest72()
{
Test(@"@""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
<CommentTrivia>(?#cat)</CommentTrivia>
<WhitespaceTrivia> </WhitespaceTrivia>
</Trivia>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
</Sequence>
<EndOfFile>
<Trivia>
<WhitespaceTrivia> </WhitespaceTrivia>
<CommentTrivia>(?#followed by 1 or more whitespace</CommentTrivia>
</Trivia>
</EndOfFile>
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[31..66)"" Text=""(?#followed by 1 or more whitespace"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..66)"" Text=""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
</Captures>
</Tree>", RegexOptions.IgnorePatternWhitespace);
}
[Fact]
public void NegativeTest73()
{
Test(@"@""cat(?(?afdcat)dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>afdcat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[15..16)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[16..17)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..28)"" Text=""cat(?(?afdcat)dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest74()
{
Test(@"@""cat(?(?<cat>cat)dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[13..14)"" Text=""("" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?<cat>cat)dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest75()
{
Test(@"@""cat(?(?'cat'cat)dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SingleQuoteToken>'</SingleQuoteToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<SingleQuoteToken>'</SingleQuoteToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[13..14)"" Text=""("" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?'cat'cat)dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest76()
{
Test(@"@""cat(?(?#COMMENT)cat)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<ConditionalExpressionGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>?</TextToken>
</Text>
<Text>
<TextToken>#COMMENT</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</ConditionalExpressionGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Alternation_conditions_cannot_be_comments}"" Span=""[13..14)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[15..16)"" Text=""("" />
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[16..17)"" Text=""?"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..30)"" Text=""cat(?(?#COMMENT)cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest77()
{
Test(@"@""(?<cat>cat)\w+(?<dog-()*!@>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken />
<GreaterThanToken />
<Sequence>
<ZeroOrMoreQuantifier>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence />
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>!@>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[31..32)"" Text=""("" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..41)"" Text=""(?<cat>cat)\w+(?<dog-()*!@>dog)"" />
<Capture Name=""1"" Span=""[31..33)"" Text=""()"" />
<Capture Name=""2"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""3"" Span=""[24..41)"" Text=""(?<dog-()*!@>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..41)"" Text=""(?<dog-()*!@>dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest78()
{
Test(@"@""(?<cat>cat)\w+(?<dog-catdog>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<MinusToken>-</MinusToken>
<CaptureNameToken value=""catdog"">catdog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "catdog")}"" Span=""[31..37)"" Text=""catdog"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..42)"" Text=""(?<cat>cat)\w+(?<dog-catdog>dog)"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..42)"" Text=""(?<dog-catdog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..42)"" Text=""(?<dog-catdog>dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest79()
{
Test(@"@""(?<cat>cat)\w+(?<dog-1uosn>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<MinusToken>-</MinusToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken>uosn>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[32..33)"" Text=""u"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..41)"" Text=""(?<cat>cat)\w+(?<dog-1uosn>dog)"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..41)"" Text=""(?<dog-1uosn>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..41)"" Text=""(?<dog-1uosn>dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest80()
{
Test(@"@""(?<cat>cat)\w+(?<dog-16>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<MinusToken>-</MinusToken>
<NumberToken value=""16"">16</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "16")}"" Span=""[31..33)"" Text=""16"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..38)"" Text=""(?<cat>cat)\w+(?<dog-16>dog)"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..38)"" Text=""(?<dog-16>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..38)"" Text=""(?<dog-16>dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest81()
{
Test(@"@""cat(?<->dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<BalancingGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken />
<MinusToken>-</MinusToken>
<CaptureNameToken />
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</BalancingGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text="">"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""cat(?<->dog)"" />
</Captures>
</Tree>", RegexOptions.None, allowIndexOutOfRange: true);
}
[Fact]
public void NegativeTest82()
{
Test(@"@""cat(?<>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken />
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[16..17)"" Text="">"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""cat(?<>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest83()
{
Test(@"@""cat(?<dog<>)_*>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken><></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>_</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>>dog</TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text=""<"" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""cat(?<dog<>)_*>dog)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""(?<dog<>)"" />
<Capture Name=""dog"" Span=""[13..22)"" Text=""(?<dog<>)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest84()
{
Test(@"@""cat(?<dog >)_*>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken> ></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>_</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>>dog</TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text="" "" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""cat(?<dog >)_*>dog)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""(?<dog >)"" />
<Capture Name=""dog"" Span=""[13..22)"" Text=""(?<dog >)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest85()
{
Test(@"@""cat(?<dog!>)_*>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken>!></TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>_</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>>dog</TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text=""!"" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[28..29)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..29)"" Text=""cat(?<dog!>)_*>dog)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""(?<dog!>)"" />
<Capture Name=""dog"" Span=""[13..22)"" Text=""(?<dog!>)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest86()
{
Test(@"@""cat(?<dog)_*>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken />
<Sequence />
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>_</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>>dog</TextToken>
</Text>
<Text>
<TextToken>)</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[19..20)"" Text="")"" />
<Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[26..27)"" Text="")"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""cat(?<dog)_*>dog)"" />
<Capture Name=""1"" Span=""[13..20)"" Text=""(?<dog)"" />
<Capture Name=""dog"" Span=""[13..20)"" Text=""(?<dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest87()
{
Test(@"@""cat(?<1dog>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1"">1</NumberToken>
<GreaterThanToken />
<Sequence>
<Text>
<TextToken>dog>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[17..18)"" Text=""d"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""cat(?<1dog>dog)"" />
<Capture Name=""1"" Span=""[13..25)"" Text=""(?<1dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest88()
{
Test(@"@""cat(?<0>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""0"">0</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[16..17)"" Text=""0"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""cat(?<0>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest89()
{
Test(@"@""([5-\D]*)dog""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>5</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>D</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "D")}"" Span=""[14..16)"" Text=""\D"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""([5-\D]*)dog"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""([5-\D]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest90()
{
Test(@"@""cat([6-\s]*)dog""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>6</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "s")}"" Span=""[17..19)"" Text=""\s"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""cat([6-\s]*)dog"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([6-\s]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest91()
{
Test(@"@""cat([c-\S]*)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>c</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>S</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "S")}"" Span=""[17..19)"" Text=""\S"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""cat([c-\S]*)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([c-\S]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest92()
{
Test(@"@""cat([7-\w]*)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>7</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "w")}"" Span=""[17..19)"" Text=""\w"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""cat([7-\w]*)"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([7-\w]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest93()
{
Test(@"@""cat([a-\W]*)dog""", $@"<Tree>
<CompilationUnit>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>a</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>W</TextToken>
</CharacterClassEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "W")}"" Span=""[17..19)"" Text=""\W"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""cat([a-\W]*)dog"" />
<Capture Name=""1"" Span=""[13..22)"" Text=""([a-\W]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest94()
{
Test(@"@""([f-\p{Lu}]\w*)\s([\p{Lu}]\w*)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>f</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Lu</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>w</TextToken>
</CharacterClassEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "p")}"" Span=""[14..16)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""([f-\p{{Lu}}]\w*)\s([\p{{Lu}}]\w*)"" />
<Capture Name=""1"" Span=""[10..25)"" Text=""([f-\p{{Lu}}]\w*)"" />
<Capture Name=""2"" Span=""[27..40)"" Text=""([\p{{Lu}}]\w*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest95()
{
Test(@"@""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<Text>
<TextToken> </TextToken>
</Text>
<Text>
<TextToken>
<Trivia>
<CommentTrivia>(?#cat)</CommentTrivia>
</Trivia> </TextToken>
</Text>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Text>
<TextToken> </TextToken>
</Text>
</Sequence>
<EndOfFile>
<Trivia>
<CommentTrivia>(?#followed by 1 or more whitespace</CommentTrivia>
</Trivia>
</EndOfFile>
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[31..66)"" Text=""(?#followed by 1 or more whitespace"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..66)"" Text=""(cat) (?#cat) \s+ (?#followed by 1 or more whitespace"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest96()
{
Test(@"@""([1-\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CharacterClassRange>
<Text>
<TextToken>1</TextToken>
</Text>
<MinusToken>-</MinusToken>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</CharacterClassRange>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<CategoryEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
<OpenBraceToken>{{</OpenBraceToken>
<EscapeCategoryToken>Ll</EscapeCategoryToken>
<CloseBraceToken>}}</CloseBraceToken>
</CategoryEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "P")}"" Span=""[14..16)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..52)"" Text=""([1-\P{{Ll}}][\p{{Ll}}]*)\s([\P{{Ll}}][\p{{Ll}}]*)"" />
<Capture Name=""1"" Span=""[10..31)"" Text=""([1-\P{{Ll}}][\p{{Ll}}]*)"" />
<Capture Name=""2"" Span=""[33..52)"" Text=""([\P{{Ll}}][\p{{Ll}}]*)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest97()
{
Test(@"@""[\P]""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""[\P]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest98()
{
Test(@"@""([\pcat])""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[12..14)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""([\pcat])"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""([\pcat])"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest99()
{
Test(@"@""([\Pcat])""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>P</TextToken>
</SimpleEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[12..14)"" Text=""\P"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""([\Pcat])"" />
<Capture Name=""1"" Span=""[10..19)"" Text=""([\Pcat])"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest100()
{
Test(@"@""(\p{""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""(\p{{"" />
<Capture Name=""1"" Span=""[10..14)"" Text=""(\p{{"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest101()
{
Test(@"@""(\p{Ll""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
<Text>
<TextToken>{{Ll</TextToken>
</Text>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..16)"" Text=""(\p{{Ll"" />
<Capture Name=""1"" Span=""[10..16)"" Text=""(\p{{Ll"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest102()
{
Test(@"@""(cat)([\o]*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>o</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "o")}"" Span=""[18..19)"" Text=""o"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(cat)([\o]*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..22)"" Text=""([\o]*)"" />
<Capture Name=""3"" Span=""[22..27)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest103()
{
Test(@"@""[\p]""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>p</TextToken>
</SimpleEscape>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[11..13)"" Text=""\p"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..14)"" Text=""[\p]"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest104()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\kcat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[35..37)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""(?<cat>cat)\s+(?<dog>dog)\kcat"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest105()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<cat2>""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat2"">cat2</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "cat2")}"" Span=""[38..42)"" Text=""cat2"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k<cat2>"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest106()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<8>cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""8"">8</NumberToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "8")}"" Span=""[38..39)"" Text=""8"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k<8>cat"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest107()
{
Test(@"@""^[abcd]{1}?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<ExactNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CloseBraceToken>}}</CloseBraceToken>
</ExactNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[21..22)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""^[abcd]{{1}}?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest108()
{
Test(@"@""^[abcd]*+$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>+</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[18..19)"" Text=""+"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]*+$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest109()
{
Test(@"@""^[abcd]+*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[18..19)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]+*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest110()
{
Test(@"@""^[abcd]?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[18..19)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..20)"" Text=""^[abcd]?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest111()
{
Test(@"@""^[abcd]*?+$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>+</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[19..20)"" Text=""+"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]*?+$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest112()
{
Test(@"@""^[abcd]+?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]+?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest113()
{
Test(@"@""^[abcd]{1,}?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<OpenRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[22..23)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]{{1,}}?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest114()
{
Test(@"@""^[abcd]??*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..21)"" Text=""^[abcd]??*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest115()
{
Test(@"@""^[abcd]+{0,5}$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OneOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<Text>
<TextToken>{{</TextToken>
</Text>
<Text>
<TextToken>0,5}}</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]+{{0,5}}$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest116()
{
Test(@"@""^[abcd]?{0,5}$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrOneQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>{{</TextToken>
</Text>
<Text>
<TextToken>0,5}}</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]?{{0,5}}$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest117()
{
Test(@"@""\u""", $@"<Tree>
<CompilationUnit>
<Sequence>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken />
</UnicodeEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\u"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest118()
{
Test(@"@""\ua""", $@"<Tree>
<CompilationUnit>
<Sequence>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken>a</TextToken>
</UnicodeEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\ua"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\ua"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest119()
{
Test(@"@""\u0""", $@"<Tree>
<CompilationUnit>
<Sequence>
<UnicodeEscape>
<BackslashToken>\</BackslashToken>
<TextToken>u</TextToken>
<TextToken>0</TextToken>
</UnicodeEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\u0"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..13)"" Text=""\u0"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest120()
{
Test(@"@""\x""", $@"<Tree>
<CompilationUnit>
<Sequence>
<HexEscape>
<BackslashToken>\</BackslashToken>
<TextToken>x</TextToken>
<TextToken />
</HexEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..12)"" Text=""\x"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest121()
{
Test(@"@""^[abcd]*{0,5}$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ZeroOrMoreQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
<Text>
<TextToken>{{</TextToken>
</Text>
<Text>
<TextToken>0,5}}</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[18..19)"" Text=""{{"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..24)"" Text=""^[abcd]*{{0,5}}$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest122()
{
Test(@"@""[""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence />
<CloseBracketToken />
</CharacterClass>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[11..11)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..11)"" Text=""["" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest123()
{
Test(@"@""^[abcd]{0,16}?*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<LazyQuantifier>
<ClosedRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""0"">0</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""16"">16</NumberToken>
<CloseBraceToken>}}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<QuestionToken>?</QuestionToken>
</LazyQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[24..25)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""^[abcd]{{0,16}}?*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest124()
{
Test(@"@""^[abcd]{1,}*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<OpenRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CommaToken>,</CommaToken>
<CloseBraceToken>}}</CloseBraceToken>
</OpenRangeNumericQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[21..22)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..23)"" Text=""^[abcd]{{1,}}*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest125()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k<8>cat""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<KCaptureEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""8"">8</NumberToken>
<GreaterThanToken>></GreaterThanToken>
</KCaptureEscape>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "8")}"" Span=""[38..39)"" Text=""8"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..43)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k<8>cat"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.ECMAScript);
}
[Fact]
public void NegativeTest126()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k8""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken>8</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[35..37)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..38)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k8"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest127()
{
Test(@"@""(?<cat>cat)\s+(?<dog>dog)\k8""", $@"<Tree>
<CompilationUnit>
<Sequence>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""cat"">cat</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<CaptureNameToken value=""dog"">dog</CaptureNameToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
<SimpleEscape>
<BackslashToken>\</BackslashToken>
<TextToken>k</TextToken>
</SimpleEscape>
<Text>
<TextToken>8</TextToken>
</Text>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "<").Replace(">", ">")}"" Span=""[35..37)"" Text=""\k"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..38)"" Text=""(?<cat>cat)\s+(?<dog>dog)\k8"" />
<Capture Name=""1"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""2"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
<Capture Name=""cat"" Span=""[10..21)"" Text=""(?<cat>cat)"" />
<Capture Name=""dog"" Span=""[24..35)"" Text=""(?<dog>dog)"" />
</Captures>
</Tree>", RegexOptions.ECMAScript);
}
[Fact]
public void NegativeTest128()
{
Test(@"@""(cat)(\7)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<BackreferenceEscape>
<BackslashToken>\</BackslashToken>
<NumberToken value=""7"">7</NumberToken>
</BackreferenceEscape>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, "7")}"" Span=""[17..18)"" Text=""7"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..19)"" Text=""(cat)(\7)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..19)"" Text=""(\7)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest129()
{
Test(@"@""(cat)\s+(?<2147483648>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""-2147483648"">2147483648</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[21..31)"" Text=""2147483648"" />
</Diagnostics>
<Captures>
<Capture Name=""-2147483648"" Span=""[18..36)"" Text=""(?<2147483648>dog)"" />
<Capture Name=""0"" Span=""[10..36)"" Text=""(cat)\s+(?<2147483648>dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest130()
{
Test(@"@""(cat)\s+(?<21474836481097>dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<OneOrMoreQuantifier>
<CharacterClassEscape>
<BackslashToken>\</BackslashToken>
<TextToken>s</TextToken>
</CharacterClassEscape>
<PlusToken>+</PlusToken>
</OneOrMoreQuantifier>
<CaptureGrouping>
<OpenParenToken>(</OpenParenToken>
<QuestionToken>?</QuestionToken>
<LessThanToken><</LessThanToken>
<NumberToken value=""1097"">21474836481097</NumberToken>
<GreaterThanToken>></GreaterThanToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</CaptureGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[21..35)"" Text=""21474836481097"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..40)"" Text=""(cat)\s+(?<21474836481097>dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""1097"" Span=""[18..40)"" Text=""(?<21474836481097>dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest131()
{
Test(@"@""^[abcd]{1}*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ExactNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""1"">1</NumberToken>
<CloseBraceToken>}}</CloseBraceToken>
</ExactNumericQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[20..21)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..22)"" Text=""^[abcd]{{1}}*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest132()
{
Test(@"@""(cat)(\c*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrMoreQuantifier>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""(cat)(\c*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..20)"" Text=""(\c*)"" />
<Capture Name=""3"" Span=""[20..25)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest133()
{
Test(@"@""(cat)(\c *)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
<ZeroOrMoreQuantifier>
<Text>
<TextToken> </TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text="" "" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c *)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..21)"" Text=""(\c *)"" />
<Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest134()
{
Test(@"@""(cat)(\c?*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ZeroOrOneQuantifier>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
<QuestionToken>?</QuestionToken>
</ZeroOrOneQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""?"" />
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[19..20)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c?*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..21)"" Text=""(\c?*)"" />
<Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest135()
{
Test(@"@""(cat)(\c`*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
<ZeroOrMoreQuantifier>
<Text>
<TextToken>`</TextToken>
</Text>
<AsteriskToken>*</AsteriskToken>
</ZeroOrMoreQuantifier>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[18..19)"" Text=""`"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..26)"" Text=""(cat)(\c`*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..21)"" Text=""(\c`*)"" />
<Capture Name=""3"" Span=""[21..26)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest136()
{
Test(@"@""(cat)(\c\|*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Alternation>
<Sequence>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken>\</TextToken>
</ControlEscape>
</Sequence>
<BarToken>|</BarToken>
<Sequence>
<Text>
<TextToken>*</TextToken>
</Text>
</Sequence>
</Alternation>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>dog</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[20..21)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(cat)(\c\|*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..22)"" Text=""(\c\|*)"" />
<Capture Name=""3"" Span=""[22..27)"" Text=""(dog)"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest137()
{
Test(@"@""(cat)(\c\[*)(dog)""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken>\</TextToken>
</ControlEscape>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>*)(dog)</TextToken>
</Text>
</Sequence>
<CloseBracketToken />
</CharacterClass>
</Sequence>
<CloseParenToken />
</SimpleGrouping>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[27..27)"" Text="""" />
<Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[27..27)"" Text="""" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..27)"" Text=""(cat)(\c\[*)(dog)"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
<Capture Name=""2"" Span=""[15..27)"" Text=""(\c\[*)(dog)"" />
</Captures>
</Tree>", RegexOptions.None, runSubTreeTests: false);
}
[Fact]
public void NegativeTest138()
{
Test(@"@""^[abcd]{0,16}*$""", $@"<Tree>
<CompilationUnit>
<Sequence>
<StartAnchor>
<CaretToken>^</CaretToken>
</StartAnchor>
<ClosedRangeNumericQuantifier>
<CharacterClass>
<OpenBracketToken>[</OpenBracketToken>
<Sequence>
<Text>
<TextToken>abcd</TextToken>
</Text>
</Sequence>
<CloseBracketToken>]</CloseBracketToken>
</CharacterClass>
<OpenBraceToken>{{</OpenBraceToken>
<NumberToken value=""0"">0</NumberToken>
<CommaToken>,</CommaToken>
<NumberToken value=""16"">16</NumberToken>
<CloseBraceToken>}}</CloseBraceToken>
</ClosedRangeNumericQuantifier>
<Text>
<TextToken>*</TextToken>
</Text>
<EndAnchor>
<DollarToken>$</DollarToken>
</EndAnchor>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[23..24)"" Text=""*"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..25)"" Text=""^[abcd]{{0,16}}*$"" />
</Captures>
</Tree>", RegexOptions.None);
}
[Fact]
public void NegativeTest139()
{
Test(@"@""(cat)\c""", $@"<Tree>
<CompilationUnit>
<Sequence>
<SimpleGrouping>
<OpenParenToken>(</OpenParenToken>
<Sequence>
<Text>
<TextToken>cat</TextToken>
</Text>
</Sequence>
<CloseParenToken>)</CloseParenToken>
</SimpleGrouping>
<ControlEscape>
<BackslashToken>\</BackslashToken>
<TextToken>c</TextToken>
<TextToken />
</ControlEscape>
</Sequence>
<EndOfFile />
</CompilationUnit>
<Diagnostics>
<Diagnostic Message=""{FeaturesResources.Missing_control_character}"" Span=""[16..17)"" Text=""c"" />
</Diagnostics>
<Captures>
<Capture Name=""0"" Span=""[10..17)"" Text=""(cat)\c"" />
<Capture Name=""1"" Span=""[10..15)"" Text=""(cat)"" />
</Captures>
</Tree>", RegexOptions.None);
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Model/AbstractNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Xml.Serialization;
namespace CSharpSyntaxGenerator
{
public class AbstractNode : TreeType
{
public readonly List<Field> Fields = new List<Field>();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Xml.Serialization;
namespace CSharpSyntaxGenerator
{
public class AbstractNode : TreeType
{
public readonly List<Field> Fields = new List<Field>();
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Roslyn.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier<
Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers.GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateEqualsAndGetHashCodeFromMembers
{
[UseExportProvider]
public class GenerateEqualsAndGetHashCodeFromMembersTests
{
private class TestWithDialog : VerifyCS.Test
{
private static readonly TestComposition s_composition =
FeaturesTestCompositions.Features.AddParts(typeof(TestPickMembersService));
public ImmutableArray<string> MemberNames;
public Action<ImmutableArray<PickMembersOption>> OptionsCallback;
protected override Workspace CreateWorkspaceImpl()
{
// If we're a dialog test, then mixin our mock and initialize its values to the ones the test asked for.
var workspace = new AdhocWorkspace(s_composition.GetHostServices());
var service = (TestPickMembersService)workspace.Services.GetService<IPickMembersService>();
service.MemberNames = MemberNames;
service.OptionsCallback = OptionsCallback;
return workspace;
}
}
private static OptionsCollection PreferImplicitTypeWithInfo()
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, true, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Suggestion },
};
private static OptionsCollection PreferExplicitTypeWithInfo()
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.VarElsewhere, false, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, false, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, false, NotificationOption2.Suggestion },
};
internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id)
{
var option = options.FirstOrDefault(o => o.Id == id);
if (option != null)
{
option.Value = true;
}
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsSingleField()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
a == program.a;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsSingleField_PreferExplicitType()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
public override bool Equals(object obj)
{
Program program = obj as Program;
return program != null &&
a == program.a;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferExplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestReferenceIEquatable()
{
var code =
@"
using System;
using System.Collections.Generic;
class S : {|CS0535:IEquatable<S>|} { }
class Program
{
[|S a;|]
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
class S : {|CS0535:IEquatable<S>|} { }
class Program
{
S a;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
EqualityComparer<S>.Default.Equals(a, program.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestNullableReferenceIEquatable()
{
var code =
@"#nullable enable
using System;
using System.Collections.Generic;
class S : {|CS0535:IEquatable<S>|} { }
class Program
{
[|S? a;|]
}";
var fixedCode =
@"#nullable enable
using System;
using System.Collections.Generic;
class S : {|CS0535:IEquatable<S>|} { }
class Program
{
S? a;
public override bool Equals(object? obj)
{
return obj is Program program &&
EqualityComparer<S?>.Default.Equals(a, program.a);
}
public override int GetHashCode()
{
return -1757793268 + EqualityComparer<S?>.Default.GetHashCode(a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestValueIEquatable()
{
var code =
@"
using System;
using System.Collections.Generic;
struct S : {|CS0535:IEquatable<S>|} { }
class Program
{
[|S a;|]
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
struct S : {|CS0535:IEquatable<S>|} { }
class Program
{
S a;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
a.Equals(program.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsLongName()
{
var code =
@"using System.Collections.Generic;
class ReallyLongName
{
[|int a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class ReallyLongName
{
int a;
public override bool Equals(object obj)
{
var name = obj as ReallyLongName;
return name != null &&
a == name.a;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsKeywordName()
{
var code =
@"using System.Collections.Generic;
class ReallyLongLong
{
[|long a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class ReallyLongLong
{
long a;
public override bool Equals(object obj)
{
var @long = obj as ReallyLongLong;
return @long != null &&
a == @long.a;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsProperty()
{
var code =
@"using System.Collections.Generic;
class ReallyLongName
{
[|int a;
string B { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class ReallyLongName
{
int a;
string B { get; }
public override bool Equals(object obj)
{
var name = obj as ReallyLongName;
return name != null &&
a == name.a &&
B == name.B;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsBaseTypeWithNoEquals()
{
var code =
@"class Base
{
}
class Program : Base
{
[|int i;|]
}";
var fixedCode =
@"class Base
{
}
class Program : Base
{
int i;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i == program.i;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsBaseWithOverriddenEquals()
{
var code =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Program : Base
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Program : Base
{
int i;
string S { get; }
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
base.Equals(obj) &&
i == program.i &&
S == program.S;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsOverriddenDeepBase()
{
var code =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Middle : Base
{
}
class Program : Middle
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Middle : Base
{
}
class Program : Middle
{
int i;
string S { get; }
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
base.Equals(obj) &&
i == program.i &&
S == program.S;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStruct()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System.Collections.Generic;
struct ReallyLongName
{
[|int i;
string S { get; }|]
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : IEquatable<ReallyLongName>
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name && Equals(name);
}
public bool Equals(ReallyLongName other)
{
return i == other.i &&
S == other.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right)
{
return left.Equals(right);
}
public static bool operator !=(ReallyLongName left, ReallyLongName right)
{
return !(left == right);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStructCSharpLatest()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System.Collections.Generic;
struct ReallyLongName
{
[|int i;
string S { get; }|]
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : IEquatable<ReallyLongName>
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name && Equals(name);
}
public bool Equals(ReallyLongName other)
{
return i == other.i &&
S == other.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right)
{
return left.Equals(right);
}
public static bool operator !=(ReallyLongName left, ReallyLongName right)
{
return !(left == right);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStructAlreadyImplementsIEquatable()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System;
using System.Collections.Generic;
struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|}
{
[|int i;
string S { get; }|]
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|}
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name &&
i == name.i &&
S == name.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right)
{
return left.Equals(right);
}
public static bool operator !=(ReallyLongName left, ReallyLongName right)
{
return !(left == right);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStructAlreadyHasOperators()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System;
using System.Collections.Generic;
struct ReallyLongName
{
[|int i;
string S { get; }|]
public static bool operator ==(ReallyLongName left, ReallyLongName right) => false;
public static bool operator !=(ReallyLongName left, ReallyLongName right) => false;
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : IEquatable<ReallyLongName>
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name && Equals(name);
}
public bool Equals(ReallyLongName other)
{
return i == other.i &&
S == other.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right) => false;
public static bool operator !=(ReallyLongName left, ReallyLongName right) => false;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStructAlreadyImplementsIEquatableAndHasOperators()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System;
using System.Collections.Generic;
struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|}
{
[|int i;
string S { get; }|]
public static bool operator ==(ReallyLongName left, ReallyLongName right) => false;
public static bool operator !=(ReallyLongName left, ReallyLongName right) => false;
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|}
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name &&
i == name.i &&
S == name.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right) => false;
public static bool operator !=(ReallyLongName left, ReallyLongName right) => false;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsGenericType()
{
var code = @"
using System.Collections.Generic;
class Program<T>
{
[|int i;|]
}
";
var expected = @"
using System.Collections.Generic;
class Program<T>
{
int i;
public override bool Equals(object obj)
{
var program = obj as Program<T>;
return program != null &&
i == program.i;
}
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = expected,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsNullableContext()
{
await VerifyCS.VerifyRefactoringAsync(
@"#nullable enable
class Program
{
[|int a;|]
}",
@"#nullable enable
class Program
{
int a;
public override bool Equals(object? obj)
{
return obj is Program program &&
a == program.a;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSingleField1()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int i;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i == program.i;
}
public override int GetHashCode()
{
return 165851236 + i.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSingleField2()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int j;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int j;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
j == program.j;
}
public override int GetHashCode()
{
return 1424088837 + j.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeWithBaseHashCode1()
{
var code =
@"using System.Collections.Generic;
class Base {
public override int GetHashCode() => 0;
}
class Program : Base
{
[|int j;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base {
public override int GetHashCode() => 0;
}
class Program : Base
{
int j;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
j == program.j;
}
public override int GetHashCode()
{
var hashCode = 339610899;
hashCode = hashCode * -1521134295 + base.GetHashCode();
hashCode = hashCode * -1521134295 + j.GetHashCode();
return hashCode;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeWithBaseHashCode2()
{
var code =
@"using System.Collections.Generic;
class Base {
public override int GetHashCode() => 0;
}
class Program : Base
{
int j;
[||]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base {
public override int GetHashCode() => 0;
}
class Program : Base
{
int j;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null;
}
public override int GetHashCode()
{
return 624022166 + base.GetHashCode();
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
MemberNames = ImmutableArray<string>.Empty,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSingleField_CodeStyle1()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int i;
public override bool Equals(object obj)
{
Program program = obj as Program;
return program != null &&
i == program.i;
}
public override int GetHashCode() => 165851236 + i.GetHashCode();
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
Options =
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeTypeParameter()
{
var code =
@"using System.Collections.Generic;
class Program<T>
{
[|T i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program<T>
{
T i;
public override bool Equals(object obj)
{
var program = obj as Program<T>;
return program != null &&
EqualityComparer<T>.Default.Equals(i, program.i);
}
public override int GetHashCode()
{
return 165851236 + EqualityComparer<T>.Default.GetHashCode(i);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeGenericType()
{
var code =
@"using System.Collections.Generic;
class Program<T>
{
[|Program<T> i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program<T>
{
Program<T> i;
public override bool Equals(object obj)
{
var program = obj as Program<T>;
return program != null &&
EqualityComparer<Program<T>>.Default.Equals(i, program.i);
}
public override int GetHashCode()
{
return 165851236 + EqualityComparer<Program<T>>.Default.GetHashCode(i);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeMultipleMembers()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int i;
string S { get; }
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i == program.i &&
S == program.S;
}
public override int GetHashCode()
{
var hashCode = -538000506;
hashCode = hashCode * -1521134295 + i.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(S);
return hashCode;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestSmartTagText1()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|bool b;
HashSet<string> s;|]
public Program(bool b)
{
this.b = b;
}
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
bool b;
HashSet<string> s;
public Program(bool b)
{
this.b = b;
}
public override bool Equals(object obj)
{
return obj is Program program &&
b == program.b &&
EqualityComparer<HashSet<string>>.Default.Equals(s, program.s);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_object,
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_object, codeAction.Title),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestSmartTagText2()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|bool b;
HashSet<string> s;|]
public Program(bool b)
{
this.b = b;
}
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
bool b;
HashSet<string> s;
public Program(bool b)
{
this.b = b;
}
public override bool Equals(object obj)
{
return obj is Program program &&
b == program.b &&
EqualityComparer<HashSet<string>>.Default.Equals(s, program.s);
}
public override int GetHashCode()
{
int hashCode = -666523601;
hashCode = hashCode * -1521134295 + b.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<HashSet<string>>.Default.GetHashCode(s);
return hashCode;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode,
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestSmartTagText3()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|bool b;
HashSet<string> s;|]
public Program(bool b)
{
this.b = b;
}
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
bool b;
HashSet<string> s;
public Program(bool b)
{
this.b = b;
}
public override bool Equals(object obj)
{
return obj is Program program &&
b == program.b &&
EqualityComparer<HashSet<string>>.Default.Equals(s, program.s);
}
public override int GetHashCode()
{
int hashCode = -666523601;
hashCode = hashCode * -1521134295 + b.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<HashSet<string>>.Default.GetHashCode(s);
return hashCode;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode,
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Tuple_Disabled()
{
var code =
@"using System.Collections.Generic;
class C
{
[|{|CS8059:(int, string)|} a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class C
{
{|CS8059:(int, string)|} a;
public override bool Equals(object obj)
{
var c = obj as C;
return c != null &&
a.Equals(c.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Tuples_Equals()
{
var code =
@"using System.Collections.Generic;
class C
{
[|{|CS8059:(int, string)|} a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class C
{
{|CS8059:(int, string)|} a;
public override bool Equals(object obj)
{
var c = obj as C;
return c != null &&
a.Equals(c.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TupleWithNames_Equals()
{
var code =
@"using System.Collections.Generic;
class C
{
[|{|CS8059:(int x, string y)|} a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class C
{
{|CS8059:(int x, string y)|} a;
public override bool Equals(object obj)
{
var c = obj as C;
return c != null &&
a.Equals(c.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Tuple_HashCode()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|{|CS8059:(int, string)|} i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
{|CS8059:(int, string)|} i;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i.Equals(program.i);
}
public override int GetHashCode()
{
return 165851236 + i.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TupleWithNames_HashCode()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|{|CS8059:(int x, string y)|} i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
{|CS8059:(int x, string y)|} i;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i.Equals(program.i);
}
public override int GetHashCode()
{
return 165851236 + i.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task StructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|Bar bar;|]
}
struct Bar
{
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
Bar bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
EqualityComparer<Bar>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}
struct Bar
{
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task StructWithGetHashCodeOverride_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|Bar bar;|]
}
struct Bar
{
public override int GetHashCode() => 0;
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
Bar bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
EqualityComparer<Bar>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}
struct Bar
{
public override int GetHashCode() => 0;
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task NullableStructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|Bar? bar;|]
}
struct Bar
{
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
Bar? bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
EqualityComparer<Bar?>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}
struct Bar
{
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task StructTypeParameter_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo<TBar> where TBar : struct
{
[|TBar bar;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo<TBar> where TBar : struct
{
TBar bar;
public override bool Equals(object obj)
{
var foo = obj as Foo<TBar>;
return foo != null &&
EqualityComparer<TBar>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task NullableStructTypeParameter_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo<TBar> where TBar : struct
{
[|TBar? bar;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo<TBar> where TBar : struct
{
TBar? bar;
public override bool Equals(object obj)
{
var foo = obj as Foo<TBar>;
return foo != null &&
EqualityComparer<TBar?>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Enum_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|Bar bar;|]
}
enum Bar
{
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
Bar bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
bar == foo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}
enum Bar
{
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task PrimitiveValueType_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|ulong bar;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
ulong bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
bar == foo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialog1()
{
var code =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
[||]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
a == program.a &&
b == program.b;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = ImmutableArray.Create("a", "b"),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialog2()
{
var code =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
bool c;
[||]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
bool c;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
c == program.c &&
b == program.b;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = ImmutableArray.Create("c", "b"),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialog3()
{
var code =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
bool c;
[||]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
bool c;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = ImmutableArray<string>.Empty,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(17643, "https://github.com/dotnet/roslyn/issues/17643")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialogNoBackingField()
{
var code =
@"
class Program
{
public int F { get; set; }
[||]
}";
var fixedCode =
@"
class Program
{
public int F { get; set; }
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
F == program.F;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialogNoIndexer()
{
var code =
@"
class Program
{
public int P => 0;
public int this[int index] => 0;
[||]
}";
var fixedCode =
@"
class Program
{
public int P => 0;
public int this[int index] => 0;
public override bool Equals(object obj)
{
return obj is Program program &&
P == program.P;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
}.RunAsync();
}
[WorkItem(25707, "https://github.com/dotnet/roslyn/issues/25707")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialogNoSetterOnlyProperty()
{
var code =
@"
class Program
{
public int P => 0;
public int S { set { } }
[||]
}";
var fixedCode =
@"
class Program
{
public int P => 0;
public int S { set { } }
public override bool Equals(object obj)
{
return obj is Program program &&
P == program.P;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
}.RunAsync();
}
[WorkItem(41958, "https://github.com/dotnet/roslyn/issues/41958")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialogInheritedMembers()
{
var code =
@"
class Base
{
public int C { get; set; }
}
class Middle : Base
{
public int B { get; set; }
}
class Derived : Middle
{
public int A { get; set; }
[||]
}";
var fixedCode =
@"
class Base
{
public int C { get; set; }
}
class Middle : Base
{
public int B { get; set; }
}
class Derived : Middle
{
public int A { get; set; }
public override bool Equals(object obj)
{
return obj is Derived derived &&
C == derived.C &&
B == derived.B &&
A == derived.A;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateOperators1()
{
var code =
@"
using System.Collections.Generic;
class Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System.Collections.Generic;
class Program
{
public string s;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
s == program.s;
}
public static bool operator ==(Program left, Program right)
{
return EqualityComparer<Program>.Default.Equals(left, right);
}
public static bool operator !=(Program left, Program right)
{
return !(left == right);
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateOperators2()
{
var code =
@"
using System.Collections.Generic;
class Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System.Collections.Generic;
class Program
{
public string s;
public override bool Equals(object obj)
{
Program program = obj as Program;
return program != null &&
s == program.s;
}
public static bool operator ==(Program left, Program right) => EqualityComparer<Program>.Default.Equals(left, right);
public static bool operator !=(Program left, Program right) => !(left == right);
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.CSharp6,
Options =
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
},
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateOperators3()
{
var code =
@"
using System.Collections.Generic;
class Program
{
public string s;
[||]
public static bool operator {|CS0216:==|}(Program left, Program right) => true;
}";
var fixedCode =
@"
using System.Collections.Generic;
class Program
{
public string s;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
s == program.s;
}
public static bool operator {|CS0216:==|}(Program left, Program right) => true;
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId)),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateOperators4()
{
var code =
@"
using System.Collections.Generic;
struct Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System.Collections.Generic;
struct Program
{
public string s;
public override bool Equals(object obj)
{
if (!(obj is Program))
{
return false;
}
var program = (Program)obj;
return s == program.s;
}
public static bool operator ==(Program left, Program right)
{
return left.Equals(right);
}
public static bool operator !=(Program left, Program right)
{
return !(left == right);
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateLiftedOperators()
{
var code =
@"
using System;
using System.Collections.Generic;
class Foo
{
[|public bool? BooleanValue { get; }
public decimal? DecimalValue { get; }
public Bar? EnumValue { get; }
public DateTime? DateTimeValue { get; }|]
}
enum Bar
{
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
class Foo
{
public bool? BooleanValue { get; }
public decimal? DecimalValue { get; }
public Bar? EnumValue { get; }
public DateTime? DateTimeValue { get; }
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
BooleanValue == foo.BooleanValue &&
DecimalValue == foo.DecimalValue &&
EnumValue == foo.EnumValue &&
DateTimeValue == foo.DateTimeValue;
}
}
enum Bar
{
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task LiftedOperatorIsNotUsedWhenDirectOperatorWouldNotBeUsed()
{
var code =
@"
using System;
using System.Collections.Generic;
class Foo
{
[|public Bar Value { get; }
public Bar? NullableValue { get; }|]
}
struct Bar : IEquatable<Bar>
{
private readonly int value;
public override bool Equals(object obj) => false;
public bool Equals(Bar other) => value == other.value;
public override int GetHashCode() => -1584136870 + value.GetHashCode();
public static bool operator ==(Bar left, Bar right) => left.Equals(right);
public static bool operator !=(Bar left, Bar right) => !(left == right);
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
class Foo
{
public Bar Value { get; }
public Bar? NullableValue { get; }
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
Value.Equals(foo.Value) &&
EqualityComparer<Bar?>.Default.Equals(NullableValue, foo.NullableValue);
}
}
struct Bar : IEquatable<Bar>
{
private readonly int value;
public override bool Equals(object obj) => false;
public bool Equals(Bar other) => value == other.value;
public override int GetHashCode() => -1584136870 + value.GetHashCode();
public static bool operator ==(Bar left, Bar right) => left.Equals(right);
public static bool operator !=(Bar left, Bar right) => !(left == right);
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnStruct()
{
var code =
@"
using System.Collections.Generic;
struct Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
struct Program : IEquatable<Program>
{
public string s;
public override bool Equals(object obj)
{
return obj is Program && Equals((Program)obj);
}
public bool Equals(Program other)
{
return s == other.s;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
[WorkItem(25708, "https://github.com/dotnet/roslyn/issues/25708")]
public async Task TestOverrideEqualsOnRefStructReturnsFalse()
{
var code =
@"
ref struct Program
{
public string s;
[||]
}";
var fixedCode =
@"
ref struct Program
{
public string s;
public override bool Equals(object obj)
{
return false;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
[WorkItem(25708, "https://github.com/dotnet/roslyn/issues/25708")]
public async Task TestImplementIEquatableOnRefStructSkipsIEquatable()
{
var code =
@"
ref struct Program
{
public string s;
[||]
}";
var fixedCode =
@"
ref struct Program
{
public string s;
public override bool Equals(object obj)
{
return false;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
// We are forcefully enabling the ImplementIEquatable option, as that is our way
// to test that the option does nothing. The VS mode will ensure if the option
// is not available it will not be shown.
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnStructInNullableContextWithUnannotatedMetadata()
{
var code =
@"#nullable enable
struct Foo
{
public int Bar { get; }
[||]
}";
var fixedCode =
@"#nullable enable
using System;
struct Foo : IEquatable<Foo>
{
public int Bar { get; }
public override bool Equals(object? obj)
{
return obj is Foo foo && Equals(foo);
}
public bool Equals(Foo other)
{
return Bar == other.Bar;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnStructInNullableContextWithAnnotatedMetadata()
{
var code =
@"
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
struct Foo
{
public bool Bar { get; }
[||]
}
";
var fixedCode =
@"
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
struct Foo : IEquatable<Foo>
{
public bool Bar { get; }
public override bool Equals(object? obj)
{
return obj is Foo foo && Equals(foo);
}
public bool Equals(Foo other)
{
return Bar == other.Bar;
}
}
";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnClass()
{
var code =
@"
using System.Collections.Generic;
class Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
class Program : IEquatable<Program>
{
public string s;
public override bool Equals(object obj)
{
return Equals(obj as Program);
}
public bool Equals(Program other)
{
return other != null &&
s == other.s;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnClassInNullableContextWithUnannotatedMetadata()
{
var code =
@"#nullable enable
class Foo
{
public int Bar { get; }
[||]
}";
var fixedCode =
@"#nullable enable
using System;
class Foo : IEquatable<Foo?>
{
public int Bar { get; }
public override bool Equals(object? obj)
{
return Equals(obj as Foo);
}
public bool Equals(Foo? other)
{
return other != null &&
Bar == other.Bar;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnClassInNullableContextWithAnnotatedMetadata()
{
var code =
@"
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
class Foo
{
public bool Bar { get; }
[||]
}
";
var fixedCode =
@"
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
class Foo : IEquatable<Foo?>
{
public bool Bar { get; }
public override bool Equals(object? obj)
{
return Equals(obj as Foo);
}
public bool Equals(Foo? other)
{
return other != null &&
Bar == other.Bar;
}
}
";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestDoNotOfferIEquatableIfTypeAlreadyImplementsIt()
{
var code =
@"
using System.Collections.Generic;
class Program : {|CS0535:System.IEquatable<Program>|}
{
public string s;
[||]
}";
var fixedCode =
@"
using System.Collections.Generic;
class Program : {|CS0535:System.IEquatable<Program>|}
{
public string s;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
s == program.s;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId)),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestMissingReferences1()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp6,
CodeActionIndex = 1,
TestState =
{
Sources =
{
@"public class Class1
{
[|int i;|]
public void F()
{
}
}",
},
ExpectedDiagnostics =
{
// /0/Test0.cs(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(1, 14, 1, 20).WithArguments("System.Object"),
// /0/Test0.cs(1,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments
DiagnosticResult.CompilerError("CS1729").WithSpan(1, 14, 1, 20).WithArguments("object", "0"),
// /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(3, 5, 3, 8).WithArguments("System.Int32"),
// /0/Test0.cs(5,12): error CS0518: Predefined type 'System.Void' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(5, 12, 5, 16).WithArguments("System.Void"),
},
},
FixedState =
{
Sources = {
@"public class Class1
{
int i;
public override System.Boolean Equals(System.Object obj)
{
Class1 @class = obj as Class1;
return @class != null &&
i == @class.i;
}
public void F()
{
}
public override System.Int32 GetHashCode()
{
return 165851236 + EqualityComparer<System.Int32>.Default.GetHashCode(i);
}
}",
},
ExpectedDiagnostics =
{
// /0/Test0.cs(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(1, 14, 1, 20).WithArguments("System.Object"),
// /0/Test0.cs(1,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments
DiagnosticResult.CompilerError("CS1729").WithSpan(1, 14, 1, 20).WithArguments("object", "0"),
// /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(3, 5, 3, 8).WithArguments("System.Int32"),
// /0/Test0.cs(5,21): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(5, 21, 5, 27).WithArguments("System.Object"),
// /0/Test0.cs(5,28): error CS1069: The type name 'Boolean' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.
DiagnosticResult.CompilerError("CS1069").WithSpan(5, 28, 5, 35).WithArguments("Boolean", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
// /0/Test0.cs(5,43): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(5, 43, 5, 49).WithArguments("System.Object"),
// /0/Test0.cs(5,50): error CS1069: The type name 'Object' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.
DiagnosticResult.CompilerError("CS1069").WithSpan(5, 50, 5, 56).WithArguments("Object", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
// /0/Test0.cs(7,9): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(7, 9, 7, 15).WithArguments("System.Object"),
// /0/Test0.cs(7,32): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(7, 32, 7, 38).WithArguments("System.Object"),
// /0/Test0.cs(8,16): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(8, 16, 8, 30).WithArguments("System.Object"),
// /0/Test0.cs(9,16): error CS0518: Predefined type 'System.Boolean' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(9, 16, 9, 29).WithArguments("System.Boolean"),
// /0/Test0.cs(12,12): error CS0518: Predefined type 'System.Void' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(12, 12, 12, 16).WithArguments("System.Void"),
// /0/Test0.cs(16,21): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(16, 21, 16, 27).WithArguments("System.Object"),
// /0/Test0.cs(16,28): error CS1069: The type name 'Int32' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.
DiagnosticResult.CompilerError("CS1069").WithSpan(16, 28, 16, 33).WithArguments("Int32", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
// /0/Test0.cs(16,34): error CS0115: 'Class1.GetHashCode()': no suitable method found to override
DiagnosticResult.CompilerError("CS0115").WithSpan(16, 34, 16, 45).WithArguments("Class1.GetHashCode()"),
// /0/Test0.cs(18,16): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(18, 16, 18, 25).WithArguments("System.Int32"),
// /0/Test0.cs(18,28): error CS0103: The name 'EqualityComparer' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithSpan(18, 28, 18, 58).WithArguments("EqualityComparer"),
// /0/Test0.cs(18,28): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(18, 28, 18, 58).WithArguments("System.Object"),
// /0/Test0.cs(18,45): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(18, 45, 18, 51).WithArguments("System.Object"),
// /0/Test0.cs(18,52): error CS1069: The type name 'Int32' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.
DiagnosticResult.CompilerError("CS1069").WithSpan(18, 52, 18, 57).WithArguments("Int32", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
},
},
ReferenceAssemblies = ReferenceAssemblies.Default.WithAssemblies(ImmutableArray<string>.Empty),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeInCheckedContext()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int i;
string S { get; }
public override bool Equals(object obj)
{
Program program = obj as Program;
return program != null &&
i == program.i &&
S == program.S;
}
public override int GetHashCode()
{
unchecked
{
int hashCode = -538000506;
hashCode = hashCode * -1521134295 + i.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(S);
return hashCode;
}
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
SolutionTransforms =
{
(solution, projectId) =>
{
var compilationOptions = solution.GetRequiredProject(projectId).CompilationOptions;
return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOverflowChecks(true));
},
},
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeStruct()
{
var code =
@"using System.Collections.Generic;
struct S
{
[|int j;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
struct S : IEquatable<S>
{
int j;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j;
}
public override int GetHashCode()
{
return 1424088837 + j.GetHashCode();
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSystemHashCodeOneMember()
{
var code =
@"using System.Collections.Generic;
namespace System { public struct HashCode { } }
struct S
{
[|int j;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
namespace System { public struct HashCode { } }
struct S : IEquatable<S>
{
int j;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j;
}
public override int GetHashCode()
{
return HashCode.Combine(j);
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(21,25): error CS0117: 'HashCode' does not contain a definition for 'Combine'
DiagnosticResult.CompilerError("CS0117").WithSpan(21, 25, 21, 32).WithArguments("System.HashCode", "Combine"),
},
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(37297, "https://github.com/dotnet/roslyn/issues/37297")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPublicSystemHashCodeOtherProject()
{
var publicHashCode =
@"using System.Collections.Generic;
namespace System { public struct HashCode { } }";
var code =
@"struct S
{
[|int j;|]
}";
var fixedCode =
@"using System;
struct S : IEquatable<S>
{
int j;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j;
}
public override int GetHashCode()
{
return HashCode.Combine(j);
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestState =
{
AdditionalProjects =
{
["P1"] =
{
Sources = { ("HashCode.cs", publicHashCode) },
},
},
Sources = { code },
AdditionalProjectReferences = { "P1" },
},
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(19,25): error CS0117: 'HashCode' does not contain a definition for 'Combine'
DiagnosticResult.CompilerError("CS0117").WithSpan(19, 25, 19, 32).WithArguments("System.HashCode", "Combine"),
},
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(37297, "https://github.com/dotnet/roslyn/issues/37297")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestInternalSystemHashCode()
{
var internalHashCode =
@"using System.Collections.Generic;
namespace System { internal struct HashCode { } }";
var code =
@"struct S
{
[|int j;|]
}";
var fixedCode =
@"using System;
struct S : IEquatable<S>
{
int j;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j;
}
public override int GetHashCode()
{
return 1424088837 + j.GetHashCode();
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestState =
{
AdditionalProjects =
{
["P1"] =
{
Sources = { ("HashCode.cs", internalHashCode) },
},
},
Sources = { code },
AdditionalProjectReferences = { "P1" },
},
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSystemHashCodeEightMembers()
{
var code =
@"using System.Collections.Generic;
namespace System { public struct HashCode { } }
struct S
{
[|int j, k, l, m, n, o, p, q;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
namespace System { public struct HashCode { } }
struct S : IEquatable<S>
{
int j, k, l, m, n, o, p, q;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j &&
k == other.k &&
l == other.l &&
m == other.m &&
n == other.n &&
o == other.o &&
p == other.p &&
q == other.q;
}
public override int GetHashCode()
{
return HashCode.Combine(j, k, l, m, n, o, p, q);
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(28,25): error CS0117: 'HashCode' does not contain a definition for 'Combine'
DiagnosticResult.CompilerError("CS0117").WithSpan(28, 25, 28, 32).WithArguments("System.HashCode", "Combine"),
},
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSystemHashCodeNineMembers()
{
var code =
@"using System.Collections.Generic;
namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } }
struct S
{
[|int j, k, l, m, n, o, p, q, r;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } }
struct S : IEquatable<S>
{
int j, k, l, m, n, o, p, q, r;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j &&
k == other.k &&
l == other.l &&
m == other.m &&
n == other.n &&
o == other.o &&
p == other.p &&
q == other.q &&
r == other.r;
}
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(j);
hash.Add(k);
hash.Add(l);
hash.Add(m);
hash.Add(n);
hash.Add(o);
hash.Add(p);
hash.Add(q);
hash.Add(r);
return hash.ToHashCode();
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSystemHashCodeNineMembers_Explicit()
{
var code =
@"using System.Collections.Generic;
namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } }
struct S
{
[|int j, k, l, m, n, o, p, q, r;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } }
struct S : IEquatable<S>
{
int j, k, l, m, n, o, p, q, r;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j &&
k == other.k &&
l == other.l &&
m == other.m &&
n == other.n &&
o == other.o &&
p == other.p &&
q == other.q &&
r == other.r;
}
public override int GetHashCode()
{
HashCode hash = new HashCode();
hash.Add(j);
hash.Add(k);
hash.Add(l);
hash.Add(m);
hash.Add(n);
hash.Add(o);
hash.Add(p);
hash.Add(q);
hash.Add(r);
return hash.ToHashCode();
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferExplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsSingleField_Patterns()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System.Collections.Generic;
class Program
{
[|int a;|]
}",
@"using System.Collections.Generic;
class Program
{
int a;
public override bool Equals(object obj)
{
return obj is Program program &&
a == program.a;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsSingleFieldInStruct_Patterns()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System.Collections.Generic;
struct Program
{
[|int a;|]
}",
@"using System;
using System.Collections.Generic;
struct Program : IEquatable<Program>
{
int a;
public override bool Equals(object obj)
{
return obj is Program program && Equals(program);
}
public bool Equals(Program other)
{
return a == other.a;
}
public static bool operator ==(Program left, Program right)
{
return left.Equals(right);
}
public static bool operator !=(Program left, Program right)
{
return !(left == right);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsBaseWithOverriddenEquals_Patterns()
{
var code =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Program : Base
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Program : Base
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is Program program &&
base.Equals(obj) &&
i == program.i &&
S == program.S;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialSelection()
{
var code =
@"using System.Collections.Generic;
class Program
{
int [|a|];
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
}.RunAsync();
}
[WorkItem(40053, "https://github.com/dotnet/roslyn/issues/40053")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualityOperatorsNullableAnnotationWithReferenceType()
{
var code =
@"
#nullable enable
using System;
namespace N
{
public class C[||]
{
public int X;
}
}";
var fixedCode =
@"
#nullable enable
using System;
using System.Collections.Generic;
namespace N
{
public class C
{
public int X;
public override bool Equals(object? obj)
{
return obj is C c &&
X == c.X;
}
public static bool operator ==(C? left, C? right)
{
return EqualityComparer<C>.Default.Equals(left, right);
}
public static bool operator !=(C? left, C? right)
{
return !(left == right);
}
}
}";
await new TestWithDialog
{
TestCode = code,
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(20,55): error CS8604: Possible null reference argument for parameter 'x' in 'bool EqualityComparer<C>.Equals(C x, C y)'.
DiagnosticResult.CompilerError("CS8604").WithSpan(20, 55, 20, 59).WithArguments("x", "bool EqualityComparer<C>.Equals(C x, C y)"),
// /0/Test0.cs(20,61): error CS8604: Possible null reference argument for parameter 'y' in 'bool EqualityComparer<C>.Equals(C x, C y)'.
DiagnosticResult.CompilerError("CS8604").WithSpan(20, 61, 20, 66).WithArguments("y", "bool EqualityComparer<C>.Equals(C x, C y)"),
},
},
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.Default,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(40053, "https://github.com/dotnet/roslyn/issues/40053")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualityOperatorsNullableAnnotationWithValueType()
{
var code =
@"
#nullable enable
using System;
namespace N
{
public struct C[||]
{
public int X;
}
}";
var fixedCode =
@"
#nullable enable
using System;
namespace N
{
public struct C
{
public int X;
public override bool Equals(object? obj)
{
return obj is C c &&
X == c.X;
}
public static bool operator ==(C left, C right)
{
return left.Equals(right);
}
public static bool operator !=(C left, C right)
{
return !(left == right);
}
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.Default,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialTypes1()
{
await new TestWithDialog
{
TestState =
{
Sources =
{
@"partial class Goo
{
int bar;
[||]
}",
@"partial class Goo
{
}",
},
},
FixedState =
{
Sources =
{
@"partial class Goo
{
int bar;
public override bool Equals(object obj)
{
return obj is Goo goo &&
bar == goo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}",
@"partial class Goo
{
}",
},
},
MemberNames = ImmutableArray.Create("bar"),
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialTypes2()
{
await new TestWithDialog
{
TestState =
{
Sources =
{
@"partial class Goo
{
int bar;
}",
@"partial class Goo
{
[||]
}",
},
},
FixedState =
{
Sources =
{
@"partial class Goo
{
int bar;
}",
@"partial class Goo
{
public override bool Equals(object obj)
{
return obj is Goo goo &&
bar == goo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}",
},
},
MemberNames = ImmutableArray.Create("bar"),
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialTypes3()
{
await new TestWithDialog
{
TestState =
{
Sources =
{
@"partial class Goo
{
[||]
}",
@"partial class Goo
{
int bar;
}",
},
},
FixedState =
{
Sources =
{
@"partial class Goo
{
public override bool Equals(object obj)
{
return obj is Goo goo &&
bar == goo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}",
@"partial class Goo
{
int bar;
}",
},
},
MemberNames = ImmutableArray.Create("bar"),
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialTypes4()
{
await new TestWithDialog
{
TestState =
{
Sources =
{
@"partial class Goo
{
}",
@"partial class Goo
{
int bar;
[||]
}",
},
},
FixedState =
{
Sources =
{
@"partial class Goo
{
}",
@"partial class Goo
{
int bar;
public override bool Equals(object obj)
{
return obj is Goo goo &&
bar == goo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}",
},
},
MemberNames = ImmutableArray.Create("bar"),
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(43290, "https://github.com/dotnet/roslyn/issues/43290")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestAbstractBase()
{
var code =
@"
#nullable enable
namespace System { public struct HashCode { } }
abstract class Base
{
public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
}
class {|CS0534:{|CS0534:Derived|}|} : Base
{
[|public int P { get; }|]
}";
var fixedCode =
@"
#nullable enable
using System;
namespace System { public struct HashCode { } }
abstract class Base
{
public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
}
class Derived : Base
{
public int P { get; }
public override bool Equals(object? obj)
{
return obj is Derived derived &&
P == derived.P;
}
public override int GetHashCode()
{
return HashCode.Combine(P);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(23,25): error CS0117: 'HashCode' does not contain a definition for 'Combine'
DiagnosticResult.CompilerError("CS0117").WithSpan(26, 25, 26, 32).WithArguments("System.HashCode", "Combine"),
},
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.Default,
}.RunAsync();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Roslyn.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier<
Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers.GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateEqualsAndGetHashCodeFromMembers
{
[UseExportProvider]
public class GenerateEqualsAndGetHashCodeFromMembersTests
{
private class TestWithDialog : VerifyCS.Test
{
private static readonly TestComposition s_composition =
FeaturesTestCompositions.Features.AddParts(typeof(TestPickMembersService));
public ImmutableArray<string> MemberNames;
public Action<ImmutableArray<PickMembersOption>> OptionsCallback;
protected override Workspace CreateWorkspaceImpl()
{
// If we're a dialog test, then mixin our mock and initialize its values to the ones the test asked for.
var workspace = new AdhocWorkspace(s_composition.GetHostServices());
var service = (TestPickMembersService)workspace.Services.GetService<IPickMembersService>();
service.MemberNames = MemberNames;
service.OptionsCallback = OptionsCallback;
return workspace;
}
}
private static OptionsCollection PreferImplicitTypeWithInfo()
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, true, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Suggestion },
};
private static OptionsCollection PreferExplicitTypeWithInfo()
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.VarElsewhere, false, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, false, NotificationOption2.Suggestion },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, false, NotificationOption2.Suggestion },
};
internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id)
{
var option = options.FirstOrDefault(o => o.Id == id);
if (option != null)
{
option.Value = true;
}
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsSingleField()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
a == program.a;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsSingleField_PreferExplicitType()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
public override bool Equals(object obj)
{
Program program = obj as Program;
return program != null &&
a == program.a;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferExplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestReferenceIEquatable()
{
var code =
@"
using System;
using System.Collections.Generic;
class S : {|CS0535:IEquatable<S>|} { }
class Program
{
[|S a;|]
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
class S : {|CS0535:IEquatable<S>|} { }
class Program
{
S a;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
EqualityComparer<S>.Default.Equals(a, program.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestNullableReferenceIEquatable()
{
var code =
@"#nullable enable
using System;
using System.Collections.Generic;
class S : {|CS0535:IEquatable<S>|} { }
class Program
{
[|S? a;|]
}";
var fixedCode =
@"#nullable enable
using System;
using System.Collections.Generic;
class S : {|CS0535:IEquatable<S>|} { }
class Program
{
S? a;
public override bool Equals(object? obj)
{
return obj is Program program &&
EqualityComparer<S?>.Default.Equals(a, program.a);
}
public override int GetHashCode()
{
return -1757793268 + EqualityComparer<S?>.Default.GetHashCode(a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestValueIEquatable()
{
var code =
@"
using System;
using System.Collections.Generic;
struct S : {|CS0535:IEquatable<S>|} { }
class Program
{
[|S a;|]
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
struct S : {|CS0535:IEquatable<S>|} { }
class Program
{
S a;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
a.Equals(program.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsLongName()
{
var code =
@"using System.Collections.Generic;
class ReallyLongName
{
[|int a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class ReallyLongName
{
int a;
public override bool Equals(object obj)
{
var name = obj as ReallyLongName;
return name != null &&
a == name.a;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsKeywordName()
{
var code =
@"using System.Collections.Generic;
class ReallyLongLong
{
[|long a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class ReallyLongLong
{
long a;
public override bool Equals(object obj)
{
var @long = obj as ReallyLongLong;
return @long != null &&
a == @long.a;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsProperty()
{
var code =
@"using System.Collections.Generic;
class ReallyLongName
{
[|int a;
string B { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class ReallyLongName
{
int a;
string B { get; }
public override bool Equals(object obj)
{
var name = obj as ReallyLongName;
return name != null &&
a == name.a &&
B == name.B;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsBaseTypeWithNoEquals()
{
var code =
@"class Base
{
}
class Program : Base
{
[|int i;|]
}";
var fixedCode =
@"class Base
{
}
class Program : Base
{
int i;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i == program.i;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsBaseWithOverriddenEquals()
{
var code =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Program : Base
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Program : Base
{
int i;
string S { get; }
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
base.Equals(obj) &&
i == program.i &&
S == program.S;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsOverriddenDeepBase()
{
var code =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Middle : Base
{
}
class Program : Middle
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Middle : Base
{
}
class Program : Middle
{
int i;
string S { get; }
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
base.Equals(obj) &&
i == program.i &&
S == program.S;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStruct()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System.Collections.Generic;
struct ReallyLongName
{
[|int i;
string S { get; }|]
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : IEquatable<ReallyLongName>
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name && Equals(name);
}
public bool Equals(ReallyLongName other)
{
return i == other.i &&
S == other.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right)
{
return left.Equals(right);
}
public static bool operator !=(ReallyLongName left, ReallyLongName right)
{
return !(left == right);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStructCSharpLatest()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System.Collections.Generic;
struct ReallyLongName
{
[|int i;
string S { get; }|]
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : IEquatable<ReallyLongName>
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name && Equals(name);
}
public bool Equals(ReallyLongName other)
{
return i == other.i &&
S == other.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right)
{
return left.Equals(right);
}
public static bool operator !=(ReallyLongName left, ReallyLongName right)
{
return !(left == right);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStructAlreadyImplementsIEquatable()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System;
using System.Collections.Generic;
struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|}
{
[|int i;
string S { get; }|]
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|}
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name &&
i == name.i &&
S == name.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right)
{
return left.Equals(right);
}
public static bool operator !=(ReallyLongName left, ReallyLongName right)
{
return !(left == right);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStructAlreadyHasOperators()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System;
using System.Collections.Generic;
struct ReallyLongName
{
[|int i;
string S { get; }|]
public static bool operator ==(ReallyLongName left, ReallyLongName right) => false;
public static bool operator !=(ReallyLongName left, ReallyLongName right) => false;
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : IEquatable<ReallyLongName>
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name && Equals(name);
}
public bool Equals(ReallyLongName other)
{
return i == other.i &&
S == other.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right) => false;
public static bool operator !=(ReallyLongName left, ReallyLongName right) => false;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStructAlreadyImplementsIEquatableAndHasOperators()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System;
using System.Collections.Generic;
struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|}
{
[|int i;
string S { get; }|]
public static bool operator ==(ReallyLongName left, ReallyLongName right) => false;
public static bool operator !=(ReallyLongName left, ReallyLongName right) => false;
}",
@"using System;
using System.Collections.Generic;
struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|}
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is ReallyLongName name &&
i == name.i &&
S == name.S;
}
public static bool operator ==(ReallyLongName left, ReallyLongName right) => false;
public static bool operator !=(ReallyLongName left, ReallyLongName right) => false;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsGenericType()
{
var code = @"
using System.Collections.Generic;
class Program<T>
{
[|int i;|]
}
";
var expected = @"
using System.Collections.Generic;
class Program<T>
{
int i;
public override bool Equals(object obj)
{
var program = obj as Program<T>;
return program != null &&
i == program.i;
}
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = expected,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsNullableContext()
{
await VerifyCS.VerifyRefactoringAsync(
@"#nullable enable
class Program
{
[|int a;|]
}",
@"#nullable enable
class Program
{
int a;
public override bool Equals(object? obj)
{
return obj is Program program &&
a == program.a;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSingleField1()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int i;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i == program.i;
}
public override int GetHashCode()
{
return 165851236 + i.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSingleField2()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int j;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int j;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
j == program.j;
}
public override int GetHashCode()
{
return 1424088837 + j.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeWithBaseHashCode1()
{
var code =
@"using System.Collections.Generic;
class Base {
public override int GetHashCode() => 0;
}
class Program : Base
{
[|int j;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base {
public override int GetHashCode() => 0;
}
class Program : Base
{
int j;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
j == program.j;
}
public override int GetHashCode()
{
var hashCode = 339610899;
hashCode = hashCode * -1521134295 + base.GetHashCode();
hashCode = hashCode * -1521134295 + j.GetHashCode();
return hashCode;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeWithBaseHashCode2()
{
var code =
@"using System.Collections.Generic;
class Base {
public override int GetHashCode() => 0;
}
class Program : Base
{
int j;
[||]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base {
public override int GetHashCode() => 0;
}
class Program : Base
{
int j;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null;
}
public override int GetHashCode()
{
return 624022166 + base.GetHashCode();
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
MemberNames = ImmutableArray<string>.Empty,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSingleField_CodeStyle1()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int i;
public override bool Equals(object obj)
{
Program program = obj as Program;
return program != null &&
i == program.i;
}
public override int GetHashCode() => 165851236 + i.GetHashCode();
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
Options =
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeTypeParameter()
{
var code =
@"using System.Collections.Generic;
class Program<T>
{
[|T i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program<T>
{
T i;
public override bool Equals(object obj)
{
var program = obj as Program<T>;
return program != null &&
EqualityComparer<T>.Default.Equals(i, program.i);
}
public override int GetHashCode()
{
return 165851236 + EqualityComparer<T>.Default.GetHashCode(i);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeGenericType()
{
var code =
@"using System.Collections.Generic;
class Program<T>
{
[|Program<T> i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program<T>
{
Program<T> i;
public override bool Equals(object obj)
{
var program = obj as Program<T>;
return program != null &&
EqualityComparer<Program<T>>.Default.Equals(i, program.i);
}
public override int GetHashCode()
{
return 165851236 + EqualityComparer<Program<T>>.Default.GetHashCode(i);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeMultipleMembers()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int i;
string S { get; }
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i == program.i &&
S == program.S;
}
public override int GetHashCode()
{
var hashCode = -538000506;
hashCode = hashCode * -1521134295 + i.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(S);
return hashCode;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestSmartTagText1()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|bool b;
HashSet<string> s;|]
public Program(bool b)
{
this.b = b;
}
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
bool b;
HashSet<string> s;
public Program(bool b)
{
this.b = b;
}
public override bool Equals(object obj)
{
return obj is Program program &&
b == program.b &&
EqualityComparer<HashSet<string>>.Default.Equals(s, program.s);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_object,
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_object, codeAction.Title),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestSmartTagText2()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|bool b;
HashSet<string> s;|]
public Program(bool b)
{
this.b = b;
}
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
bool b;
HashSet<string> s;
public Program(bool b)
{
this.b = b;
}
public override bool Equals(object obj)
{
return obj is Program program &&
b == program.b &&
EqualityComparer<HashSet<string>>.Default.Equals(s, program.s);
}
public override int GetHashCode()
{
int hashCode = -666523601;
hashCode = hashCode * -1521134295 + b.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<HashSet<string>>.Default.GetHashCode(s);
return hashCode;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode,
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestSmartTagText3()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|bool b;
HashSet<string> s;|]
public Program(bool b)
{
this.b = b;
}
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
bool b;
HashSet<string> s;
public Program(bool b)
{
this.b = b;
}
public override bool Equals(object obj)
{
return obj is Program program &&
b == program.b &&
EqualityComparer<HashSet<string>>.Default.Equals(s, program.s);
}
public override int GetHashCode()
{
int hashCode = -666523601;
hashCode = hashCode * -1521134295 + b.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<HashSet<string>>.Default.GetHashCode(s);
return hashCode;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode,
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Tuple_Disabled()
{
var code =
@"using System.Collections.Generic;
class C
{
[|{|CS8059:(int, string)|} a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class C
{
{|CS8059:(int, string)|} a;
public override bool Equals(object obj)
{
var c = obj as C;
return c != null &&
a.Equals(c.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Tuples_Equals()
{
var code =
@"using System.Collections.Generic;
class C
{
[|{|CS8059:(int, string)|} a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class C
{
{|CS8059:(int, string)|} a;
public override bool Equals(object obj)
{
var c = obj as C;
return c != null &&
a.Equals(c.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TupleWithNames_Equals()
{
var code =
@"using System.Collections.Generic;
class C
{
[|{|CS8059:(int x, string y)|} a;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class C
{
{|CS8059:(int x, string y)|} a;
public override bool Equals(object obj)
{
var c = obj as C;
return c != null &&
a.Equals(c.a);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Tuple_HashCode()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|{|CS8059:(int, string)|} i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
{|CS8059:(int, string)|} i;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i.Equals(program.i);
}
public override int GetHashCode()
{
return 165851236 + i.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TupleWithNames_HashCode()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|{|CS8059:(int x, string y)|} i;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
{|CS8059:(int x, string y)|} i;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
i.Equals(program.i);
}
public override int GetHashCode()
{
return 165851236 + i.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task StructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|Bar bar;|]
}
struct Bar
{
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
Bar bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
EqualityComparer<Bar>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}
struct Bar
{
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task StructWithGetHashCodeOverride_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|Bar bar;|]
}
struct Bar
{
public override int GetHashCode() => 0;
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
Bar bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
EqualityComparer<Bar>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}
struct Bar
{
public override int GetHashCode() => 0;
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task NullableStructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|Bar? bar;|]
}
struct Bar
{
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
Bar? bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
EqualityComparer<Bar?>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}
struct Bar
{
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task StructTypeParameter_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo<TBar> where TBar : struct
{
[|TBar bar;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo<TBar> where TBar : struct
{
TBar bar;
public override bool Equals(object obj)
{
var foo = obj as Foo<TBar>;
return foo != null &&
EqualityComparer<TBar>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task NullableStructTypeParameter_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo<TBar> where TBar : struct
{
[|TBar? bar;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo<TBar> where TBar : struct
{
TBar? bar;
public override bool Equals(object obj)
{
var foo = obj as Foo<TBar>;
return foo != null &&
EqualityComparer<TBar?>.Default.Equals(bar, foo.bar);
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Enum_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|Bar bar;|]
}
enum Bar
{
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
Bar bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
bar == foo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}
enum Bar
{
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task PrimitiveValueType_ShouldCallGetHashCodeDirectly()
{
var code =
@"using System.Collections.Generic;
class Foo
{
[|ulong bar;|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Foo
{
ulong bar;
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
bar == foo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialog1()
{
var code =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
[||]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
a == program.a &&
b == program.b;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = ImmutableArray.Create("a", "b"),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialog2()
{
var code =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
bool c;
[||]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
bool c;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
c == program.c &&
b == program.b;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = ImmutableArray.Create("c", "b"),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialog3()
{
var code =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
bool c;
[||]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int a;
string b;
bool c;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = ImmutableArray<string>.Empty,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(17643, "https://github.com/dotnet/roslyn/issues/17643")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialogNoBackingField()
{
var code =
@"
class Program
{
public int F { get; set; }
[||]
}";
var fixedCode =
@"
class Program
{
public int F { get; set; }
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
F == program.F;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialogNoIndexer()
{
var code =
@"
class Program
{
public int P => 0;
public int this[int index] => 0;
[||]
}";
var fixedCode =
@"
class Program
{
public int P => 0;
public int this[int index] => 0;
public override bool Equals(object obj)
{
return obj is Program program &&
P == program.P;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
}.RunAsync();
}
[WorkItem(25707, "https://github.com/dotnet/roslyn/issues/25707")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialogNoSetterOnlyProperty()
{
var code =
@"
class Program
{
public int P => 0;
public int S { set { } }
[||]
}";
var fixedCode =
@"
class Program
{
public int P => 0;
public int S { set { } }
public override bool Equals(object obj)
{
return obj is Program program &&
P == program.P;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
}.RunAsync();
}
[WorkItem(41958, "https://github.com/dotnet/roslyn/issues/41958")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestWithDialogInheritedMembers()
{
var code =
@"
class Base
{
public int C { get; set; }
}
class Middle : Base
{
public int B { get; set; }
}
class Derived : Middle
{
public int A { get; set; }
[||]
}";
var fixedCode =
@"
class Base
{
public int C { get; set; }
}
class Middle : Base
{
public int B { get; set; }
}
class Derived : Middle
{
public int A { get; set; }
public override bool Equals(object obj)
{
return obj is Derived derived &&
C == derived.C &&
B == derived.B &&
A == derived.A;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateOperators1()
{
var code =
@"
using System.Collections.Generic;
class Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System.Collections.Generic;
class Program
{
public string s;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
s == program.s;
}
public static bool operator ==(Program left, Program right)
{
return EqualityComparer<Program>.Default.Equals(left, right);
}
public static bool operator !=(Program left, Program right)
{
return !(left == right);
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateOperators2()
{
var code =
@"
using System.Collections.Generic;
class Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System.Collections.Generic;
class Program
{
public string s;
public override bool Equals(object obj)
{
Program program = obj as Program;
return program != null &&
s == program.s;
}
public static bool operator ==(Program left, Program right) => EqualityComparer<Program>.Default.Equals(left, right);
public static bool operator !=(Program left, Program right) => !(left == right);
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.CSharp6,
Options =
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
},
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateOperators3()
{
var code =
@"
using System.Collections.Generic;
class Program
{
public string s;
[||]
public static bool operator {|CS0216:==|}(Program left, Program right) => true;
}";
var fixedCode =
@"
using System.Collections.Generic;
class Program
{
public string s;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
s == program.s;
}
public static bool operator {|CS0216:==|}(Program left, Program right) => true;
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId)),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateOperators4()
{
var code =
@"
using System.Collections.Generic;
struct Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System.Collections.Generic;
struct Program
{
public string s;
public override bool Equals(object obj)
{
if (!(obj is Program))
{
return false;
}
var program = (Program)obj;
return s == program.s;
}
public static bool operator ==(Program left, Program right)
{
return left.Equals(right);
}
public static bool operator !=(Program left, Program right)
{
return !(left == right);
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGenerateLiftedOperators()
{
var code =
@"
using System;
using System.Collections.Generic;
class Foo
{
[|public bool? BooleanValue { get; }
public decimal? DecimalValue { get; }
public Bar? EnumValue { get; }
public DateTime? DateTimeValue { get; }|]
}
enum Bar
{
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
class Foo
{
public bool? BooleanValue { get; }
public decimal? DecimalValue { get; }
public Bar? EnumValue { get; }
public DateTime? DateTimeValue { get; }
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
BooleanValue == foo.BooleanValue &&
DecimalValue == foo.DecimalValue &&
EnumValue == foo.EnumValue &&
DateTimeValue == foo.DateTimeValue;
}
}
enum Bar
{
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task LiftedOperatorIsNotUsedWhenDirectOperatorWouldNotBeUsed()
{
var code =
@"
using System;
using System.Collections.Generic;
class Foo
{
[|public Bar Value { get; }
public Bar? NullableValue { get; }|]
}
struct Bar : IEquatable<Bar>
{
private readonly int value;
public override bool Equals(object obj) => false;
public bool Equals(Bar other) => value == other.value;
public override int GetHashCode() => -1584136870 + value.GetHashCode();
public static bool operator ==(Bar left, Bar right) => left.Equals(right);
public static bool operator !=(Bar left, Bar right) => !(left == right);
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
class Foo
{
public Bar Value { get; }
public Bar? NullableValue { get; }
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
Value.Equals(foo.Value) &&
EqualityComparer<Bar?>.Default.Equals(NullableValue, foo.NullableValue);
}
}
struct Bar : IEquatable<Bar>
{
private readonly int value;
public override bool Equals(object obj) => false;
public bool Equals(Bar other) => value == other.value;
public override int GetHashCode() => -1584136870 + value.GetHashCode();
public static bool operator ==(Bar left, Bar right) => left.Equals(right);
public static bool operator !=(Bar left, Bar right) => !(left == right);
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnStruct()
{
var code =
@"
using System.Collections.Generic;
struct Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
struct Program : IEquatable<Program>
{
public string s;
public override bool Equals(object obj)
{
return obj is Program && Equals((Program)obj);
}
public bool Equals(Program other)
{
return s == other.s;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
[WorkItem(25708, "https://github.com/dotnet/roslyn/issues/25708")]
public async Task TestOverrideEqualsOnRefStructReturnsFalse()
{
var code =
@"
ref struct Program
{
public string s;
[||]
}";
var fixedCode =
@"
ref struct Program
{
public string s;
public override bool Equals(object obj)
{
return false;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
[WorkItem(25708, "https://github.com/dotnet/roslyn/issues/25708")]
public async Task TestImplementIEquatableOnRefStructSkipsIEquatable()
{
var code =
@"
ref struct Program
{
public string s;
[||]
}";
var fixedCode =
@"
ref struct Program
{
public string s;
public override bool Equals(object obj)
{
return false;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
// We are forcefully enabling the ImplementIEquatable option, as that is our way
// to test that the option does nothing. The VS mode will ensure if the option
// is not available it will not be shown.
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnStructInNullableContextWithUnannotatedMetadata()
{
var code =
@"#nullable enable
struct Foo
{
public int Bar { get; }
[||]
}";
var fixedCode =
@"#nullable enable
using System;
struct Foo : IEquatable<Foo>
{
public int Bar { get; }
public override bool Equals(object? obj)
{
return obj is Foo foo && Equals(foo);
}
public bool Equals(Foo other)
{
return Bar == other.Bar;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnStructInNullableContextWithAnnotatedMetadata()
{
var code =
@"
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
struct Foo
{
public bool Bar { get; }
[||]
}
";
var fixedCode =
@"
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
struct Foo : IEquatable<Foo>
{
public bool Bar { get; }
public override bool Equals(object? obj)
{
return obj is Foo foo && Equals(foo);
}
public bool Equals(Foo other)
{
return Bar == other.Bar;
}
}
";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnClass()
{
var code =
@"
using System.Collections.Generic;
class Program
{
public string s;
[||]
}";
var fixedCode =
@"
using System;
using System.Collections.Generic;
class Program : IEquatable<Program>
{
public string s;
public override bool Equals(object obj)
{
return Equals(obj as Program);
}
public bool Equals(Program other)
{
return other != null &&
s == other.s;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnClassInNullableContextWithUnannotatedMetadata()
{
var code =
@"#nullable enable
class Foo
{
public int Bar { get; }
[||]
}";
var fixedCode =
@"#nullable enable
using System;
class Foo : IEquatable<Foo?>
{
public int Bar { get; }
public override bool Equals(object? obj)
{
return Equals(obj as Foo);
}
public bool Equals(Foo? other)
{
return other != null &&
Bar == other.Bar;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestImplementIEquatableOnClassInNullableContextWithAnnotatedMetadata()
{
var code =
@"
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
class Foo
{
public bool Bar { get; }
[||]
}
";
var fixedCode =
@"
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
class Foo : IEquatable<Foo?>
{
public bool Bar { get; }
public override bool Equals(object? obj)
{
return Equals(obj as Foo);
}
public bool Equals(Foo? other)
{
return other != null &&
Bar == other.Bar;
}
}
";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId),
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestDoNotOfferIEquatableIfTypeAlreadyImplementsIt()
{
var code =
@"
using System.Collections.Generic;
class Program : {|CS0535:System.IEquatable<Program>|}
{
public string s;
[||]
}";
var fixedCode =
@"
using System.Collections.Generic;
class Program : {|CS0535:System.IEquatable<Program>|}
{
public string s;
public override bool Equals(object obj)
{
var program = obj as Program;
return program != null &&
s == program.s;
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId)),
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestMissingReferences1()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp6,
CodeActionIndex = 1,
TestState =
{
Sources =
{
@"public class Class1
{
[|int i;|]
public void F()
{
}
}",
},
ExpectedDiagnostics =
{
// /0/Test0.cs(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(1, 14, 1, 20).WithArguments("System.Object"),
// /0/Test0.cs(1,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments
DiagnosticResult.CompilerError("CS1729").WithSpan(1, 14, 1, 20).WithArguments("object", "0"),
// /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(3, 5, 3, 8).WithArguments("System.Int32"),
// /0/Test0.cs(5,12): error CS0518: Predefined type 'System.Void' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(5, 12, 5, 16).WithArguments("System.Void"),
},
},
FixedState =
{
Sources = {
@"public class Class1
{
int i;
public override System.Boolean Equals(System.Object obj)
{
Class1 @class = obj as Class1;
return @class != null &&
i == @class.i;
}
public void F()
{
}
public override System.Int32 GetHashCode()
{
return 165851236 + EqualityComparer<System.Int32>.Default.GetHashCode(i);
}
}",
},
ExpectedDiagnostics =
{
// /0/Test0.cs(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(1, 14, 1, 20).WithArguments("System.Object"),
// /0/Test0.cs(1,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments
DiagnosticResult.CompilerError("CS1729").WithSpan(1, 14, 1, 20).WithArguments("object", "0"),
// /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(3, 5, 3, 8).WithArguments("System.Int32"),
// /0/Test0.cs(5,21): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(5, 21, 5, 27).WithArguments("System.Object"),
// /0/Test0.cs(5,28): error CS1069: The type name 'Boolean' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.
DiagnosticResult.CompilerError("CS1069").WithSpan(5, 28, 5, 35).WithArguments("Boolean", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
// /0/Test0.cs(5,43): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(5, 43, 5, 49).WithArguments("System.Object"),
// /0/Test0.cs(5,50): error CS1069: The type name 'Object' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.
DiagnosticResult.CompilerError("CS1069").WithSpan(5, 50, 5, 56).WithArguments("Object", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
// /0/Test0.cs(7,9): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(7, 9, 7, 15).WithArguments("System.Object"),
// /0/Test0.cs(7,32): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(7, 32, 7, 38).WithArguments("System.Object"),
// /0/Test0.cs(8,16): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(8, 16, 8, 30).WithArguments("System.Object"),
// /0/Test0.cs(9,16): error CS0518: Predefined type 'System.Boolean' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(9, 16, 9, 29).WithArguments("System.Boolean"),
// /0/Test0.cs(12,12): error CS0518: Predefined type 'System.Void' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(12, 12, 12, 16).WithArguments("System.Void"),
// /0/Test0.cs(16,21): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(16, 21, 16, 27).WithArguments("System.Object"),
// /0/Test0.cs(16,28): error CS1069: The type name 'Int32' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.
DiagnosticResult.CompilerError("CS1069").WithSpan(16, 28, 16, 33).WithArguments("Int32", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
// /0/Test0.cs(16,34): error CS0115: 'Class1.GetHashCode()': no suitable method found to override
DiagnosticResult.CompilerError("CS0115").WithSpan(16, 34, 16, 45).WithArguments("Class1.GetHashCode()"),
// /0/Test0.cs(18,16): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(18, 16, 18, 25).WithArguments("System.Int32"),
// /0/Test0.cs(18,28): error CS0103: The name 'EqualityComparer' does not exist in the current context
DiagnosticResult.CompilerError("CS0103").WithSpan(18, 28, 18, 58).WithArguments("EqualityComparer"),
// /0/Test0.cs(18,28): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(18, 28, 18, 58).WithArguments("System.Object"),
// /0/Test0.cs(18,45): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithSpan(18, 45, 18, 51).WithArguments("System.Object"),
// /0/Test0.cs(18,52): error CS1069: The type name 'Int32' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.
DiagnosticResult.CompilerError("CS1069").WithSpan(18, 52, 18, 57).WithArguments("Int32", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
},
},
ReferenceAssemblies = ReferenceAssemblies.Default.WithAssemblies(ImmutableArray<string>.Empty),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeInCheckedContext()
{
var code =
@"using System.Collections.Generic;
class Program
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Program
{
int i;
string S { get; }
public override bool Equals(object obj)
{
Program program = obj as Program;
return program != null &&
i == program.i &&
S == program.S;
}
public override int GetHashCode()
{
unchecked
{
int hashCode = -538000506;
hashCode = hashCode * -1521134295 + i.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(S);
return hashCode;
}
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
SolutionTransforms =
{
(solution, projectId) =>
{
var compilationOptions = solution.GetRequiredProject(projectId).CompilationOptions;
return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOverflowChecks(true));
},
},
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeStruct()
{
var code =
@"using System.Collections.Generic;
struct S
{
[|int j;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
struct S : IEquatable<S>
{
int j;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j;
}
public override int GetHashCode()
{
return 1424088837 + j.GetHashCode();
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSystemHashCodeOneMember()
{
var code =
@"using System.Collections.Generic;
namespace System { public struct HashCode { } }
struct S
{
[|int j;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
namespace System { public struct HashCode { } }
struct S : IEquatable<S>
{
int j;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j;
}
public override int GetHashCode()
{
return HashCode.Combine(j);
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(21,25): error CS0117: 'HashCode' does not contain a definition for 'Combine'
DiagnosticResult.CompilerError("CS0117").WithSpan(21, 25, 21, 32).WithArguments("System.HashCode", "Combine"),
},
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(37297, "https://github.com/dotnet/roslyn/issues/37297")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPublicSystemHashCodeOtherProject()
{
var publicHashCode =
@"using System.Collections.Generic;
namespace System { public struct HashCode { } }";
var code =
@"struct S
{
[|int j;|]
}";
var fixedCode =
@"using System;
struct S : IEquatable<S>
{
int j;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j;
}
public override int GetHashCode()
{
return HashCode.Combine(j);
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestState =
{
AdditionalProjects =
{
["P1"] =
{
Sources = { ("HashCode.cs", publicHashCode) },
},
},
Sources = { code },
AdditionalProjectReferences = { "P1" },
},
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(19,25): error CS0117: 'HashCode' does not contain a definition for 'Combine'
DiagnosticResult.CompilerError("CS0117").WithSpan(19, 25, 19, 32).WithArguments("System.HashCode", "Combine"),
},
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(37297, "https://github.com/dotnet/roslyn/issues/37297")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestInternalSystemHashCode()
{
var internalHashCode =
@"using System.Collections.Generic;
namespace System { internal struct HashCode { } }";
var code =
@"struct S
{
[|int j;|]
}";
var fixedCode =
@"using System;
struct S : IEquatable<S>
{
int j;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j;
}
public override int GetHashCode()
{
return 1424088837 + j.GetHashCode();
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestState =
{
AdditionalProjects =
{
["P1"] =
{
Sources = { ("HashCode.cs", internalHashCode) },
},
},
Sources = { code },
AdditionalProjectReferences = { "P1" },
},
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSystemHashCodeEightMembers()
{
var code =
@"using System.Collections.Generic;
namespace System { public struct HashCode { } }
struct S
{
[|int j, k, l, m, n, o, p, q;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
namespace System { public struct HashCode { } }
struct S : IEquatable<S>
{
int j, k, l, m, n, o, p, q;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j &&
k == other.k &&
l == other.l &&
m == other.m &&
n == other.n &&
o == other.o &&
p == other.p &&
q == other.q;
}
public override int GetHashCode()
{
return HashCode.Combine(j, k, l, m, n, o, p, q);
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(28,25): error CS0117: 'HashCode' does not contain a definition for 'Combine'
DiagnosticResult.CompilerError("CS0117").WithSpan(28, 25, 28, 32).WithArguments("System.HashCode", "Combine"),
},
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSystemHashCodeNineMembers()
{
var code =
@"using System.Collections.Generic;
namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } }
struct S
{
[|int j, k, l, m, n, o, p, q, r;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } }
struct S : IEquatable<S>
{
int j, k, l, m, n, o, p, q, r;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j &&
k == other.k &&
l == other.l &&
m == other.m &&
n == other.n &&
o == other.o &&
p == other.p &&
q == other.q &&
r == other.r;
}
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(j);
hash.Add(k);
hash.Add(l);
hash.Add(m);
hash.Add(n);
hash.Add(o);
hash.Add(p);
hash.Add(q);
hash.Add(r);
return hash.ToHashCode();
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSystemHashCodeNineMembers_Explicit()
{
var code =
@"using System.Collections.Generic;
namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } }
struct S
{
[|int j, k, l, m, n, o, p, q, r;|]
}";
var fixedCode =
@"using System;
using System.Collections.Generic;
namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } }
struct S : IEquatable<S>
{
int j, k, l, m, n, o, p, q, r;
public override bool Equals(object obj)
{
return obj is S && Equals((S)obj);
}
public bool Equals(S other)
{
return j == other.j &&
k == other.k &&
l == other.l &&
m == other.m &&
n == other.n &&
o == other.o &&
p == other.p &&
q == other.q &&
r == other.r;
}
public override int GetHashCode()
{
HashCode hash = new HashCode();
hash.Add(j);
hash.Add(k);
hash.Add(l);
hash.Add(m);
hash.Add(n);
hash.Add(o);
hash.Add(p);
hash.Add(q);
hash.Add(r);
return hash.ToHashCode();
}
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.CSharp6,
Options = { PreferExplicitTypeWithInfo() },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsSingleField_Patterns()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System.Collections.Generic;
class Program
{
[|int a;|]
}",
@"using System.Collections.Generic;
class Program
{
int a;
public override bool Equals(object obj)
{
return obj is Program program &&
a == program.a;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsSingleFieldInStruct_Patterns()
{
await VerifyCS.VerifyRefactoringAsync(
@"using System.Collections.Generic;
struct Program
{
[|int a;|]
}",
@"using System;
using System.Collections.Generic;
struct Program : IEquatable<Program>
{
int a;
public override bool Equals(object obj)
{
return obj is Program program && Equals(program);
}
public bool Equals(Program other)
{
return a == other.a;
}
public static bool operator ==(Program left, Program right)
{
return left.Equals(right);
}
public static bool operator !=(Program left, Program right)
{
return !(left == right);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsBaseWithOverriddenEquals_Patterns()
{
var code =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Program : Base
{
[|int i;
string S { get; }|]
}";
var fixedCode =
@"using System.Collections.Generic;
class Base
{
public override bool Equals(object o)
{
return false;
}
}
class Program : Base
{
int i;
string S { get; }
public override bool Equals(object obj)
{
return obj is Program program &&
base.Equals(obj) &&
i == program.i &&
S == program.S;
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialSelection()
{
var code =
@"using System.Collections.Generic;
class Program
{
int [|a|];
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
}.RunAsync();
}
[WorkItem(40053, "https://github.com/dotnet/roslyn/issues/40053")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualityOperatorsNullableAnnotationWithReferenceType()
{
var code =
@"
#nullable enable
using System;
namespace N
{
public class C[||]
{
public int X;
}
}";
var fixedCode =
@"
#nullable enable
using System;
using System.Collections.Generic;
namespace N
{
public class C
{
public int X;
public override bool Equals(object? obj)
{
return obj is C c &&
X == c.X;
}
public static bool operator ==(C? left, C? right)
{
return EqualityComparer<C>.Default.Equals(left, right);
}
public static bool operator !=(C? left, C? right)
{
return !(left == right);
}
}
}";
await new TestWithDialog
{
TestCode = code,
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(20,55): error CS8604: Possible null reference argument for parameter 'x' in 'bool EqualityComparer<C>.Equals(C x, C y)'.
DiagnosticResult.CompilerError("CS8604").WithSpan(20, 55, 20, 59).WithArguments("x", "bool EqualityComparer<C>.Equals(C x, C y)"),
// /0/Test0.cs(20,61): error CS8604: Possible null reference argument for parameter 'y' in 'bool EqualityComparer<C>.Equals(C x, C y)'.
DiagnosticResult.CompilerError("CS8604").WithSpan(20, 61, 20, 66).WithArguments("y", "bool EqualityComparer<C>.Equals(C x, C y)"),
},
},
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.Default,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(40053, "https://github.com/dotnet/roslyn/issues/40053")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualityOperatorsNullableAnnotationWithValueType()
{
var code =
@"
#nullable enable
using System;
namespace N
{
public struct C[||]
{
public int X;
}
}";
var fixedCode =
@"
#nullable enable
using System;
namespace N
{
public struct C
{
public int X;
public override bool Equals(object? obj)
{
return obj is C c &&
X == c.X;
}
public static bool operator ==(C left, C right)
{
return left.Equals(right);
}
public static bool operator !=(C left, C right)
{
return !(left == right);
}
}
}";
await new TestWithDialog
{
TestCode = code,
FixedCode = fixedCode,
MemberNames = default,
OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId),
LanguageVersion = LanguageVersion.Default,
Options = { PreferImplicitTypeWithInfo() },
}.RunAsync();
}
[WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialTypes1()
{
await new TestWithDialog
{
TestState =
{
Sources =
{
@"partial class Goo
{
int bar;
[||]
}",
@"partial class Goo
{
}",
},
},
FixedState =
{
Sources =
{
@"partial class Goo
{
int bar;
public override bool Equals(object obj)
{
return obj is Goo goo &&
bar == goo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}",
@"partial class Goo
{
}",
},
},
MemberNames = ImmutableArray.Create("bar"),
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialTypes2()
{
await new TestWithDialog
{
TestState =
{
Sources =
{
@"partial class Goo
{
int bar;
}",
@"partial class Goo
{
[||]
}",
},
},
FixedState =
{
Sources =
{
@"partial class Goo
{
int bar;
}",
@"partial class Goo
{
public override bool Equals(object obj)
{
return obj is Goo goo &&
bar == goo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}",
},
},
MemberNames = ImmutableArray.Create("bar"),
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialTypes3()
{
await new TestWithDialog
{
TestState =
{
Sources =
{
@"partial class Goo
{
[||]
}",
@"partial class Goo
{
int bar;
}",
},
},
FixedState =
{
Sources =
{
@"partial class Goo
{
public override bool Equals(object obj)
{
return obj is Goo goo &&
bar == goo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}",
@"partial class Goo
{
int bar;
}",
},
},
MemberNames = ImmutableArray.Create("bar"),
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestPartialTypes4()
{
await new TestWithDialog
{
TestState =
{
Sources =
{
@"partial class Goo
{
}",
@"partial class Goo
{
int bar;
[||]
}",
},
},
FixedState =
{
Sources =
{
@"partial class Goo
{
}",
@"partial class Goo
{
int bar;
public override bool Equals(object obj)
{
return obj is Goo goo &&
bar == goo.bar;
}
public override int GetHashCode()
{
return 999205674 + bar.GetHashCode();
}
}",
},
},
MemberNames = ImmutableArray.Create("bar"),
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(43290, "https://github.com/dotnet/roslyn/issues/43290")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestAbstractBase()
{
var code =
@"
#nullable enable
namespace System { public struct HashCode { } }
abstract class Base
{
public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
}
class {|CS0534:{|CS0534:Derived|}|} : Base
{
[|public int P { get; }|]
}";
var fixedCode =
@"
#nullable enable
using System;
namespace System { public struct HashCode { } }
abstract class Base
{
public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
}
class Derived : Base
{
public int P { get; }
public override bool Equals(object? obj)
{
return obj is Derived derived &&
P == derived.P;
}
public override int GetHashCode()
{
return HashCode.Combine(P);
}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedState =
{
Sources = { fixedCode },
ExpectedDiagnostics =
{
// /0/Test0.cs(23,25): error CS0117: 'HashCode' does not contain a definition for 'Combine'
DiagnosticResult.CompilerError("CS0117").WithSpan(26, 25, 26, 32).WithArguments("System.HashCode", "Combine"),
},
},
CodeActionIndex = 1,
LanguageVersion = LanguageVersion.Default,
}.RunAsync();
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Workspaces/Core/Portable/Storage/SQLite/Interop/SqlException.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.SQLite.Interop
{
internal class SqlException : Exception
{
public readonly Result Result;
public SqlException(Result result, string message)
: base(message)
{
this.Result = result;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.SQLite.Interop
{
internal class SqlException : Exception
{
public readonly Result Result;
public SqlException(Result result, string message)
: base(message)
{
this.Result = result;
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ByteKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public ByteKeywordRecommender()
: base(SyntaxKind.ByteKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsEnumBaseListContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Byte;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public ByteKeywordRecommender()
: base(SyntaxKind.ByteKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsEnumBaseListContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Byte;
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Tools/PrepareTests/Program.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 Mono.Options;
internal static class Program
{
internal const int ExitFailure = 1;
internal const int ExitSuccess = 0;
public static int Main(string[] args)
{
string? source = null;
string? destination = null;
bool isUnix = false;
var options = new OptionSet()
{
{ "source=", "Path to binaries", (string s) => source = s },
{ "destination=", "Output path", (string s) => destination = s },
{ "unix", "If true, prepares tests for unix environment instead of Windows", o => isUnix = o is object }
};
options.Parse(args);
if (source is null)
{
Console.Error.WriteLine("--source argument must be provided");
return ExitFailure;
}
if (destination is null)
{
Console.Error.WriteLine("--destination argument must be provided");
return ExitFailure;
}
MinimizeUtil.Run(source, destination, isUnix);
return ExitSuccess;
}
}
| // Licensed to the .NET Foundation under one or more 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 Mono.Options;
internal static class Program
{
internal const int ExitFailure = 1;
internal const int ExitSuccess = 0;
public static int Main(string[] args)
{
string? source = null;
string? destination = null;
bool isUnix = false;
var options = new OptionSet()
{
{ "source=", "Path to binaries", (string s) => source = s },
{ "destination=", "Output path", (string s) => destination = s },
{ "unix", "If true, prepares tests for unix environment instead of Windows", o => isUnix = o is object }
};
options.Parse(args);
if (source is null)
{
Console.Error.WriteLine("--source argument must be provided");
return ExitFailure;
}
if (destination is null)
{
Console.Error.WriteLine("--destination argument must be provided");
return ExitFailure;
}
MinimizeUtil.Run(source, destination, isUnix);
return ExitSuccess;
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/VisualStudio/Core/Def/EditorConfigSettings/ServiceProviderExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings
{
internal static class ServiceProviderExtensions
{
public static bool TryGetService<TService, TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface)
where TInterface : class
{
@interface = sp.GetService<TService, TInterface>(throwOnFailure: false);
return @interface is not null;
}
public static bool TryGetService<TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface)
where TInterface : class
{
@interface = sp.GetService<TInterface>();
return @interface is not null;
}
public static TInterface? GetService<TInterface>(this IServiceProvider sp)
where TInterface : class
{
return sp.GetService<TInterface, TInterface>(throwOnFailure: false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings
{
internal static class ServiceProviderExtensions
{
public static bool TryGetService<TService, TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface)
where TInterface : class
{
@interface = sp.GetService<TService, TInterface>(throwOnFailure: false);
return @interface is not null;
}
public static bool TryGetService<TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface)
where TInterface : class
{
@interface = sp.GetService<TInterface>();
return @interface is not null;
}
public static TInterface? GetService<TInterface>(this IServiceProvider sp)
where TInterface : class
{
return sp.GetService<TInterface, TInterface>(throwOnFailure: false);
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/CSharp/Test/Symbol/Compilation/UsedAssembliesTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class UsedAssembliesTests : CSharpTestBase
{
[Fact]
public void NoReferences_01()
{
var source =
@"
interface I1
{
public I1 M();
}
";
var comp1 = CreateEmptyCompilation(source);
CompileAndVerify(comp1);
Assert.Empty(comp1.GetUsedAssemblyReferences());
var comp2 = CreateCompilation(source);
CompileAndVerify(comp2);
AssertUsedAssemblyReferences(comp2);
}
[Fact]
public void NoReferences_02()
{
var source =
@"
public interface I1
{
public I1 M();
}
";
var comp1 = CreateEmptyCompilation(source);
CompileAndVerify(comp1);
var source2 =
@"
public class C2
{
public static void Main(I1 x)
{
x.M();
}
}
";
verify<PEAssemblySymbol>(source2, comp1.EmitToImageReference());
verify<RetargetingAssemblySymbol>(source2, comp1.ToMetadataReference());
Assert.Empty(comp1.GetUsedAssemblyReferences());
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
private void AssertUsedAssemblyReferences(Compilation comp, MetadataReference[] expected, DiagnosticDescription[] before, DiagnosticDescription[] after, MetadataReference[] specificReferencesToAssert)
{
foreach (var c in CloneCompilationsWithUsings(comp, before, after))
{
assertUsedAssemblyReferences(c.comp, expected, c.before, c.after, specificReferencesToAssert);
}
void assertUsedAssemblyReferences(Compilation comp, MetadataReference[] expected, DiagnosticDescription[] before, DiagnosticDescription[] after, MetadataReference[] specificReferencesToAssert)
{
comp.VerifyDiagnostics(before);
bool hasCoreLibraryRef = !comp.ObjectType.IsErrorType();
var used = comp.GetUsedAssemblyReferences();
if (hasCoreLibraryRef)
{
Assert.Same(comp.ObjectType.ContainingAssembly, comp.GetAssemblyOrModuleSymbol(used[0]));
AssertEx.Equal(expected, used.Skip(1));
}
else
{
AssertEx.Equal(expected, used);
}
Assert.Empty(used.Where(r => r.Properties.Kind == MetadataImageKind.Module));
var comp2 = comp.RemoveAllReferences().AddReferences(used.Concat(comp.References.Where(r => r.Properties.Kind == MetadataImageKind.Module)));
if (!after.Any(d => ErrorFacts.GetSeverity((ErrorCode)d.Code) == DiagnosticSeverity.Error))
{
CompileAndVerify(comp2, verify: Verification.Skipped).Diagnostics.Where(d => d.Code != (int)ErrorCode.WRN_NoRuntimeMetadataVersion).Verify(after);
if (specificReferencesToAssert is object)
{
var tryRemove = specificReferencesToAssert.Where(reference => reference.Properties.Kind == MetadataImageKind.Assembly && !used.Contains(reference));
if (tryRemove.Count() > 1)
{
foreach (var reference in tryRemove)
{
var comp3 = comp.RemoveReferences(reference);
CompileAndVerify(comp3, verify: Verification.Skipped).Diagnostics.Where(d => d.Code != (int)ErrorCode.WRN_NoRuntimeMetadataVersion).Verify(after);
}
}
}
}
else
{
comp2.VerifyDiagnostics(after);
}
}
}
private static IEnumerable<(Compilation comp, DiagnosticDescription[] before, DiagnosticDescription[] after)> CloneCompilationsWithUsings(Compilation comp, DiagnosticDescription[] before, DiagnosticDescription[] after)
{
var tree = comp.SyntaxTrees.Single();
var unit = (CompilationUnitSyntax)tree.GetRoot();
if (!unit.Usings.Any())
{
yield return (comp, before, after);
yield break;
}
var source = unit.ToFullString();
var beforeUsings = source.Substring(0, unit.Usings.First().FullSpan.Start);
var afterUsings = source.Substring(unit.Usings.Last().FullSpan.End);
// With regular usings
var builder = new System.Text.StringBuilder();
builder.Append(beforeUsings);
builder.Append(@"
#line 1000
");
foreach (var directive in unit.Usings)
{
builder.Append(directive.ToFullString());
}
builder.Append(@"
#line 2000
");
builder.Append(afterUsings);
yield return (comp.ReplaceSyntaxTree(tree, CSharpTestBase.Parse(builder.ToString(), tree.FilePath, (CSharpParseOptions)tree.Options)), before, after);
// With global usings
before = adjustDiagnosticDescription(before);
after = adjustDiagnosticDescription(after);
builder.Clear();
builder.Append(@"
#line 1000
");
foreach (var directive in unit.Usings)
{
builder.Append(directive.ToFullString().Replace("using", "global using"));
}
var globalUsings = builder.ToString();
builder.Clear();
builder.Append(beforeUsings);
builder.Append(globalUsings);
builder.Append(@"
#line 2000
");
builder.Append(afterUsings);
var parseOptions = ((CSharpParseOptions)tree.Options).WithLanguageVersion(LanguageVersion.CSharp10);
yield return (comp.ReplaceSyntaxTree(tree, CSharpTestBase.Parse(builder.ToString(), tree.FilePath, parseOptions)), before, after);
// With global usings in a separate unit
builder.Clear();
builder.Append(beforeUsings);
builder.Append(@"
#line 2000
");
builder.Append(afterUsings);
yield return (comp.ReplaceSyntaxTree(tree, CSharpTestBase.Parse(builder.ToString(), tree.FilePath, parseOptions)).
AddSyntaxTrees(CSharpTestBase.Parse(globalUsings, "", parseOptions)), before, after);
static DiagnosticDescription[] adjustDiagnosticDescription(DiagnosticDescription[] input)
{
if (input is null)
{
return null;
}
DiagnosticDescription[] output = null;
for (int i = 0; i < input.Length; i++)
{
var old = input[i];
if (old.Code is (int)ErrorCode.HDN_UnusedUsingDirective)
{
allocateOutput(input, ref output)[i] = old.WithSquiggledText("global " + old.SquiggledText);
}
else if (old.LocationLine is > 1000 and < 2000)
{
allocateOutput(input, ref output)[i] = old.WithLocation(old.LocationLine, old.LocationCharacter + 7);
}
}
return output ?? input;
}
static DiagnosticDescription[] allocateOutput(DiagnosticDescription[] input, ref DiagnosticDescription[] output)
{
if (output is null)
{
System.Array.Copy(input, output = new DiagnosticDescription[input.Length], input.Length);
}
return output;
}
}
private void AssertUsedAssemblyReferences(Compilation comp, params MetadataReference[] expected)
{
AssertUsedAssemblyReferences(comp, expected, new DiagnosticDescription[] { }, new DiagnosticDescription[] { }, specificReferencesToAssert: null);
}
private void AssertUsedAssemblyReferences(Compilation comp, MetadataReference[] expected, MetadataReference[] specificReferencesToAssert)
{
AssertUsedAssemblyReferences(comp, expected, new DiagnosticDescription[] { }, new DiagnosticDescription[] { }, specificReferencesToAssert);
}
private Compilation AssertUsedAssemblyReferences(string source, MetadataReference[] references, params MetadataReference[] expected)
{
Compilation comp = CreateCompilation(source, references: references);
AssertUsedAssemblyReferences(comp, expected, references);
return comp;
}
private Compilation AssertUsedAssemblyReferences(string source, params MetadataReference[] references)
{
return AssertUsedAssemblyReferences(source, references, references);
}
private static void AssertUsedAssemblyReferences(string source, MetadataReference[] references, params DiagnosticDescription[] expected)
{
Compilation comp = CreateCompilation(source, references: references);
foreach (var c in CloneCompilationsWithUsings(comp, expected, null))
{
assertUsedAssemblyReferences(c.comp, c.before);
}
static void assertUsedAssemblyReferences(Compilation comp, params DiagnosticDescription[] expected)
{
var diagnostics = comp.GetDiagnostics();
diagnostics.Verify(expected);
Assert.True(diagnostics.Any(d => d.DefaultSeverity == DiagnosticSeverity.Error));
AssertEx.Equal(comp.References.Where(r => r.Properties.Kind == MetadataImageKind.Assembly), comp.GetUsedAssemblyReferences());
}
}
private ImmutableArray<MetadataReference> CompileWithUsedAssemblyReferences(string source, TargetFramework targetFramework, params MetadataReference[] references)
{
return CompileWithUsedAssemblyReferences(source, targetFramework, options: null, references);
}
private ImmutableArray<MetadataReference> CompileWithUsedAssemblyReferences(string source, TargetFramework targetFramework, CSharpCompilationOptions options, params MetadataReference[] references)
{
options ??= TestOptions.ReleaseDll;
options = options.WithSpecificDiagnosticOptions(options.SpecificDiagnosticOptions.Add("CS1591", ReportDiagnostic.Suppress));
Compilation comp = CreateEmptyCompilation(source,
references: TargetFrameworkUtil.GetReferences(targetFramework).Concat(references),
options: options,
parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
return CompileWithUsedAssemblyReferences(comp, specificReferencesToAssert: references);
}
private ImmutableArray<MetadataReference> CompileWithUsedAssemblyReferences(Compilation comp, string expectedOutput = null, MetadataReference[] specificReferencesToAssert = null)
{
ImmutableArray<MetadataReference> result = default;
foreach (var c in CloneCompilationsWithUsings(comp, null, null))
{
var currentResult = compileWithUsedAssemblyReferences(c.comp, expectedOutput, specificReferencesToAssert);
if (result.IsDefault)
{
result = currentResult;
}
else
{
AssertEx.Equal(result, currentResult);
}
}
return result;
ImmutableArray<MetadataReference> compileWithUsedAssemblyReferences(Compilation comp, string expectedOutput = null, MetadataReference[] specificReferencesToAssert = null)
{
var used = comp.GetUsedAssemblyReferences();
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: expectedOutput).VerifyDiagnostics();
Assert.Empty(used.Where(r => r.Properties.Kind == MetadataImageKind.Module));
if (specificReferencesToAssert is object)
{
var tryRemove = specificReferencesToAssert.Where(reference => reference.Properties.Kind == MetadataImageKind.Assembly && !used.Contains(reference));
if (tryRemove.Count() > 1)
{
foreach (var reference in tryRemove)
{
var comp3 = comp.RemoveReferences(reference);
CompileAndVerify(comp3, verify: Verification.Skipped, expectedOutput: expectedOutput).VerifyDiagnostics();
}
}
}
var comp2 = comp.RemoveAllReferences().AddReferences(used.Concat(comp.References.Where(r => r.Properties.Kind == MetadataImageKind.Module)));
CompileAndVerify(comp2, verify: Verification.Skipped, expectedOutput: expectedOutput).VerifyDiagnostics();
return used;
}
}
private ImmutableArray<MetadataReference> CompileWithUsedAssemblyReferences(string source, params MetadataReference[] references)
{
return CompileWithUsedAssemblyReferences(source, TargetFramework.Standard, references);
}
private void CompileWithUsedAssemblyReferences(string source, CSharpCompilationOptions options, params MetadataReference[] references)
{
CompileWithUsedAssemblyReferences(source, TargetFramework.Standard, options: options, references);
}
[Fact]
public void NoReferences_03()
{
var source =
@"
namespace System
{
public class Object {}
public class ValueType {}
public struct Void {}
}
public interface I1
{
public I1 M();
}
";
var comp1 = CreateEmptyCompilation(source);
comp1.VerifyEmitDiagnostics(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1)
);
var source2 =
@"
public class C2
{
public static object Main(I1 x)
{
x.M();
return null;
}
}
";
verify<PEAssemblySymbol>(source2, comp1.EmitToImageReference());
verify<SourceAssemblySymbol>(source2, comp1.ToMetadataReference());
Assert.Empty(comp1.GetUsedAssemblyReferences());
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = CreateEmptyCompilation(source2, references: new[] { reference, SystemCoreRef, SystemDrawingRef });
AssertUsedAssemblyReferences(comp2);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void NoReferences_04()
{
var source =
@"
public interface I1
{
public I1 M1();
}
";
var comp1 = CreateEmptyCompilation(source);
CompileAndVerify(comp1);
var source2 =
@"
public interface I2
{
public I1 M2();
}
";
verify<PEAssemblySymbol>(source2, comp1.EmitToImageReference());
verify<RetargetingAssemblySymbol>(source2, comp1.ToMetadataReference());
Assert.Empty(comp1.GetUsedAssemblyReferences());
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = CreateEmptyCompilation(source2, references: new[] { reference, SystemCoreRef, SystemDrawingRef });
AssertUsedAssemblyReferences(comp2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void FieldReference_01()
{
var source1 =
@"
public class C1
{
public static int F1 = 0;
public int F2 = 0;
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = C1.F1;
}
}
";
verify<PEAssemblySymbol>(source2, comp1ImageRef);
verify<SourceAssemblySymbol>(source2, comp1Ref);
var source3 =
@"
public class C2
{
public static void Main()
{
C1 x = null;
_ = x.F2;
}
}
";
verify<PEAssemblySymbol>(source3, comp1ImageRef);
verify<SourceAssemblySymbol>(source3, comp1Ref);
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void FieldReference_02()
{
var source0 =
@"
public class C0
{
public static C0 F0 = new C0();
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var comp0ImageRef = comp0.EmitToImageReference();
var source1 =
@"
public class C1
{
public static C0 F0 = C0.F0;
public static int F1 = 0;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = C1.F1;
}
}
";
verify<PEAssemblySymbol>(source2, comp0ImageRef, comp1ImageRef);
verify<PEAssemblySymbol>(source2, comp0Ref, comp1ImageRef);
verify<SourceAssemblySymbol>(source2, comp0Ref, comp1Ref);
verify<RetargetingAssemblySymbol>(source2, comp0ImageRef, comp1Ref);
var source3 =
@"
using static C1;
public class C2
{
public static void Main()
{
Assert(F1);
}
[System.Diagnostics.Conditional(""Always"")]
public static void Assert(int condition) {}
}
";
verify<SourceAssemblySymbol>(source3, comp0Ref, comp1Ref);
void verify<TAssemblySymbol>(string source2, MetadataReference reference0, MetadataReference reference1) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference0, reference1);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference1));
}
}
[Fact]
public void FieldReference_03()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var comp0ImageRef = comp0.EmitToImageReference();
var source1 =
@"
class C1
{
static C0 F0 = new C0();
public static C1 F1 = new C1();
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref }, options: TestOptions.DebugModule);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
static C1 F1 = C1.F1;
public static int F2 = 0;
}
";
var comp2 = verify2<SourceAssemblySymbol>(source2, comp0Ref, comp1Ref);
var comp2Ref = comp2.ToMetadataReference();
var comp2ImageRef = comp2.EmitToImageReference();
var source3 =
@"
public class C3
{
public static void Main()
{
_ = C2.F2;
}
}
";
verify3<PEAssemblySymbol>(source3, comp0ImageRef, comp2ImageRef);
verify3<PEAssemblySymbol>(source3, comp0Ref, comp2ImageRef);
verify3<SourceAssemblySymbol>(source3, comp0Ref, comp2Ref);
verify3<RetargetingAssemblySymbol>(source3, comp0ImageRef, comp2Ref);
verify3<PEAssemblySymbol>(source3, comp2ImageRef);
verify3<RetargetingAssemblySymbol>(source3, comp2Ref);
comp2 = verify2<PEAssemblySymbol>(source2, comp0ImageRef, comp1Ref);
comp2Ref = comp2.ToMetadataReference();
comp2ImageRef = comp2.EmitToImageReference();
verify3<PEAssemblySymbol>(source3, comp0ImageRef, comp2ImageRef);
verify3<PEAssemblySymbol>(source3, comp0Ref, comp2ImageRef);
verify3<RetargetingAssemblySymbol>(source3, comp0Ref, comp2Ref);
verify3<SourceAssemblySymbol>(source3, comp0ImageRef, comp2Ref);
verify3<PEAssemblySymbol>(source3, comp2ImageRef);
verify3<RetargetingAssemblySymbol>(source3, comp2Ref);
comp2 = CreateCompilation(source2, references: new[] { comp1Ref });
comp2.VerifyDiagnostics();
Assert.True(comp2.References.Count() > 1);
var used = comp2.GetUsedAssemblyReferences();
Assert.Equal(1, used.Length);
Assert.Same(comp2.ObjectType.ContainingAssembly, comp2.GetAssemblyOrModuleSymbol(used[0]));
comp2Ref = comp2.ToMetadataReference();
comp2ImageRef = comp2.EmitToImageReference();
verify3<PEAssemblySymbol>(source3, comp0ImageRef, comp2ImageRef);
verify3<PEAssemblySymbol>(source3, comp0Ref, comp2ImageRef);
verify3<RetargetingAssemblySymbol>(source3, comp0Ref, comp2Ref);
verify3<RetargetingAssemblySymbol>(source3, comp0ImageRef, comp2Ref);
verify3<PEAssemblySymbol>(source3, comp2ImageRef);
verify3<SourceAssemblySymbol>(source3, comp2Ref);
Compilation verify2<TAssemblySymbol>(string source2, MetadataReference reference0, MetadataReference reference1) where TAssemblySymbol : AssemblySymbol
{
var comp2 = AssertUsedAssemblyReferences(source2, new[] { reference0, reference1 }, reference0);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference0));
return comp2;
}
void verify3<TAssemblySymbol>(string source3, params MetadataReference[] references) where TAssemblySymbol : AssemblySymbol
{
Compilation comp3 = AssertUsedAssemblyReferences(source3, references: references);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp3).GetAssemblyOrModuleSymbol(references.Last()));
}
}
[Fact]
public void FieldReference_04()
{
var source1 =
@"
namespace N1
{
public enum E1
{
F1 = 0
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
verify(comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = N1.E1.F1 + 1;
}
}
");
verify(comp1Ref,
@"
using N1;
public class C2
{
public static void Main()
{
_ = E1.F1 + 1;
}
}
");
verify(comp1Ref,
@"
using static N1.E1;
public class C2
{
public static void Main()
{
_ = F1 + 1;
}
}
");
verify(comp1Ref,
@"
using alias = N1.E1;
public class C2
{
public static void Main()
{
_ = alias.F1 + 1;
}
}
");
void verify(MetadataReference reference, string source)
{
AssertUsedAssemblyReferences(source, reference);
}
}
[Fact]
public void FieldReference_05()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
public class C3
{
public int F3 = 0;
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = C1<C0>.E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main()
{
_ = E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = alias.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main()
{
_ = alias.E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = nameof(C1<C0>.E1.F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(E1.F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = nameof(F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = nameof(alias.F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(alias.E1.F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = nameof(C1<C0>.C3.F3);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(C3.F3);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.C3;
public class C2
{
public static void Main()
{
_ = nameof(alias.F3);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(alias.C3.F3);
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void FieldReference_06()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
public class C3
{
public int F3;
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
class C2
{
/// <summary>
/// <see cref=""C1{C0}.E1.F1""/>
/// </summary>
static void Main()
{
}
}
",
hasTypeReferencesInUsing: false);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
class C2
{
/// <summary>
/// <see cref=""E1.F1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
class C2
{
/// <summary>
/// <see cref=""F1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
class C2
{
/// <summary>
/// <see cref=""alias.F1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
class C2
{
/// <summary>
/// <see cref=""alias.E1.F1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
class C2
{
/// <summary>
/// <see cref=""C1{C0}.C3.F3""/>
/// </summary>
static void Main()
{
}
}
",
hasTypeReferencesInUsing: false);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
class C2
{
/// <summary>
/// <see cref=""C3.F3""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.C3;
class C2
{
/// <summary>
/// <see cref=""alias.F3""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
class C2
{
/// <summary>
/// <see cref=""alias.C3.F3""/>
/// </summary>
static void Main()
{
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source, bool hasTypeReferencesInUsing = true)
{
var references = new[] { reference0, reference1 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, hasTypeReferencesInUsing ? references : new MetadataReference[] { }, references);
var expected = hasTypeReferencesInUsing ? references : new[] { reference1 };
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, expected);
Compilation comp4 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
AssertUsedAssemblyReferences(comp4, expected);
}
}
[Fact]
public void FieldReference_07()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var attribute =
@"
class TestAttribute : System.Attribute
{
public TestAttribute()
{ }
public TestAttribute(int value)
{ }
public int Value = 0;
}
";
verify(comp0Ref, comp1Ref,
@"
public class C2
{
[Test((int)C1<C0>.E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
[Test((int)E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
[Test((int)F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
[Test((int)alias.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
[Test((int)alias.E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
public class C2
{
[Test(Value = (int)C1<C0>.E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
[Test(Value = (int)E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
[Test(Value = (int)F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
[Test(Value = (int)alias.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
[Test(Value = (int)alias.E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void FieldReference_08()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main(int p = (int)C1<C0>.E1.F1 + 1)
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main(int p = (int)E1.F1 + 1)
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
public static void Main(int p = (int)F1 + 1)
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
public static void Main(int p = (int)alias.F1 + 1)
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main(int p = (int)alias.E1.F1 + 1)
{
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void MethodReference_01()
{
var source1 =
@"
public class C1
{
public static void M1(){}
}
";
var comp1 = CreateCompilation(source1);
var source2 =
@"
public class C2
{
public static void Main()
{
C1.M1();
}
}
";
verify<PEAssemblySymbol>(source2, comp1.EmitToImageReference());
verify<SourceAssemblySymbol>(source2, comp1.ToMetadataReference());
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void MethodReference_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var source1 =
@"
public class C1
{
public static void M1<T>(){}
}
public class C2<T> {}
public class C3<T>
{
public class C4 {}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var reference0 = comp0.ToMetadataReference();
var reference1 = comp1.ToMetadataReference();
verify(reference0, reference1,
@"
public class C5
{
public static void Main()
{
C1.M1<C0>();
}
}
");
verify(reference0, reference1,
@"
public class C5
{
public static void Main()
{
C1.M1<C2<C0>>();
}
}
");
verify(reference1, reference0,
@"
public class C5
{
public static void Main()
{
C1.M1<C3<C0>.C4>();
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void MethodReference_03()
{
var source0 =
@"
public static class C0
{
public static void M1(this string x, int y) { }
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void M1(this string x, string y) { }
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
var x = ""a"";
x.M1(""b"");
}
}
";
AssertUsedAssemblyReferences(source2, references: new[] { comp0Ref, comp1Ref }, comp0Ref, comp1Ref);
}
[Fact]
public void MethodReference_04()
{
var source0 =
@"
public static class C0
{
public static void M1(this string x, string y) { }
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void M1(this string x, string y) { }
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
var x = ""a"";
x.M1(""b"");
}
}
";
AssertUsedAssemblyReferences(source2, references: new[] { comp0Ref, comp1Ref },
// (7,11): error CS0121: The call is ambiguous between the following methods or properties: 'C0.M1(string, string)' and 'C1.M1(string, string)'
// x.M1("b");
Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C0.M1(string, string)", "C1.M1(string, string)").WithLocation(7, 11)
);
}
[Fact]
public void MethodReference_05()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0, assemblyName: "MethodReference_05_0");
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void M1(this string x, C0 y) { }
}
public interface I1 {}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public static class C2
{
public static void M1(this string x, string y) { }
}
";
var comp2 = CreateCompilation(source2);
var comp2Ref = comp2.ToMetadataReference();
var source3 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
x.M1(""b"");
}
}
";
AssertUsedAssemblyReferences(source3, references: new[] { comp0Ref, comp1Ref, comp2Ref }, comp0Ref, comp1Ref, comp2Ref);
var expected1 = new DiagnosticDescription[] {
// (7,9): error CS0012: The type 'C0' is defined in an assembly that is not referenced. You must add a reference to assembly 'MethodReference_05_0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// x.M1("b");
Diagnostic(ErrorCode.ERR_NoTypeDef, "x.M1").WithArguments("C0", "MethodReference_05_0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 9)
};
AssertUsedAssemblyReferences(source3, references: new[] { comp1Ref, comp2Ref }, expected1);
var source4 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
x.M1(""b"");
}
void M1(I1 x) {}
}
";
AssertUsedAssemblyReferences(source4, references: new[] { comp0Ref, comp1Ref, comp2Ref }, comp0Ref, comp1Ref, comp2Ref);
AssertUsedAssemblyReferences(source4, references: new[] { comp1Ref, comp2Ref }, expected1);
var source5 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface C0
{
}
";
var comp5 = CreateCompilation(source5);
comp5.VerifyDiagnostics();
var comp5Ref = comp5.ToMetadataReference(embedInteropTypes: true);
var comp6 = CreateCompilation(source1, references: new[] { comp5Ref });
var comp6Ref = comp6.ToMetadataReference();
var comp6ImageRef = comp6.EmitToImageReference();
var comp7 = CreateCompilation(source5);
var comp7Ref = comp7.ToMetadataReference(embedInteropTypes: false);
var comp7ImageRef = comp7.EmitToImageReference(embedInteropTypes: false);
AssertUsedAssemblyReferences(source3, references: new[] { comp7Ref, comp6Ref, comp2Ref }, comp7Ref, comp6Ref, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp7ImageRef, comp6ImageRef, comp2Ref }, comp7ImageRef, comp6ImageRef, comp2Ref);
var expected2 = new DiagnosticDescription[] {
// (7,9): error CS1748: Cannot find the interop type that matches the embedded interop type 'C0'. Are you missing an assembly reference?
// x.M1("b");
Diagnostic(ErrorCode.ERR_NoCanonicalView, "x.M1").WithArguments("C0").WithLocation(7, 9)
};
AssertUsedAssemblyReferences(source3, references: new[] { comp6Ref, comp2Ref }, expected2);
AssertUsedAssemblyReferences(source3, references: new[] { comp6ImageRef, comp2Ref }, expected2);
AssertUsedAssemblyReferences(source4, references: new[] { comp7Ref, comp6Ref, comp2Ref }, comp7Ref, comp6Ref, comp2Ref);
AssertUsedAssemblyReferences(source4, references: new[] { comp7ImageRef, comp6ImageRef, comp2Ref }, comp7ImageRef, comp6ImageRef, comp2Ref);
AssertUsedAssemblyReferences(source4, references: new[] { comp6Ref, comp2Ref }, expected2);
AssertUsedAssemblyReferences(source4, references: new[] { comp6ImageRef, comp2Ref }, expected2);
var source8 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
_ = nameof(x.M1);
}
}
";
AssertUsedAssemblyReferences(source8, new[] { comp0Ref, comp1Ref, comp2Ref },
// (7,20): error CS8093: Extension method groups are not allowed as an argument to 'nameof'.
// _ = nameof(x.M1);
Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "x.M1").WithLocation(7, 20)
);
}
[Fact]
public void MethodReference_06()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public void M1(C0 y) { }
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2 : C1
{
public void M1(string y) { }
}
";
var comp2 = CreateCompilation(source2, references: new[] { comp1Ref });
var comp2Ref = comp2.ToMetadataReference();
var comp2ImageRef = comp2.EmitToImageReference();
var source3 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
new C2().M1(x);
}
}
";
AssertUsedAssemblyReferences(source3, references: new[] { comp0Ref, comp1Ref, comp2Ref }, comp0Ref, comp1Ref, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp1Ref, comp2Ref }, comp1Ref, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp1ImageRef, comp2Ref }, comp1ImageRef, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp1Ref, comp2ImageRef }, comp1Ref, comp2ImageRef);
AssertUsedAssemblyReferences(source3, references: new[] { comp1ImageRef, comp2ImageRef }, comp1ImageRef, comp2ImageRef);
}
[Fact]
public void MethodReference_07()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0, assemblyName: "MethodReference_07_0");
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public void M1(string y) { }
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2 : C1
{
public void M1(C0 y) { }
}
";
var comp2 = CreateCompilation(source2, references: new[] { comp0Ref, comp1Ref });
var comp2Ref = comp2.ToMetadataReference();
var source3 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
new C2().M1(x);
}
}
";
AssertUsedAssemblyReferences(source3, references: new[] { comp0Ref, comp1Ref, comp2Ref }, comp0Ref, comp1Ref, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp1Ref, comp2Ref },
// (7,9): error CS0012: The type 'C0' is defined in an assembly that is not referenced. You must add a reference to assembly 'MethodReference_07_0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// new C2().M1(x);
Diagnostic(ErrorCode.ERR_NoTypeDef, "new C2().M1").WithArguments("C0", "MethodReference_07_0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 9)
);
}
[Fact]
public void MethodReference_08()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public C0 M1() => null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source3 =
@"
public class C3
{
public static void Main()
{
_ = nameof(C1.M1);
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
AssertUsedAssemblyReferences(source3, comp1Ref);
AssertUsedAssemblyReferences(source3, comp1ImageRef);
var source5 =
@"
using static C1;
public class C3
{
public static void Main()
{
_ = nameof(M1);
}
}
";
AssertUsedAssemblyReferences(source5, new[] { comp0Ref, comp1Ref },
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,20): error CS0103: The name 'M1' does not exist in the current context
// _ = nameof(M1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(2005, 20)
);
var source6 =
@"
public class C3
{
public static void Main()
{
var x = new C1();
_ = nameof(x.M1);
}
}
";
AssertUsedAssemblyReferences(source6, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source6, comp0Ref, comp1ImageRef);
AssertUsedAssemblyReferences(source6, comp1Ref);
AssertUsedAssemblyReferences(source6, comp1ImageRef);
}
[Fact]
public void MethodReference_09()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public static C0 M1() => null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source3 =
@"
public class C3
{
public static void Main()
{
_ = nameof(C1.M1);
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
AssertUsedAssemblyReferences(source3, comp1Ref);
AssertUsedAssemblyReferences(source3, comp1ImageRef);
var source4 =
@"
using static C1;
public class C3
{
public static void Main()
{
_ = nameof(M1);
}
}
";
AssertUsedAssemblyReferences(source4, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source4, comp0Ref, comp1ImageRef);
AssertUsedAssemblyReferences(source4, comp1Ref);
AssertUsedAssemblyReferences(source4, comp1ImageRef);
var source5 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface C0
{
}
";
var comp5 = CreateCompilation(source5);
comp5.VerifyDiagnostics();
var comp5Ref = comp5.ToMetadataReference(embedInteropTypes: true);
var comp6 = CreateCompilation(source1, references: new[] { comp5Ref });
var comp6Ref = comp6.ToMetadataReference();
var comp6ImageRef = comp6.EmitToImageReference();
var comp7 = CreateCompilation(source5);
var comp7Ref = comp7.ToMetadataReference(embedInteropTypes: false);
var comp7ImageRef = comp7.EmitToImageReference(embedInteropTypes: false);
AssertUsedAssemblyReferences(source3, new[] { comp7Ref, comp6Ref }, comp6Ref);
AssertUsedAssemblyReferences(source3, new[] { comp7ImageRef, comp6ImageRef }, comp6ImageRef);
AssertUsedAssemblyReferences(source4, new[] { comp7Ref, comp6Ref }, comp6Ref);
AssertUsedAssemblyReferences(source4, new[] { comp7ImageRef, comp6ImageRef }, comp6ImageRef);
}
[Fact]
public void MethodReference_10()
{
var source1 =
@"
public class C1
{
[System.Diagnostics.Conditional(""Always"")]
public static void M1(){}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
C1.M1();
}
}
";
verify<PEAssemblySymbol>(source2, comp1ImageRef);
verify<SourceAssemblySymbol>(source2, comp1Ref);
var source3 =
@"
using static C1;
public class C2
{
public static void Main()
{
M1();
}
}
";
verify<PEAssemblySymbol>(source3, comp1ImageRef);
verify<SourceAssemblySymbol>(source3, comp1Ref);
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void MethodReference_11()
{
var source0 =
@"
public class C0 : System.Collections.IEnumerable
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new System.NotImplementedException();
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void Add(this C0 x, int y) => throw null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = new C0() { 1 };
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
}
[Fact]
public void MethodReference_12()
{
var source0 =
@"
public class C0 : System.Collections.IEnumerable
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new System.NotImplementedException();
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
[System.Diagnostics.Conditional(""Always"")]
public static void Add(this C0 x, int y) => throw null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = new C0() { 1 };
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
}
[Fact]
public void FieldDeclaration_01()
{
var source1 =
@"
namespace N1
{
public class C1
{
public class C11
{
}
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
verify(comp1Ref,
@"
public class C2
{
public static N1.C1.C11 F1 = null;
}
");
verify(comp1Ref,
@"
using N2 = N1;
public class C2
{
public static N2.C1.C11 F1 = null;
}
");
verify(comp1Ref,
@"
using N1;
public class C2
{
public static C1.C11 F1 = null;
}
");
verify(comp1Ref,
@"
using static N1.C1;
public class C2
{
public static C11 F1 = null;
}
");
verify(comp1Ref,
@"
using C111 = N1.C1.C11;
public class C2
{
public static C111 F1 = null;
}
");
void verify(MetadataReference reference, string source2)
{
AssertUsedAssemblyReferences(source2, reference);
}
}
[Fact]
public void UnusedUsings_01()
{
var source1 =
@"
namespace N1
{
public static class C1
{
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
verify1(comp1Ref,
@"
using N1;
public class C2
{
}
",
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1;").WithLocation(1001, 1)
);
verify1(comp1Ref,
@"
using static N1.C1;
public class C2
{
}
",
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static N1.C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N1.C1;").WithLocation(1001, 1)
);
verify1(comp1Ref,
@"
using alias = N1.C1;
public class C2
{
}
",
// (1001,1): hidden CS8019: Unnecessary using directive.
// using alias = N1.C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using alias = N1.C1;").WithLocation(1001, 1)
);
verify1(comp1Ref,
@"
using alias = N1;
public class C2
{
}
",
// (1001,1): hidden CS8019: Unnecessary using directive.
// using alias = N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using alias = N1;").WithLocation(1001, 1)
);
verify1(comp1Ref.WithAliases(new[] { "N1C1" }),
@"
extern alias N1C1;
public class C2
{
}
",
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1)
);
verify1(comp1Ref,
@"namespace N2 {
using N1;
public class C2
{
}
}",
// (2,1): hidden CS8019: Unnecessary using directive.
// using N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1;").WithLocation(2, 1)
);
verify1(comp1Ref,
@"namespace N2 {
using static N1.C1;
public class C2
{
}
}",
// (2,1): hidden CS8019: Unnecessary using directive.
// using static N1.C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N1.C1;").WithLocation(2, 1)
);
verify1(comp1Ref,
@"namespace N2 {
using alias = N1.C1;
public class C2
{
}
}",
// (2,1): hidden CS8019: Unnecessary using directive.
// using alias = N1.C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using alias = N1.C1;").WithLocation(2, 1)
);
verify1(comp1Ref,
@"namespace N2 {
using alias = N1;
public class C2
{
}
}",
// (2,1): hidden CS8019: Unnecessary using directive.
// using alias = N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using alias = N1;").WithLocation(2, 1)
);
verify1(comp1Ref.WithAliases(new[] { "N1C1" }),
@"namespace N2 {
extern alias N1C1;
public class C2
{
}
}",
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1)
);
verify2(comp1Ref,
@"
public class C2
{
}
",
"N1");
verify2(comp1Ref,
@"
public class C2
{
}
",
"N1.C1");
static void verify1(MetadataReference reference, string source, params DiagnosticDescription[] expected)
{
Compilation comp = CreateCompilation(source, references: new[] { reference });
foreach (var c in CloneCompilationsWithUsings(comp, expected, null))
{
verify(c.comp, c.before);
}
static void verify(Compilation comp, params DiagnosticDescription[] expected)
{
comp.VerifyDiagnostics(expected);
Assert.True(comp.References.Count() > 1);
var used = comp.GetUsedAssemblyReferences();
Assert.Equal(1, used.Length);
Assert.Same(comp.ObjectType.ContainingAssembly, comp.GetAssemblyOrModuleSymbol(used[0]));
}
}
void verify2(MetadataReference reference, string source, string @using)
{
AssertUsedAssemblyReferences(CreateCompilation(Parse(source, options: TestOptions.Script), references: new[] { reference }, options: TestOptions.DebugDll.WithUsings(@using)),
reference);
}
}
[Fact]
public void MethodDeclaration_01()
{
var source1 =
@"
namespace N1
{
public class C1
{
public class C11
{
}
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
verify(comp1Ref,
@"
public class C2
{
public static N1.C1.C11 M1() => null;
}
");
verify(comp1Ref,
@"
using N2 = N1;
public class C2
{
public static N2.C1.C11 M1() => null;
}
");
verify(comp1Ref,
@"
using N1;
public class C2
{
public static C1.C11 M1() => null;
}
");
verify(comp1Ref,
@"
using static N1.C1;
public class C2
{
public static C11 M1() => null;
}
");
verify(comp1Ref,
@"
using C111 = N1.C1.C11;
public class C2
{
public static C111 M1() => null;
}
");
void verify(MetadataReference reference, string source2)
{
AssertUsedAssemblyReferences(source2, reference);
}
}
[Fact]
public void NoPia_01()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static ITest33 F0 = null;
public static int F1 = 0;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = C1.F1;
}
}
";
verify<PEAssemblySymbol>(source2, comp0ImageRef, comp1ImageRef);
verify<PEAssemblySymbol>(source2, comp0Ref, comp1ImageRef);
verify<RetargetingAssemblySymbol>(source2, comp0Ref, comp1Ref);
verify<RetargetingAssemblySymbol>(source2, comp0ImageRef, comp1Ref);
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify<PEAssemblySymbol>(source2, comp3ImageRef, comp1ImageRef);
verify<PEAssemblySymbol>(source2, comp3Ref, comp1ImageRef);
verify<RetargetingAssemblySymbol>(source2, comp3Ref, comp1Ref);
verify<RetargetingAssemblySymbol>(source2, comp3ImageRef, comp1Ref);
void verify<TAssemblySymbol>(string source2, MetadataReference reference0, MetadataReference reference1) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, new[] { reference0, reference1 }, reference1);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference1));
}
}
[Fact]
public void NoPia_02()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static ITest33 F0 = null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
_ = C1.F0;
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.F0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.F0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_03()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static ITest33 M0() => null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
C1.M0();
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.M0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.M0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_04()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static object M0(ITest33 x) => null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
C1.M0(null);
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.M0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.M0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_05()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public delegate void DTest33();
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
#pragma warning disable CS0414
public class C1
{
public static event DTest33 E0 = null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
C1.E0 += Main;
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.E0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.E0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_06()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static ITest33 P0 => null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
_ = C1.P0;
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.P0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.P0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_07()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public object this[ITest33 x] => null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
_ = new C1()[null];
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_08()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1 : ITest33, I1
{
}
public interface I1
{
}
public class C2 : I2<ITest33>, I1
{
}
public class C3 : C2
{
}
public interface I2<out T>
{
}
public interface I3 : ITest33, I1
{
}
public interface I4 : I3
{
}
public struct S1 : ITest33, I1
{
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C
{
public static void Main()
{
_ = (I2<object>)new C2();
}
}
");
verify(
@"
public class C
{
public static void Main()
{
_ = (I1)new C2();
}
}
");
verify(
@"
public class C
{
public static void Main()
{
_ = (I1)new C1();
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I2<object> x = new C2();
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I1 x = new C2();
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I1 x = new C1();
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
_ = (I2<object>)new C3();
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I2<object> x = new C3();
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I3 x = null;
I1 y = x;
_ = y;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I4 x = null;
I1 y = x;
_ = y;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I<C1[]> x = null;
I<I1[]> y = x;
_ = y;
}
}
interface I<out T> {}
");
verify(
@"
public class C
{
public static void Main()
{
I<C1> x = null;
I<I1> y = x;
_ = y;
}
}
interface I<out T> {}
");
verify(
@"
public class C
{
public static void Main()
{
I<I1>[] x = new I<C1>[10];
_ = x;
}
}
interface I<out T> {}
");
verify(
@"
public class C
{
public static void Main()
{
I1[] x = new C1[10];
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
S1? x = null;
I1 y = x;
_ = y;
}
}
");
verify(
@"
public class C
{
public static void Main<T>() where T : C1
{
T x = null;
I1 y = x;
_ = y;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I1 x = new A();
_ = x;
}
}
class A : C1 {}
");
verify(
@"
public class C
{
public static void Main()
{
IA x = null;
I1 y = x;
_ = y;
}
}
interface IA : I3 {}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_09()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1 : ITest33, I1
{
}
public interface I1
{
}
public interface I3 : ITest33, I1
{
}
public interface I4 : I3
{
}
public class C2
{
public static void M1<T>() where T : ITest33 {}
public static void M2<T>() where T : I3 {}
public static void M3<T>() where T : C1 {}
public static void M4<T>() where T : I1 {}
}
public class C3<T> where T : I1
{
}
public static class C4<T> where T : I1
{
public static void M5() {}
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M4<I3>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M4<C1>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M3<C1>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M2<I4>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M2<I3>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M1<I4>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M1<I3>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M1<C1>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C : I3
{
}
");
compileWithUsedAssemblyReferences(
@"
public class C : C1
{
}
");
compileWithUsedAssemblyReferences(
@"
interface IA : I3 {}
");
compileWithUsedAssemblyReferences(
@"
using static C4<I3>;
public class C
{
static void Main()
{
M5();
}
}
");
verifyNotUsed(
@"
using static C4<I3>;
public class C
{
static void Main()
{
}
}
");
verifyNotUsed(
@"
using alias = C3<I3>;
public class C
{
static void Main()
{
}
}
");
compileWithUsedAssemblyReferences(
@"
using alias = C3<I3>;
public class C
{
static void Main()
{
_ = new alias();
}
}
");
void compileWithUsedAssemblyReferences(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
void verifyNotUsed(string source2)
{
verifyNotUsed(source2, comp0ImageRef, comp1ImageRef);
verifyNotUsed(source2, comp0Ref, comp1ImageRef);
verifyNotUsed(source2, comp0Ref, comp1Ref);
verifyNotUsed(source2, comp0ImageRef, comp1Ref);
verifyNotUsed(source2, comp3ImageRef, comp1ImageRef);
verifyNotUsed(source2, comp3Ref, comp1ImageRef);
verifyNotUsed(source2, comp3Ref, comp1Ref);
verifyNotUsed(source2, comp3ImageRef, comp1Ref);
void verifyNotUsed(string source2, MetadataReference ref0, MetadataReference ref1)
{
var comp = CreateCompilation(source2, references: new[] { ref0, ref1 });
foreach (var c in CloneCompilationsWithUsings(comp, null, null))
{
var used = c.comp.GetUsedAssemblyReferences();
Assert.DoesNotContain(ref0, used);
Assert.DoesNotContain(ref1, used);
}
}
}
}
[Fact]
public void ArraysAndPointers_01()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
}
public struct S<T>
{ }
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = C1<S<C0>*[]>.E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<S<C0>*[]>;
public class C2
{
public static void Main()
{
_ = E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<S<C0>*[]>.E1;
public class C2
{
public static void Main()
{
_ = F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<S<C0>*[]>.E1;
public class C2
{
public static void Main()
{
_ = alias.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<S<C0>*[]>;
public class C2
{
public static void Main()
{
_ = alias.E1.F1 + 1;
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void TypeReference_01()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = nameof(C1<C0>.E1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(E1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = nameof(alias);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(alias.E1);
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void TypeReference_02()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
class C2
{
/// <summary>
/// <see cref=""C1{C0}.E1""/>
/// </summary>
static void Main()
{
}
}
",
hasTypeReferencesInUsing: false);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
class C2
{
/// <summary>
/// <see cref=""E1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
class C2
{
/// <summary>
/// <see cref=""alias""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
class C2
{
/// <summary>
/// <see cref=""alias.E1""/>
/// </summary>
static void Main()
{
}
}
");
var source2 =
@"
class C2
{
static void Main1()
{
}
}
";
var references = new[] { comp0Ref, comp1Ref };
AssertUsedAssemblyReferences(CreateCompilation(source2, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.None),
options: TestOptions.DebugDll.WithUsings("C0")),
comp0Ref);
AssertUsedAssemblyReferences(CreateCompilation(source2, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.Parse),
options: TestOptions.DebugDll.WithUsings("C0")),
comp0Ref);
void verify(MetadataReference reference0, MetadataReference reference1, string source, bool hasTypeReferencesInUsing = true)
{
var references = new[] { reference0, reference1 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, hasTypeReferencesInUsing ? references : new MetadataReference[] { }, references);
var expected = hasTypeReferencesInUsing ? references : new[] { reference1 };
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, expected);
Compilation comp4 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
AssertUsedAssemblyReferences(comp4, expected);
}
}
[Fact]
public void TypeReference_03()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
class C2
{
/// <summary>
/// <see cref=""M(C1{C0}.E1)""/>
/// </summary>
static void Main()
{
}
void M(int x) {}
}
",
hasTypeReferencesInUsing: false);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
class C2
{
/// <summary>
/// <see cref=""M(E1)""/>
/// </summary>
static void Main()
{
}
void M(int x) {}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
class C2
{
/// <summary>
/// <see cref=""M(alias)""/>
/// </summary>
static void Main()
{
}
void M(int x) {}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
class C2
{
/// <summary>
/// <see cref=""M(alias.E1)""/>
/// </summary>
static void Main()
{
}
void M(int x) {}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source, bool hasTypeReferencesInUsing = true)
{
var references = new[] { reference0, reference1 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, hasTypeReferencesInUsing ? references : new MetadataReference[] { }, references);
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, references);
}
}
[Fact]
public void TypeReference_04()
{
var source0 =
@"
public class C0
{
public class C1
{
public static void M1() {}
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C2 : C0
{
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
CompileWithUsedAssemblyReferences(@"
public class C3
{
public static void Main()
{
_ = new C2.C1();
}
}
", comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(@"
public class C3 : C2.C1
{
public static void Main()
{
}
}
", comp0Ref, comp1Ref);
var used = CompileWithUsedAssemblyReferences(@"
public class C3 : C0
{
public static void Main()
{
}
}
", comp0Ref, comp1Ref);
Assert.DoesNotContain(comp1Ref, used);
var comp = CreateCompilation(@"
using static C2.C1;
public class C3
{
public static void Main()
{
}
}
", references: new[] { comp0Ref, comp1Ref });
foreach (var c in CloneCompilationsWithUsings(comp, null, null))
{
used = c.comp.GetUsedAssemblyReferences();
Assert.DoesNotContain(comp0Ref, used);
Assert.DoesNotContain(comp1Ref, used);
}
comp = CreateCompilation(@"
using alias = C2.C1;
public class C3
{
public static void Main()
{
}
}
", references: new[] { comp0Ref, comp1Ref });
foreach (var c in CloneCompilationsWithUsings(comp, null, null))
{
used = c.comp.GetUsedAssemblyReferences();
Assert.DoesNotContain(comp0Ref, used);
Assert.DoesNotContain(comp1Ref, used);
}
CompileWithUsedAssemblyReferences(@"
using static C2.C1;
public class C3
{
public static void Main()
{
M1();
}
}
", comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(@"
using alias = C2.C1;
public class C3
{
public static void Main()
{
_ = new alias();
}
}
", comp0Ref, comp1Ref);
}
[Fact]
public void NamespaceReference_01()
{
var source0 =
@"
namespace N1.N2
{
public enum E0
{
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace N1.N2
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
namespace N1
{
public enum E2
{
}
}
";
var comp2 = CreateCompilation(source2);
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
verify(comp0Ref, comp1Ref, comp2Ref,
@"
public class C2
{
public static void Main()
{
_ = nameof(N1.N2);
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2;
public class C2
{
public static void Main()
{
_ = nameof(alias);
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1;
public class C2
{
public static void Main()
{
_ = nameof(alias.N2);
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, MetadataReference reference2, string source)
{
AssertUsedAssemblyReferences(source, new[] { reference0, reference1, reference2 }, reference0, reference1);
}
}
[Fact]
public void NamespaceReference_02()
{
var source0 =
@"
namespace N1.N2
{
public enum E0
{
F0
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace N1.N2
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
namespace N1
{
public enum E2
{
}
}
";
var comp2 = CreateCompilation(source2);
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
verify(comp0Ref, comp1Ref, comp2Ref,
@"
public class C2
{
public static void Main()
{
_ = N1.N2.E0.F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2.E0;
public class C2
{
public static void Main()
{
_ = alias.F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using static N1.N2.E0;
public class C2
{
public static void Main()
{
_ = F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2;
public class C2
{
public static void Main()
{
_ = alias.E0.F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using N1.N2;
public class C2
{
public static void Main()
{
_ = E0.F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1;
public class C2
{
public static void Main()
{
_ = alias.N2.E0.F0;
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, MetadataReference reference2, string source)
{
AssertUsedAssemblyReferences(source, new[] { reference0, reference1, reference2 }, reference0);
}
}
[Fact]
public void NamespaceReference_03()
{
var source0 =
@"
namespace N1.N2
{
public enum E0
{
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace N1.N2
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
namespace N1
{
public enum E2
{
}
}
";
var comp2 = CreateCompilation(source2);
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
verify(comp0Ref, comp1Ref, comp2Ref,
@"
class C2
{
/// <summary>
/// <see cref=""N1.N2""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2;
class C2
{
/// <summary>
/// <see cref=""alias""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 2
);
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1;
class C2
{
/// <summary>
/// <see cref=""alias.N2""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 1
);
var source3 =
@"
using N1.N2;
class C2
{
static void Main()
{
}
}
";
var references = new[] { comp0Ref, comp1Ref, comp2Ref };
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1.N2;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1.N2;").WithLocation(1001, 1)
},
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1.N2;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1.N2;").WithLocation(1001, 1),
// (1001,7): error CS0246: The type or namespace name 'N1' could not be found (are you missing a using directive or an assembly reference?)
// using N1.N2;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "N1").WithArguments("N1").WithLocation(1001, 7)
}, references);
var source4 =
@"
using N1;
class C2
{
static void Main()
{
}
}
";
AssertUsedAssemblyReferences(CreateCompilation(source4, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
references);
AssertUsedAssemblyReferences(CreateCompilation(source4, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1;").WithLocation(1001, 1)
},
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1;").WithLocation(1001, 1),
// (1001,7): error CS0246: The type or namespace name 'N1' could not be found (are you missing a
// using N1;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "N1").WithArguments("N1").WithLocation(1001, 7)
}, references);
var source5 =
@"
class C2
{
static void Main1()
{
}
}
";
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.None),
options: TestOptions.DebugDll.WithUsings("N1.N2")),
comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.Parse),
options: TestOptions.DebugDll.WithUsings("N1.N2")),
comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.None),
options: TestOptions.DebugDll.WithUsings("N1")),
references);
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.Parse),
options: TestOptions.DebugDll.WithUsings("N1")),
references);
void verify(MetadataReference reference0, MetadataReference reference1, MetadataReference reference2, string source, int namespaceOrdinalReferencedInUsings = 0)
{
var references = new[] { reference0, reference1, reference2 };
var expected = new[] { reference0, reference1 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, namespaceOrdinalReferencedInUsings switch { 1 => references, 2 => expected, _ => new MetadataReference[] { } }, references);
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, expected);
Compilation comp4 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
AssertUsedAssemblyReferences(comp4, expected);
}
}
[Fact]
public void NamespaceReference_04()
{
var source0 =
@"
namespace N1.N2
{
public enum E0
{
F0
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace N1.N2
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
namespace N1
{
public enum E2
{
}
}
";
var comp2 = CreateCompilation(source2);
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
verify(comp0Ref, comp1Ref, comp2Ref,
@"
class C2
{
/// <summary>
/// <see cref=""N1.N2.E0""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2;
class C2
{
/// <summary>
/// <see cref=""alias.E0""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 2
);
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2.E0;
class C2
{
/// <summary>
/// <see cref=""alias""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 3
);
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using static N1.N2.E0;
class C2
{
/// <summary>
/// <see cref=""F0""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 3
);
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1;
class C2
{
/// <summary>
/// <see cref=""alias.N2.E0""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 1
);
var source3 =
@"
using static N1.N2.E0;
class C2
{
static void Main()
{
}
}
";
var references = new[] { comp0Ref, comp1Ref, comp2Ref };
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
new[] { comp0Ref }, references);
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static N1.N2.E0;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N1.N2.E0;").WithLocation(1001, 1)
},
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static N1.N2.E0;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N1.N2.E0;").WithLocation(1001, 1),
// (1001,14): error CS0246: The type or namespace name 'N1' could not be found (are you missing a using directive or an assembly reference?)
// using static N1.N2.E0;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "N1").WithArguments("N1").WithLocation(1001, 14)
}, references);
var source5 =
@"
class C2
{
static void Main1()
{
}
}
";
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.None),
options: TestOptions.DebugDll.WithUsings("N1.N2.E0")),
new[] { comp0Ref }, references);
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.Parse),
options: TestOptions.DebugDll.WithUsings("N1.N2.E0")),
new[] { comp0Ref }, references);
void verify(MetadataReference reference0, MetadataReference reference1, MetadataReference reference2, string source, int namespaceOrdinalReferencedInUsings = 0)
{
var references = new[] { reference0, reference1, reference2 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, namespaceOrdinalReferencedInUsings switch { 1 => references, 2 => new[] { reference0, reference1 }, 3 => new[] { reference0 }, _ => new MetadataReference[] { } }, references);
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, new[] { reference0 }, references);
Compilation comp4 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
AssertUsedAssemblyReferences(comp4, new[] { reference0 }, references);
}
}
[Fact]
public void NamespaceReference_05()
{
var source1 =
@"
using global;
class C2
{
static void Main()
{
}
}
";
CreateCompilation(source1, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)).VerifyDiagnostics(
// (2,7): error CS0246: The type or namespace name 'global' could not be found (are you missing a using directive or an assembly reference?)
// using global;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "global").WithArguments("global").WithLocation(2, 7)
);
var source2 =
@"
using alias = global;
class C2
{
static void Main()
{
}
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)).VerifyDiagnostics(
// (2,15): error CS0246: The type or namespace name 'global' could not be found (are you missing a using directive or an assembly reference?)
// using alias = global;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "global").WithArguments("global").WithLocation(2, 15)
);
}
[Fact]
public void NamespaceReference_06()
{
var source1 =
@"
using global::;
class C2
{
static void Main()
{
}
}
";
CreateCompilation(source1, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)).VerifyDiagnostics(
// (2,15): error CS1001: Identifier expected
// using global::;
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(2, 15)
);
var source2 =
@"
using alias = global::;
class C2
{
static void Main()
{
}
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)).VerifyDiagnostics(
// (2,23): error CS1001: Identifier expected
// using alias = global::;
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(2, 23)
);
}
[Fact]
public void EventReference_01()
{
var source0 =
@"
public delegate void D0();
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public static event D0 E1;
void Use()
{
E1();
}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
C1.E1 += null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main()
{
C1.E1 -= null;
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
var source4 =
@"
using static C1;
public class C2
{
public static void Main()
{
E1 += null;
}
}
";
AssertUsedAssemblyReferences(source4, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source4, comp0Ref, comp1ImageRef);
var source5 =
@"
using static C1;
public class C3
{
public static void Main()
{
E1 -= null;
}
}
";
AssertUsedAssemblyReferences(source5, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source5, comp0Ref, comp1ImageRef);
}
[Fact]
public void EventReference_02()
{
var source0 =
@"
public delegate void D0();
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public event D0 E1;
void Use()
{
E1();
}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main(C1 x)
{
x.E1 += null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main(C1 x)
{
x.E1 -= null;
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
}
[Fact]
public void PropertyReference_01()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public static C0 P1 {get; set;}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
C1.P1 = null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main()
{
_ = C1.P1;
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
var source4 =
@"
using static C1;
public class C2
{
public static void Main()
{
P1 = null;
}
}
";
AssertUsedAssemblyReferences(source4, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source4, comp0Ref, comp1ImageRef);
var source5 =
@"
using static C1;
public class C3
{
public static void Main()
{
_ = P1;
}
}
";
AssertUsedAssemblyReferences(source5, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source5, comp0Ref, comp1ImageRef);
}
[Fact]
public void PropertyReference_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public C0 P1 {get; set;}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main(C1 x)
{
x.P1 = null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main(C1 x)
{
_ = x.P1;
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
}
[Fact]
public void IndexerReference_01()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0ImageRef = comp0.EmitToImageReference();
var source1 =
@"
Public Class C1
Public Shared Property P1(x As Integer) As C0
Get
Return Nothing
End Get
Set
End Set
End Property
Public Shared Property P2(x As Integer) As C0
Get
Return Nothing
End Get
Set
End Set
End Property
Public Shared Property P2(x As String) As C0
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
";
var comp1 = CreateVisualBasicCompilation(source1, referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { comp0ImageRef }));
comp1.VerifyDiagnostics();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
C1.P1[0] = null;
}
}
";
var references = new[] { comp0ImageRef, comp1ImageRef };
AssertUsedAssemblyReferences(source2, references,
// (6,12): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// C1.P1[0] = null;
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(6, 12)
);
var source3 =
@"
public class C3
{
public static void Main()
{
_ = C1.P1[0];
}
}
";
AssertUsedAssemblyReferences(source3, references,
// (6,16): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// _ = C1.P1[0];
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(6, 16)
);
var source4 =
@"
using static C1;
public class C2
{
public static void Main()
{
P1[0] = null;
}
}
";
AssertUsedAssemblyReferences(source4, references,
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,9): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// P1[0] = null;
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(2005, 9)
);
var source5 =
@"
using static C1;
public class C3
{
public static void Main()
{
_ = P1[0];
}
}
";
AssertUsedAssemblyReferences(source5, references,
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,13): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// _ = P1[0];
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(2005, 13)
);
var source6 =
@"
public class C3
{
public static void Main()
{
_ = nameof(C1.P1);
}
}
";
AssertUsedAssemblyReferences(source6, references,
// (6,23): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// _ = nameof(C1.P1);
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(6, 23)
);
var source7 =
@"
using static C1;
public class C2
{
public static void Main()
{
_ = nameof(P1);
}
}
";
AssertUsedAssemblyReferences(source7, references,
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,20): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// _ = nameof(P1);
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(2005, 20)
);
var source8 =
@"
public class C3
{
public static void Main()
{
_ = nameof(C1.P2);
}
}
";
AssertUsedAssemblyReferences(source8, references,
// (6,23): error CS1545: Property, indexer, or event 'C1.P2[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P2(int)' or 'C1.set_P2(int, C0)'
// _ = nameof(C1.P2);
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P2").WithArguments("C1.P2[int]", "C1.get_P2(int)", "C1.set_P2(int, C0)").WithLocation(6, 23)
);
var source9 =
@"
using static C1;
public class C2
{
public static void Main()
{
_ = nameof(P2);
}
}
";
AssertUsedAssemblyReferences(source9, references,
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,20): error CS1545: Property, indexer, or event 'C1.P2[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P2(int)' or 'C1.set_P2(int, C0)'
// _ = nameof(P2);
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P2").WithArguments("C1.P2[int]", "C1.get_P2(int)", "C1.set_P2(int, C0)").WithLocation(2005, 20)
);
}
[Fact]
public void IndexerReference_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public C0 this[int x] {get => default; set {}}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main(C1 x)
{
x[0] = null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main(C1 x)
{
_ = x[0];
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
}
[Fact]
public void WellKnownTypeReference_01()
{
var source0 =
@"
namespace System
{
public class Object {}
public class ValueType {}
public struct Void {}
}
";
var comp0 = CreateEmptyCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace System
{
public class Type
{
public static Type GetTypeFromHandle(RuntimeTypeHandle handle) => default;
}
public struct RuntimeTypeHandle {}
}
";
var comp1 = CreateEmptyCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class Type
{
}
";
var comp2 = CreateEmptyCompilation(source2, references: new[] { comp0Ref });
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
var source3 =
@"
public class C2
{
public static void Main()
{
_ = typeof(C2);
}
}
";
var references = new[] { comp0Ref, comp1Ref, comp2Ref };
var comp3 = CreateEmptyCompilation(source3, references: references);
AssertUsedAssemblyReferences(comp3, new[] { comp1Ref }, references);
var source4 =
@"
public class C2
{
public static void Main()
{
_ = typeof(Type);
}
}
";
var comp4 = CreateEmptyCompilation(source4, references: new[] { comp0Ref, comp1Ref, comp2Ref });
AssertUsedAssemblyReferences(comp4, comp1Ref, comp2Ref);
}
[Fact]
public void WellKnownTypeReference_02()
{
var source3 =
@"
public class C2
{
public static void Main()
{
dynamic x = new C1();
x.M1();
}
}
class C1
{
public void M1() {}
}
";
CompileWithUsedAssemblyReferences(source3, targetFramework: TargetFramework.StandardAndCSharp);
}
[Fact]
public void WellKnownTypeReference_03()
{
var source3 =
@"
public class C2
{
public static void Main()
{
var x = new {a = 1};
x.ToString();
}
}
";
CompileWithUsedAssemblyReferences(source3, targetFramework: TargetFramework.StandardAndCSharp);
}
[Fact]
public void WellKnownTypeReference_04()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
bool b = false;
(c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = b ? default : c.getDeconstructReceiver();
}
public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); }
}
class C1
{
public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
class D3
{
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforX
getHolderforY
getHolderforZ
getDeconstructReceiver
Deconstruct1
Deconstruct2
Conversion1
Conversion2
Conversion3
setX
setY
setZ
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
CompileWithUsedAssemblyReferences(comp, expectedOutput: expected);
}
[Fact]
public void WellKnownTypeReference_05()
{
var source1 =
@"
namespace System.Runtime.CompilerServices
{
public class IsUnmanagedAttribute : System.Attribute { }
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
#pragma warning disable CS8321
public class Test
{
public void M()
{
void N<T>() where T : unmanaged
{
}
}
}
";
CompileWithUsedAssemblyReferences(source2, options: TestOptions.DebugModule, comp1Ref);
}
[Fact]
public void WellKnownTypeReference_06()
{
var source2 =
@"
public static class Test
{
public static void M(this string x)
{
}
}
";
CompileWithUsedAssemblyReferences(source2, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
}
[Fact]
public void Deconstruction_01()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void Deconstruct(this C0 x, out int y, out int z) => throw null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
var (y, z) = new C0();
_ = y;
_ = z;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
}
[Fact]
public void Deconstruction_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void Deconstruct(this C0 x, out int y, out int z) => throw null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
var (x, (y, z)) = (1, new C0());
_ = x;
_ = y;
_ = z;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
}
[Fact]
public void ExternAliases_01()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
var source1 =
@"
public static class C1
{
public static C0 F1;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1RefWithAlias = comp1Ref.WithAliases(new[] { "Alias0" });
var source2 =
@"
extern alias Alias0;
public class C2
{
public static void Main()
{
var x = new Alias0::C0();
_ = x;
}
}
";
var used = CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp1RefWithAlias);
Assert.DoesNotContain(comp1RefWithAlias, used);
used = CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp1Ref);
Assert.DoesNotContain(comp1Ref, used);
CreateCompilation(source2, references: new[] { comp0Ref, comp1RefWithAlias }).VerifyDiagnostics(
// (8,29): error CS0234: The type or namespace name 'C0' does not exist in the namespace 'Alias0' (are you missing an assembly reference?)
// var x = new Alias0::C0();
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "C0").WithArguments("C0", "Alias0").WithLocation(8, 29)
);
}
[Fact]
public void ExternAliases_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
MetadataReference comp0Ref = comp0.ToMetadataReference();
var comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
var source2 =
@"
extern alias Alias0;
public class C2
{
public static void Main()
{
var x = new Alias0::C0();
_ = x;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
comp0Ref = comp0.EmitToImageReference();
comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
}
[Fact]
public void ExternAliases_03()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
MetadataReference comp0Ref = comp0.ToMetadataReference();
var comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
var source2 =
@"
public class C2
{
public static void Main()
{
var x = new global::C0();
_ = x;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
comp0Ref = comp0.EmitToImageReference();
comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
}
[Fact]
public void ExternAliases_04()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
MetadataReference comp0Ref = comp0.ToMetadataReference();
var comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
var source2 =
@"
public class C2
{
public static void Main()
{
var x = new C0();
_ = x;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
comp0Ref = comp0.EmitToImageReference();
comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
}
[Fact]
public void ExternAliases_05()
{
var source1 =
@"
namespace N1
{
public static class C1
{
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference().WithAliases(new[] { "N1C1" });
var source2 =
@"
namespace N1
{
public static class C2
{
}
}
";
var comp2 = CreateCompilation(source2);
var comp2Ref = comp2.ToMetadataReference();
var source3 =
@"
extern alias N1C1;
public class C2
{
}
";
var references = new[] { comp1Ref, comp2Ref };
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
comp1Ref);
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1)
},
new[] {
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1),
// (2,14): error CS0430: The extern alias 'N1C1' was not specified in a /reference option
// extern alias N1C1;
Diagnostic(ErrorCode.ERR_BadExternAlias, "N1C1").WithArguments("N1C1").WithLocation(2, 14)
}, references);
comp2Ref = comp2.ToMetadataReference().WithAliases(new[] { "N1C1" });
references = new[] { comp1Ref, comp2Ref };
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
references);
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1)
},
new[] {
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1),
// (2,14): error CS0430: The extern alias 'N1C1' was not specified in a /reference option
// extern alias N1C1;
Diagnostic(ErrorCode.ERR_BadExternAlias, "N1C1").WithArguments("N1C1").WithLocation(2, 14)
}, references);
var source4 =
@"
extern alias N1C1;
public class C2
{
static void Main()
{
_ = nameof(N1C1);
}
}
";
CompileWithUsedAssemblyReferences(source4, references);
}
[Fact]
public void ExternAliases_06()
{
var source1 =
@"
namespace N1
{
public static class C1
{
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference().WithAliases(new[] { "N1C1" });
var source4 =
@"
extern alias N1C1;
public class C2
{
#pragma warning disable CS1574 //: XML comment has cref attribute 'N1C1::BadType' that could not be resolved
/// <summary>
/// See <see cref=""N1C1::BadType""/>.
/// </summary>
static void Main()
{
}
}
";
CompileWithUsedAssemblyReferences(source4, comp1Ref);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class UsedAssembliesTests : CSharpTestBase
{
[Fact]
public void NoReferences_01()
{
var source =
@"
interface I1
{
public I1 M();
}
";
var comp1 = CreateEmptyCompilation(source);
CompileAndVerify(comp1);
Assert.Empty(comp1.GetUsedAssemblyReferences());
var comp2 = CreateCompilation(source);
CompileAndVerify(comp2);
AssertUsedAssemblyReferences(comp2);
}
[Fact]
public void NoReferences_02()
{
var source =
@"
public interface I1
{
public I1 M();
}
";
var comp1 = CreateEmptyCompilation(source);
CompileAndVerify(comp1);
var source2 =
@"
public class C2
{
public static void Main(I1 x)
{
x.M();
}
}
";
verify<PEAssemblySymbol>(source2, comp1.EmitToImageReference());
verify<RetargetingAssemblySymbol>(source2, comp1.ToMetadataReference());
Assert.Empty(comp1.GetUsedAssemblyReferences());
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
private void AssertUsedAssemblyReferences(Compilation comp, MetadataReference[] expected, DiagnosticDescription[] before, DiagnosticDescription[] after, MetadataReference[] specificReferencesToAssert)
{
foreach (var c in CloneCompilationsWithUsings(comp, before, after))
{
assertUsedAssemblyReferences(c.comp, expected, c.before, c.after, specificReferencesToAssert);
}
void assertUsedAssemblyReferences(Compilation comp, MetadataReference[] expected, DiagnosticDescription[] before, DiagnosticDescription[] after, MetadataReference[] specificReferencesToAssert)
{
comp.VerifyDiagnostics(before);
bool hasCoreLibraryRef = !comp.ObjectType.IsErrorType();
var used = comp.GetUsedAssemblyReferences();
if (hasCoreLibraryRef)
{
Assert.Same(comp.ObjectType.ContainingAssembly, comp.GetAssemblyOrModuleSymbol(used[0]));
AssertEx.Equal(expected, used.Skip(1));
}
else
{
AssertEx.Equal(expected, used);
}
Assert.Empty(used.Where(r => r.Properties.Kind == MetadataImageKind.Module));
var comp2 = comp.RemoveAllReferences().AddReferences(used.Concat(comp.References.Where(r => r.Properties.Kind == MetadataImageKind.Module)));
if (!after.Any(d => ErrorFacts.GetSeverity((ErrorCode)d.Code) == DiagnosticSeverity.Error))
{
CompileAndVerify(comp2, verify: Verification.Skipped).Diagnostics.Where(d => d.Code != (int)ErrorCode.WRN_NoRuntimeMetadataVersion).Verify(after);
if (specificReferencesToAssert is object)
{
var tryRemove = specificReferencesToAssert.Where(reference => reference.Properties.Kind == MetadataImageKind.Assembly && !used.Contains(reference));
if (tryRemove.Count() > 1)
{
foreach (var reference in tryRemove)
{
var comp3 = comp.RemoveReferences(reference);
CompileAndVerify(comp3, verify: Verification.Skipped).Diagnostics.Where(d => d.Code != (int)ErrorCode.WRN_NoRuntimeMetadataVersion).Verify(after);
}
}
}
}
else
{
comp2.VerifyDiagnostics(after);
}
}
}
private static IEnumerable<(Compilation comp, DiagnosticDescription[] before, DiagnosticDescription[] after)> CloneCompilationsWithUsings(Compilation comp, DiagnosticDescription[] before, DiagnosticDescription[] after)
{
var tree = comp.SyntaxTrees.Single();
var unit = (CompilationUnitSyntax)tree.GetRoot();
if (!unit.Usings.Any())
{
yield return (comp, before, after);
yield break;
}
var source = unit.ToFullString();
var beforeUsings = source.Substring(0, unit.Usings.First().FullSpan.Start);
var afterUsings = source.Substring(unit.Usings.Last().FullSpan.End);
// With regular usings
var builder = new System.Text.StringBuilder();
builder.Append(beforeUsings);
builder.Append(@"
#line 1000
");
foreach (var directive in unit.Usings)
{
builder.Append(directive.ToFullString());
}
builder.Append(@"
#line 2000
");
builder.Append(afterUsings);
yield return (comp.ReplaceSyntaxTree(tree, CSharpTestBase.Parse(builder.ToString(), tree.FilePath, (CSharpParseOptions)tree.Options)), before, after);
// With global usings
before = adjustDiagnosticDescription(before);
after = adjustDiagnosticDescription(after);
builder.Clear();
builder.Append(@"
#line 1000
");
foreach (var directive in unit.Usings)
{
builder.Append(directive.ToFullString().Replace("using", "global using"));
}
var globalUsings = builder.ToString();
builder.Clear();
builder.Append(beforeUsings);
builder.Append(globalUsings);
builder.Append(@"
#line 2000
");
builder.Append(afterUsings);
var parseOptions = ((CSharpParseOptions)tree.Options).WithLanguageVersion(LanguageVersion.CSharp10);
yield return (comp.ReplaceSyntaxTree(tree, CSharpTestBase.Parse(builder.ToString(), tree.FilePath, parseOptions)), before, after);
// With global usings in a separate unit
builder.Clear();
builder.Append(beforeUsings);
builder.Append(@"
#line 2000
");
builder.Append(afterUsings);
yield return (comp.ReplaceSyntaxTree(tree, CSharpTestBase.Parse(builder.ToString(), tree.FilePath, parseOptions)).
AddSyntaxTrees(CSharpTestBase.Parse(globalUsings, "", parseOptions)), before, after);
static DiagnosticDescription[] adjustDiagnosticDescription(DiagnosticDescription[] input)
{
if (input is null)
{
return null;
}
DiagnosticDescription[] output = null;
for (int i = 0; i < input.Length; i++)
{
var old = input[i];
if (old.Code is (int)ErrorCode.HDN_UnusedUsingDirective)
{
allocateOutput(input, ref output)[i] = old.WithSquiggledText("global " + old.SquiggledText);
}
else if (old.LocationLine is > 1000 and < 2000)
{
allocateOutput(input, ref output)[i] = old.WithLocation(old.LocationLine, old.LocationCharacter + 7);
}
}
return output ?? input;
}
static DiagnosticDescription[] allocateOutput(DiagnosticDescription[] input, ref DiagnosticDescription[] output)
{
if (output is null)
{
System.Array.Copy(input, output = new DiagnosticDescription[input.Length], input.Length);
}
return output;
}
}
private void AssertUsedAssemblyReferences(Compilation comp, params MetadataReference[] expected)
{
AssertUsedAssemblyReferences(comp, expected, new DiagnosticDescription[] { }, new DiagnosticDescription[] { }, specificReferencesToAssert: null);
}
private void AssertUsedAssemblyReferences(Compilation comp, MetadataReference[] expected, MetadataReference[] specificReferencesToAssert)
{
AssertUsedAssemblyReferences(comp, expected, new DiagnosticDescription[] { }, new DiagnosticDescription[] { }, specificReferencesToAssert);
}
private Compilation AssertUsedAssemblyReferences(string source, MetadataReference[] references, params MetadataReference[] expected)
{
Compilation comp = CreateCompilation(source, references: references);
AssertUsedAssemblyReferences(comp, expected, references);
return comp;
}
private Compilation AssertUsedAssemblyReferences(string source, params MetadataReference[] references)
{
return AssertUsedAssemblyReferences(source, references, references);
}
private static void AssertUsedAssemblyReferences(string source, MetadataReference[] references, params DiagnosticDescription[] expected)
{
Compilation comp = CreateCompilation(source, references: references);
foreach (var c in CloneCompilationsWithUsings(comp, expected, null))
{
assertUsedAssemblyReferences(c.comp, c.before);
}
static void assertUsedAssemblyReferences(Compilation comp, params DiagnosticDescription[] expected)
{
var diagnostics = comp.GetDiagnostics();
diagnostics.Verify(expected);
Assert.True(diagnostics.Any(d => d.DefaultSeverity == DiagnosticSeverity.Error));
AssertEx.Equal(comp.References.Where(r => r.Properties.Kind == MetadataImageKind.Assembly), comp.GetUsedAssemblyReferences());
}
}
private ImmutableArray<MetadataReference> CompileWithUsedAssemblyReferences(string source, TargetFramework targetFramework, params MetadataReference[] references)
{
return CompileWithUsedAssemblyReferences(source, targetFramework, options: null, references);
}
private ImmutableArray<MetadataReference> CompileWithUsedAssemblyReferences(string source, TargetFramework targetFramework, CSharpCompilationOptions options, params MetadataReference[] references)
{
options ??= TestOptions.ReleaseDll;
options = options.WithSpecificDiagnosticOptions(options.SpecificDiagnosticOptions.Add("CS1591", ReportDiagnostic.Suppress));
Compilation comp = CreateEmptyCompilation(source,
references: TargetFrameworkUtil.GetReferences(targetFramework).Concat(references),
options: options,
parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
return CompileWithUsedAssemblyReferences(comp, specificReferencesToAssert: references);
}
private ImmutableArray<MetadataReference> CompileWithUsedAssemblyReferences(Compilation comp, string expectedOutput = null, MetadataReference[] specificReferencesToAssert = null)
{
ImmutableArray<MetadataReference> result = default;
foreach (var c in CloneCompilationsWithUsings(comp, null, null))
{
var currentResult = compileWithUsedAssemblyReferences(c.comp, expectedOutput, specificReferencesToAssert);
if (result.IsDefault)
{
result = currentResult;
}
else
{
AssertEx.Equal(result, currentResult);
}
}
return result;
ImmutableArray<MetadataReference> compileWithUsedAssemblyReferences(Compilation comp, string expectedOutput = null, MetadataReference[] specificReferencesToAssert = null)
{
var used = comp.GetUsedAssemblyReferences();
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: expectedOutput).VerifyDiagnostics();
Assert.Empty(used.Where(r => r.Properties.Kind == MetadataImageKind.Module));
if (specificReferencesToAssert is object)
{
var tryRemove = specificReferencesToAssert.Where(reference => reference.Properties.Kind == MetadataImageKind.Assembly && !used.Contains(reference));
if (tryRemove.Count() > 1)
{
foreach (var reference in tryRemove)
{
var comp3 = comp.RemoveReferences(reference);
CompileAndVerify(comp3, verify: Verification.Skipped, expectedOutput: expectedOutput).VerifyDiagnostics();
}
}
}
var comp2 = comp.RemoveAllReferences().AddReferences(used.Concat(comp.References.Where(r => r.Properties.Kind == MetadataImageKind.Module)));
CompileAndVerify(comp2, verify: Verification.Skipped, expectedOutput: expectedOutput).VerifyDiagnostics();
return used;
}
}
private ImmutableArray<MetadataReference> CompileWithUsedAssemblyReferences(string source, params MetadataReference[] references)
{
return CompileWithUsedAssemblyReferences(source, TargetFramework.Standard, references);
}
private void CompileWithUsedAssemblyReferences(string source, CSharpCompilationOptions options, params MetadataReference[] references)
{
CompileWithUsedAssemblyReferences(source, TargetFramework.Standard, options: options, references);
}
[Fact]
public void NoReferences_03()
{
var source =
@"
namespace System
{
public class Object {}
public class ValueType {}
public struct Void {}
}
public interface I1
{
public I1 M();
}
";
var comp1 = CreateEmptyCompilation(source);
comp1.VerifyEmitDiagnostics(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1)
);
var source2 =
@"
public class C2
{
public static object Main(I1 x)
{
x.M();
return null;
}
}
";
verify<PEAssemblySymbol>(source2, comp1.EmitToImageReference());
verify<SourceAssemblySymbol>(source2, comp1.ToMetadataReference());
Assert.Empty(comp1.GetUsedAssemblyReferences());
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = CreateEmptyCompilation(source2, references: new[] { reference, SystemCoreRef, SystemDrawingRef });
AssertUsedAssemblyReferences(comp2);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void NoReferences_04()
{
var source =
@"
public interface I1
{
public I1 M1();
}
";
var comp1 = CreateEmptyCompilation(source);
CompileAndVerify(comp1);
var source2 =
@"
public interface I2
{
public I1 M2();
}
";
verify<PEAssemblySymbol>(source2, comp1.EmitToImageReference());
verify<RetargetingAssemblySymbol>(source2, comp1.ToMetadataReference());
Assert.Empty(comp1.GetUsedAssemblyReferences());
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = CreateEmptyCompilation(source2, references: new[] { reference, SystemCoreRef, SystemDrawingRef });
AssertUsedAssemblyReferences(comp2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void FieldReference_01()
{
var source1 =
@"
public class C1
{
public static int F1 = 0;
public int F2 = 0;
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = C1.F1;
}
}
";
verify<PEAssemblySymbol>(source2, comp1ImageRef);
verify<SourceAssemblySymbol>(source2, comp1Ref);
var source3 =
@"
public class C2
{
public static void Main()
{
C1 x = null;
_ = x.F2;
}
}
";
verify<PEAssemblySymbol>(source3, comp1ImageRef);
verify<SourceAssemblySymbol>(source3, comp1Ref);
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void FieldReference_02()
{
var source0 =
@"
public class C0
{
public static C0 F0 = new C0();
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var comp0ImageRef = comp0.EmitToImageReference();
var source1 =
@"
public class C1
{
public static C0 F0 = C0.F0;
public static int F1 = 0;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = C1.F1;
}
}
";
verify<PEAssemblySymbol>(source2, comp0ImageRef, comp1ImageRef);
verify<PEAssemblySymbol>(source2, comp0Ref, comp1ImageRef);
verify<SourceAssemblySymbol>(source2, comp0Ref, comp1Ref);
verify<RetargetingAssemblySymbol>(source2, comp0ImageRef, comp1Ref);
var source3 =
@"
using static C1;
public class C2
{
public static void Main()
{
Assert(F1);
}
[System.Diagnostics.Conditional(""Always"")]
public static void Assert(int condition) {}
}
";
verify<SourceAssemblySymbol>(source3, comp0Ref, comp1Ref);
void verify<TAssemblySymbol>(string source2, MetadataReference reference0, MetadataReference reference1) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference0, reference1);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference1));
}
}
[Fact]
public void FieldReference_03()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var comp0ImageRef = comp0.EmitToImageReference();
var source1 =
@"
class C1
{
static C0 F0 = new C0();
public static C1 F1 = new C1();
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref }, options: TestOptions.DebugModule);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
static C1 F1 = C1.F1;
public static int F2 = 0;
}
";
var comp2 = verify2<SourceAssemblySymbol>(source2, comp0Ref, comp1Ref);
var comp2Ref = comp2.ToMetadataReference();
var comp2ImageRef = comp2.EmitToImageReference();
var source3 =
@"
public class C3
{
public static void Main()
{
_ = C2.F2;
}
}
";
verify3<PEAssemblySymbol>(source3, comp0ImageRef, comp2ImageRef);
verify3<PEAssemblySymbol>(source3, comp0Ref, comp2ImageRef);
verify3<SourceAssemblySymbol>(source3, comp0Ref, comp2Ref);
verify3<RetargetingAssemblySymbol>(source3, comp0ImageRef, comp2Ref);
verify3<PEAssemblySymbol>(source3, comp2ImageRef);
verify3<RetargetingAssemblySymbol>(source3, comp2Ref);
comp2 = verify2<PEAssemblySymbol>(source2, comp0ImageRef, comp1Ref);
comp2Ref = comp2.ToMetadataReference();
comp2ImageRef = comp2.EmitToImageReference();
verify3<PEAssemblySymbol>(source3, comp0ImageRef, comp2ImageRef);
verify3<PEAssemblySymbol>(source3, comp0Ref, comp2ImageRef);
verify3<RetargetingAssemblySymbol>(source3, comp0Ref, comp2Ref);
verify3<SourceAssemblySymbol>(source3, comp0ImageRef, comp2Ref);
verify3<PEAssemblySymbol>(source3, comp2ImageRef);
verify3<RetargetingAssemblySymbol>(source3, comp2Ref);
comp2 = CreateCompilation(source2, references: new[] { comp1Ref });
comp2.VerifyDiagnostics();
Assert.True(comp2.References.Count() > 1);
var used = comp2.GetUsedAssemblyReferences();
Assert.Equal(1, used.Length);
Assert.Same(comp2.ObjectType.ContainingAssembly, comp2.GetAssemblyOrModuleSymbol(used[0]));
comp2Ref = comp2.ToMetadataReference();
comp2ImageRef = comp2.EmitToImageReference();
verify3<PEAssemblySymbol>(source3, comp0ImageRef, comp2ImageRef);
verify3<PEAssemblySymbol>(source3, comp0Ref, comp2ImageRef);
verify3<RetargetingAssemblySymbol>(source3, comp0Ref, comp2Ref);
verify3<RetargetingAssemblySymbol>(source3, comp0ImageRef, comp2Ref);
verify3<PEAssemblySymbol>(source3, comp2ImageRef);
verify3<SourceAssemblySymbol>(source3, comp2Ref);
Compilation verify2<TAssemblySymbol>(string source2, MetadataReference reference0, MetadataReference reference1) where TAssemblySymbol : AssemblySymbol
{
var comp2 = AssertUsedAssemblyReferences(source2, new[] { reference0, reference1 }, reference0);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference0));
return comp2;
}
void verify3<TAssemblySymbol>(string source3, params MetadataReference[] references) where TAssemblySymbol : AssemblySymbol
{
Compilation comp3 = AssertUsedAssemblyReferences(source3, references: references);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp3).GetAssemblyOrModuleSymbol(references.Last()));
}
}
[Fact]
public void FieldReference_04()
{
var source1 =
@"
namespace N1
{
public enum E1
{
F1 = 0
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
verify(comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = N1.E1.F1 + 1;
}
}
");
verify(comp1Ref,
@"
using N1;
public class C2
{
public static void Main()
{
_ = E1.F1 + 1;
}
}
");
verify(comp1Ref,
@"
using static N1.E1;
public class C2
{
public static void Main()
{
_ = F1 + 1;
}
}
");
verify(comp1Ref,
@"
using alias = N1.E1;
public class C2
{
public static void Main()
{
_ = alias.F1 + 1;
}
}
");
void verify(MetadataReference reference, string source)
{
AssertUsedAssemblyReferences(source, reference);
}
}
[Fact]
public void FieldReference_05()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
public class C3
{
public int F3 = 0;
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = C1<C0>.E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main()
{
_ = E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = alias.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main()
{
_ = alias.E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = nameof(C1<C0>.E1.F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(E1.F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = nameof(F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = nameof(alias.F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(alias.E1.F1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = nameof(C1<C0>.C3.F3);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(C3.F3);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.C3;
public class C2
{
public static void Main()
{
_ = nameof(alias.F3);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(alias.C3.F3);
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void FieldReference_06()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
public class C3
{
public int F3;
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
class C2
{
/// <summary>
/// <see cref=""C1{C0}.E1.F1""/>
/// </summary>
static void Main()
{
}
}
",
hasTypeReferencesInUsing: false);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
class C2
{
/// <summary>
/// <see cref=""E1.F1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
class C2
{
/// <summary>
/// <see cref=""F1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
class C2
{
/// <summary>
/// <see cref=""alias.F1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
class C2
{
/// <summary>
/// <see cref=""alias.E1.F1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
class C2
{
/// <summary>
/// <see cref=""C1{C0}.C3.F3""/>
/// </summary>
static void Main()
{
}
}
",
hasTypeReferencesInUsing: false);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
class C2
{
/// <summary>
/// <see cref=""C3.F3""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.C3;
class C2
{
/// <summary>
/// <see cref=""alias.F3""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
class C2
{
/// <summary>
/// <see cref=""alias.C3.F3""/>
/// </summary>
static void Main()
{
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source, bool hasTypeReferencesInUsing = true)
{
var references = new[] { reference0, reference1 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, hasTypeReferencesInUsing ? references : new MetadataReference[] { }, references);
var expected = hasTypeReferencesInUsing ? references : new[] { reference1 };
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, expected);
Compilation comp4 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
AssertUsedAssemblyReferences(comp4, expected);
}
}
[Fact]
public void FieldReference_07()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var attribute =
@"
class TestAttribute : System.Attribute
{
public TestAttribute()
{ }
public TestAttribute(int value)
{ }
public int Value = 0;
}
";
verify(comp0Ref, comp1Ref,
@"
public class C2
{
[Test((int)C1<C0>.E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
[Test((int)E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
[Test((int)F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
[Test((int)alias.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
[Test((int)alias.E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
public class C2
{
[Test(Value = (int)C1<C0>.E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
[Test(Value = (int)E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
[Test(Value = (int)F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
[Test(Value = (int)alias.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
[Test(Value = (int)alias.E1.F1 + 1)]
public static void Main()
{
}
}
" + attribute);
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void FieldReference_08()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main(int p = (int)C1<C0>.E1.F1 + 1)
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main(int p = (int)E1.F1 + 1)
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>.E1;
public class C2
{
public static void Main(int p = (int)F1 + 1)
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
public static void Main(int p = (int)alias.F1 + 1)
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main(int p = (int)alias.E1.F1 + 1)
{
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void MethodReference_01()
{
var source1 =
@"
public class C1
{
public static void M1(){}
}
";
var comp1 = CreateCompilation(source1);
var source2 =
@"
public class C2
{
public static void Main()
{
C1.M1();
}
}
";
verify<PEAssemblySymbol>(source2, comp1.EmitToImageReference());
verify<SourceAssemblySymbol>(source2, comp1.ToMetadataReference());
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void MethodReference_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var source1 =
@"
public class C1
{
public static void M1<T>(){}
}
public class C2<T> {}
public class C3<T>
{
public class C4 {}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var reference0 = comp0.ToMetadataReference();
var reference1 = comp1.ToMetadataReference();
verify(reference0, reference1,
@"
public class C5
{
public static void Main()
{
C1.M1<C0>();
}
}
");
verify(reference0, reference1,
@"
public class C5
{
public static void Main()
{
C1.M1<C2<C0>>();
}
}
");
verify(reference1, reference0,
@"
public class C5
{
public static void Main()
{
C1.M1<C3<C0>.C4>();
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void MethodReference_03()
{
var source0 =
@"
public static class C0
{
public static void M1(this string x, int y) { }
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void M1(this string x, string y) { }
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
var x = ""a"";
x.M1(""b"");
}
}
";
AssertUsedAssemblyReferences(source2, references: new[] { comp0Ref, comp1Ref }, comp0Ref, comp1Ref);
}
[Fact]
public void MethodReference_04()
{
var source0 =
@"
public static class C0
{
public static void M1(this string x, string y) { }
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void M1(this string x, string y) { }
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
var x = ""a"";
x.M1(""b"");
}
}
";
AssertUsedAssemblyReferences(source2, references: new[] { comp0Ref, comp1Ref },
// (7,11): error CS0121: The call is ambiguous between the following methods or properties: 'C0.M1(string, string)' and 'C1.M1(string, string)'
// x.M1("b");
Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C0.M1(string, string)", "C1.M1(string, string)").WithLocation(7, 11)
);
}
[Fact]
public void MethodReference_05()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0, assemblyName: "MethodReference_05_0");
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void M1(this string x, C0 y) { }
}
public interface I1 {}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public static class C2
{
public static void M1(this string x, string y) { }
}
";
var comp2 = CreateCompilation(source2);
var comp2Ref = comp2.ToMetadataReference();
var source3 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
x.M1(""b"");
}
}
";
AssertUsedAssemblyReferences(source3, references: new[] { comp0Ref, comp1Ref, comp2Ref }, comp0Ref, comp1Ref, comp2Ref);
var expected1 = new DiagnosticDescription[] {
// (7,9): error CS0012: The type 'C0' is defined in an assembly that is not referenced. You must add a reference to assembly 'MethodReference_05_0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// x.M1("b");
Diagnostic(ErrorCode.ERR_NoTypeDef, "x.M1").WithArguments("C0", "MethodReference_05_0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 9)
};
AssertUsedAssemblyReferences(source3, references: new[] { comp1Ref, comp2Ref }, expected1);
var source4 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
x.M1(""b"");
}
void M1(I1 x) {}
}
";
AssertUsedAssemblyReferences(source4, references: new[] { comp0Ref, comp1Ref, comp2Ref }, comp0Ref, comp1Ref, comp2Ref);
AssertUsedAssemblyReferences(source4, references: new[] { comp1Ref, comp2Ref }, expected1);
var source5 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface C0
{
}
";
var comp5 = CreateCompilation(source5);
comp5.VerifyDiagnostics();
var comp5Ref = comp5.ToMetadataReference(embedInteropTypes: true);
var comp6 = CreateCompilation(source1, references: new[] { comp5Ref });
var comp6Ref = comp6.ToMetadataReference();
var comp6ImageRef = comp6.EmitToImageReference();
var comp7 = CreateCompilation(source5);
var comp7Ref = comp7.ToMetadataReference(embedInteropTypes: false);
var comp7ImageRef = comp7.EmitToImageReference(embedInteropTypes: false);
AssertUsedAssemblyReferences(source3, references: new[] { comp7Ref, comp6Ref, comp2Ref }, comp7Ref, comp6Ref, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp7ImageRef, comp6ImageRef, comp2Ref }, comp7ImageRef, comp6ImageRef, comp2Ref);
var expected2 = new DiagnosticDescription[] {
// (7,9): error CS1748: Cannot find the interop type that matches the embedded interop type 'C0'. Are you missing an assembly reference?
// x.M1("b");
Diagnostic(ErrorCode.ERR_NoCanonicalView, "x.M1").WithArguments("C0").WithLocation(7, 9)
};
AssertUsedAssemblyReferences(source3, references: new[] { comp6Ref, comp2Ref }, expected2);
AssertUsedAssemblyReferences(source3, references: new[] { comp6ImageRef, comp2Ref }, expected2);
AssertUsedAssemblyReferences(source4, references: new[] { comp7Ref, comp6Ref, comp2Ref }, comp7Ref, comp6Ref, comp2Ref);
AssertUsedAssemblyReferences(source4, references: new[] { comp7ImageRef, comp6ImageRef, comp2Ref }, comp7ImageRef, comp6ImageRef, comp2Ref);
AssertUsedAssemblyReferences(source4, references: new[] { comp6Ref, comp2Ref }, expected2);
AssertUsedAssemblyReferences(source4, references: new[] { comp6ImageRef, comp2Ref }, expected2);
var source8 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
_ = nameof(x.M1);
}
}
";
AssertUsedAssemblyReferences(source8, new[] { comp0Ref, comp1Ref, comp2Ref },
// (7,20): error CS8093: Extension method groups are not allowed as an argument to 'nameof'.
// _ = nameof(x.M1);
Diagnostic(ErrorCode.ERR_NameofExtensionMethod, "x.M1").WithLocation(7, 20)
);
}
[Fact]
public void MethodReference_06()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public void M1(C0 y) { }
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2 : C1
{
public void M1(string y) { }
}
";
var comp2 = CreateCompilation(source2, references: new[] { comp1Ref });
var comp2Ref = comp2.ToMetadataReference();
var comp2ImageRef = comp2.EmitToImageReference();
var source3 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
new C2().M1(x);
}
}
";
AssertUsedAssemblyReferences(source3, references: new[] { comp0Ref, comp1Ref, comp2Ref }, comp0Ref, comp1Ref, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp1Ref, comp2Ref }, comp1Ref, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp1ImageRef, comp2Ref }, comp1ImageRef, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp1Ref, comp2ImageRef }, comp1Ref, comp2ImageRef);
AssertUsedAssemblyReferences(source3, references: new[] { comp1ImageRef, comp2ImageRef }, comp1ImageRef, comp2ImageRef);
}
[Fact]
public void MethodReference_07()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0, assemblyName: "MethodReference_07_0");
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public void M1(string y) { }
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2 : C1
{
public void M1(C0 y) { }
}
";
var comp2 = CreateCompilation(source2, references: new[] { comp0Ref, comp1Ref });
var comp2Ref = comp2.ToMetadataReference();
var source3 =
@"
public class C3
{
public static void Main()
{
var x = ""a"";
new C2().M1(x);
}
}
";
AssertUsedAssemblyReferences(source3, references: new[] { comp0Ref, comp1Ref, comp2Ref }, comp0Ref, comp1Ref, comp2Ref);
AssertUsedAssemblyReferences(source3, references: new[] { comp1Ref, comp2Ref },
// (7,9): error CS0012: The type 'C0' is defined in an assembly that is not referenced. You must add a reference to assembly 'MethodReference_07_0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// new C2().M1(x);
Diagnostic(ErrorCode.ERR_NoTypeDef, "new C2().M1").WithArguments("C0", "MethodReference_07_0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 9)
);
}
[Fact]
public void MethodReference_08()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public C0 M1() => null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source3 =
@"
public class C3
{
public static void Main()
{
_ = nameof(C1.M1);
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
AssertUsedAssemblyReferences(source3, comp1Ref);
AssertUsedAssemblyReferences(source3, comp1ImageRef);
var source5 =
@"
using static C1;
public class C3
{
public static void Main()
{
_ = nameof(M1);
}
}
";
AssertUsedAssemblyReferences(source5, new[] { comp0Ref, comp1Ref },
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,20): error CS0103: The name 'M1' does not exist in the current context
// _ = nameof(M1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(2005, 20)
);
var source6 =
@"
public class C3
{
public static void Main()
{
var x = new C1();
_ = nameof(x.M1);
}
}
";
AssertUsedAssemblyReferences(source6, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source6, comp0Ref, comp1ImageRef);
AssertUsedAssemblyReferences(source6, comp1Ref);
AssertUsedAssemblyReferences(source6, comp1ImageRef);
}
[Fact]
public void MethodReference_09()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public static C0 M1() => null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source3 =
@"
public class C3
{
public static void Main()
{
_ = nameof(C1.M1);
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
AssertUsedAssemblyReferences(source3, comp1Ref);
AssertUsedAssemblyReferences(source3, comp1ImageRef);
var source4 =
@"
using static C1;
public class C3
{
public static void Main()
{
_ = nameof(M1);
}
}
";
AssertUsedAssemblyReferences(source4, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source4, comp0Ref, comp1ImageRef);
AssertUsedAssemblyReferences(source4, comp1Ref);
AssertUsedAssemblyReferences(source4, comp1ImageRef);
var source5 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface C0
{
}
";
var comp5 = CreateCompilation(source5);
comp5.VerifyDiagnostics();
var comp5Ref = comp5.ToMetadataReference(embedInteropTypes: true);
var comp6 = CreateCompilation(source1, references: new[] { comp5Ref });
var comp6Ref = comp6.ToMetadataReference();
var comp6ImageRef = comp6.EmitToImageReference();
var comp7 = CreateCompilation(source5);
var comp7Ref = comp7.ToMetadataReference(embedInteropTypes: false);
var comp7ImageRef = comp7.EmitToImageReference(embedInteropTypes: false);
AssertUsedAssemblyReferences(source3, new[] { comp7Ref, comp6Ref }, comp6Ref);
AssertUsedAssemblyReferences(source3, new[] { comp7ImageRef, comp6ImageRef }, comp6ImageRef);
AssertUsedAssemblyReferences(source4, new[] { comp7Ref, comp6Ref }, comp6Ref);
AssertUsedAssemblyReferences(source4, new[] { comp7ImageRef, comp6ImageRef }, comp6ImageRef);
}
[Fact]
public void MethodReference_10()
{
var source1 =
@"
public class C1
{
[System.Diagnostics.Conditional(""Always"")]
public static void M1(){}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
C1.M1();
}
}
";
verify<PEAssemblySymbol>(source2, comp1ImageRef);
verify<SourceAssemblySymbol>(source2, comp1Ref);
var source3 =
@"
using static C1;
public class C2
{
public static void Main()
{
M1();
}
}
";
verify<PEAssemblySymbol>(source3, comp1ImageRef);
verify<SourceAssemblySymbol>(source3, comp1Ref);
void verify<TAssemblySymbol>(string source2, MetadataReference reference) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, reference);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference));
}
}
[Fact]
public void MethodReference_11()
{
var source0 =
@"
public class C0 : System.Collections.IEnumerable
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new System.NotImplementedException();
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void Add(this C0 x, int y) => throw null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = new C0() { 1 };
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
}
[Fact]
public void MethodReference_12()
{
var source0 =
@"
public class C0 : System.Collections.IEnumerable
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new System.NotImplementedException();
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
[System.Diagnostics.Conditional(""Always"")]
public static void Add(this C0 x, int y) => throw null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = new C0() { 1 };
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
}
[Fact]
public void FieldDeclaration_01()
{
var source1 =
@"
namespace N1
{
public class C1
{
public class C11
{
}
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
verify(comp1Ref,
@"
public class C2
{
public static N1.C1.C11 F1 = null;
}
");
verify(comp1Ref,
@"
using N2 = N1;
public class C2
{
public static N2.C1.C11 F1 = null;
}
");
verify(comp1Ref,
@"
using N1;
public class C2
{
public static C1.C11 F1 = null;
}
");
verify(comp1Ref,
@"
using static N1.C1;
public class C2
{
public static C11 F1 = null;
}
");
verify(comp1Ref,
@"
using C111 = N1.C1.C11;
public class C2
{
public static C111 F1 = null;
}
");
void verify(MetadataReference reference, string source2)
{
AssertUsedAssemblyReferences(source2, reference);
}
}
[Fact]
public void UnusedUsings_01()
{
var source1 =
@"
namespace N1
{
public static class C1
{
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
verify1(comp1Ref,
@"
using N1;
public class C2
{
}
",
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1;").WithLocation(1001, 1)
);
verify1(comp1Ref,
@"
using static N1.C1;
public class C2
{
}
",
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static N1.C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N1.C1;").WithLocation(1001, 1)
);
verify1(comp1Ref,
@"
using alias = N1.C1;
public class C2
{
}
",
// (1001,1): hidden CS8019: Unnecessary using directive.
// using alias = N1.C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using alias = N1.C1;").WithLocation(1001, 1)
);
verify1(comp1Ref,
@"
using alias = N1;
public class C2
{
}
",
// (1001,1): hidden CS8019: Unnecessary using directive.
// using alias = N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using alias = N1;").WithLocation(1001, 1)
);
verify1(comp1Ref.WithAliases(new[] { "N1C1" }),
@"
extern alias N1C1;
public class C2
{
}
",
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1)
);
verify1(comp1Ref,
@"namespace N2 {
using N1;
public class C2
{
}
}",
// (2,1): hidden CS8019: Unnecessary using directive.
// using N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1;").WithLocation(2, 1)
);
verify1(comp1Ref,
@"namespace N2 {
using static N1.C1;
public class C2
{
}
}",
// (2,1): hidden CS8019: Unnecessary using directive.
// using static N1.C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N1.C1;").WithLocation(2, 1)
);
verify1(comp1Ref,
@"namespace N2 {
using alias = N1.C1;
public class C2
{
}
}",
// (2,1): hidden CS8019: Unnecessary using directive.
// using alias = N1.C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using alias = N1.C1;").WithLocation(2, 1)
);
verify1(comp1Ref,
@"namespace N2 {
using alias = N1;
public class C2
{
}
}",
// (2,1): hidden CS8019: Unnecessary using directive.
// using alias = N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using alias = N1;").WithLocation(2, 1)
);
verify1(comp1Ref.WithAliases(new[] { "N1C1" }),
@"namespace N2 {
extern alias N1C1;
public class C2
{
}
}",
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1)
);
verify2(comp1Ref,
@"
public class C2
{
}
",
"N1");
verify2(comp1Ref,
@"
public class C2
{
}
",
"N1.C1");
static void verify1(MetadataReference reference, string source, params DiagnosticDescription[] expected)
{
Compilation comp = CreateCompilation(source, references: new[] { reference });
foreach (var c in CloneCompilationsWithUsings(comp, expected, null))
{
verify(c.comp, c.before);
}
static void verify(Compilation comp, params DiagnosticDescription[] expected)
{
comp.VerifyDiagnostics(expected);
Assert.True(comp.References.Count() > 1);
var used = comp.GetUsedAssemblyReferences();
Assert.Equal(1, used.Length);
Assert.Same(comp.ObjectType.ContainingAssembly, comp.GetAssemblyOrModuleSymbol(used[0]));
}
}
void verify2(MetadataReference reference, string source, string @using)
{
AssertUsedAssemblyReferences(CreateCompilation(Parse(source, options: TestOptions.Script), references: new[] { reference }, options: TestOptions.DebugDll.WithUsings(@using)),
reference);
}
}
[Fact]
public void MethodDeclaration_01()
{
var source1 =
@"
namespace N1
{
public class C1
{
public class C11
{
}
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference();
verify(comp1Ref,
@"
public class C2
{
public static N1.C1.C11 M1() => null;
}
");
verify(comp1Ref,
@"
using N2 = N1;
public class C2
{
public static N2.C1.C11 M1() => null;
}
");
verify(comp1Ref,
@"
using N1;
public class C2
{
public static C1.C11 M1() => null;
}
");
verify(comp1Ref,
@"
using static N1.C1;
public class C2
{
public static C11 M1() => null;
}
");
verify(comp1Ref,
@"
using C111 = N1.C1.C11;
public class C2
{
public static C111 M1() => null;
}
");
void verify(MetadataReference reference, string source2)
{
AssertUsedAssemblyReferences(source2, reference);
}
}
[Fact]
public void NoPia_01()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static ITest33 F0 = null;
public static int F1 = 0;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
_ = C1.F1;
}
}
";
verify<PEAssemblySymbol>(source2, comp0ImageRef, comp1ImageRef);
verify<PEAssemblySymbol>(source2, comp0Ref, comp1ImageRef);
verify<RetargetingAssemblySymbol>(source2, comp0Ref, comp1Ref);
verify<RetargetingAssemblySymbol>(source2, comp0ImageRef, comp1Ref);
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify<PEAssemblySymbol>(source2, comp3ImageRef, comp1ImageRef);
verify<PEAssemblySymbol>(source2, comp3Ref, comp1ImageRef);
verify<RetargetingAssemblySymbol>(source2, comp3Ref, comp1Ref);
verify<RetargetingAssemblySymbol>(source2, comp3ImageRef, comp1Ref);
void verify<TAssemblySymbol>(string source2, MetadataReference reference0, MetadataReference reference1) where TAssemblySymbol : AssemblySymbol
{
Compilation comp2 = AssertUsedAssemblyReferences(source2, new[] { reference0, reference1 }, reference1);
Assert.IsType<TAssemblySymbol>(((CSharpCompilation)comp2).GetAssemblyOrModuleSymbol(reference1));
}
}
[Fact]
public void NoPia_02()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static ITest33 F0 = null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
_ = C1.F0;
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.F0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.F0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_03()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static ITest33 M0() => null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
C1.M0();
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.M0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.M0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_04()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static object M0(ITest33 x) => null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
C1.M0(null);
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.M0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.M0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_05()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public delegate void DTest33();
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
#pragma warning disable CS0414
public class C1
{
public static event DTest33 E0 = null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
C1.E0 += Main;
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.E0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.E0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_06()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public static ITest33 P0 => null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
_ = C1.P0;
}
}
");
verify(
@"
public class C2
{
public static void Main()
{
_ = nameof(C1.P0);
}
}
");
verify(
@"
public class C2
{
/// <summary>
/// <see cref=""C1.P0""/>
/// </summary>
public static void Main()
{
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_07()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1
{
public object this[ITest33 x] => null;
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C2
{
public static void Main()
{
_ = new C1()[null];
}
}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_08()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1 : ITest33, I1
{
}
public interface I1
{
}
public class C2 : I2<ITest33>, I1
{
}
public class C3 : C2
{
}
public interface I2<out T>
{
}
public interface I3 : ITest33, I1
{
}
public interface I4 : I3
{
}
public struct S1 : ITest33, I1
{
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
verify(
@"
public class C
{
public static void Main()
{
_ = (I2<object>)new C2();
}
}
");
verify(
@"
public class C
{
public static void Main()
{
_ = (I1)new C2();
}
}
");
verify(
@"
public class C
{
public static void Main()
{
_ = (I1)new C1();
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I2<object> x = new C2();
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I1 x = new C2();
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I1 x = new C1();
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
_ = (I2<object>)new C3();
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I2<object> x = new C3();
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I3 x = null;
I1 y = x;
_ = y;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I4 x = null;
I1 y = x;
_ = y;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I<C1[]> x = null;
I<I1[]> y = x;
_ = y;
}
}
interface I<out T> {}
");
verify(
@"
public class C
{
public static void Main()
{
I<C1> x = null;
I<I1> y = x;
_ = y;
}
}
interface I<out T> {}
");
verify(
@"
public class C
{
public static void Main()
{
I<I1>[] x = new I<C1>[10];
_ = x;
}
}
interface I<out T> {}
");
verify(
@"
public class C
{
public static void Main()
{
I1[] x = new C1[10];
_ = x;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
S1? x = null;
I1 y = x;
_ = y;
}
}
");
verify(
@"
public class C
{
public static void Main<T>() where T : C1
{
T x = null;
I1 y = x;
_ = y;
}
}
");
verify(
@"
public class C
{
public static void Main()
{
I1 x = new A();
_ = x;
}
}
class A : C1 {}
");
verify(
@"
public class C
{
public static void Main()
{
IA x = null;
I1 y = x;
_ = y;
}
}
interface IA : I3 {}
");
void verify(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
}
[Fact]
public void NoPia_09()
{
var source0 =
@"
using System;
using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface ITest33
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference(embedInteropTypes: true);
var comp0ImageRef = comp0.EmitToImageReference(embedInteropTypes: true);
var source1 =
@"
public class C1 : ITest33, I1
{
}
public interface I1
{
}
public interface I3 : ITest33, I1
{
}
public interface I4 : I3
{
}
public class C2
{
public static void M1<T>() where T : ITest33 {}
public static void M2<T>() where T : I3 {}
public static void M3<T>() where T : C1 {}
public static void M4<T>() where T : I1 {}
}
public class C3<T> where T : I1
{
}
public static class C4<T> where T : I1
{
public static void M5() {}
}
";
var comp1 = AssertUsedAssemblyReferences(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var comp3 = CreateCompilation(source0);
var comp3Ref = comp3.ToMetadataReference(embedInteropTypes: false);
var comp3ImageRef = comp3.EmitToImageReference(embedInteropTypes: false);
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M4<I3>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M4<C1>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M3<C1>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M2<I4>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M2<I3>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M1<I4>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M1<I3>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C
{
static void Main()
{
C2.M1<C1>();
}
}
");
compileWithUsedAssemblyReferences(
@"
public class C : I3
{
}
");
compileWithUsedAssemblyReferences(
@"
public class C : C1
{
}
");
compileWithUsedAssemblyReferences(
@"
interface IA : I3 {}
");
compileWithUsedAssemblyReferences(
@"
using static C4<I3>;
public class C
{
static void Main()
{
M5();
}
}
");
verifyNotUsed(
@"
using static C4<I3>;
public class C
{
static void Main()
{
}
}
");
verifyNotUsed(
@"
using alias = C3<I3>;
public class C
{
static void Main()
{
}
}
");
compileWithUsedAssemblyReferences(
@"
using alias = C3<I3>;
public class C
{
static void Main()
{
_ = new alias();
}
}
");
void compileWithUsedAssemblyReferences(string source2)
{
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp0ImageRef, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1ImageRef);
CompileWithUsedAssemblyReferences(source2, comp3Ref, comp1Ref);
CompileWithUsedAssemblyReferences(source2, comp3ImageRef, comp1Ref);
}
void verifyNotUsed(string source2)
{
verifyNotUsed(source2, comp0ImageRef, comp1ImageRef);
verifyNotUsed(source2, comp0Ref, comp1ImageRef);
verifyNotUsed(source2, comp0Ref, comp1Ref);
verifyNotUsed(source2, comp0ImageRef, comp1Ref);
verifyNotUsed(source2, comp3ImageRef, comp1ImageRef);
verifyNotUsed(source2, comp3Ref, comp1ImageRef);
verifyNotUsed(source2, comp3Ref, comp1Ref);
verifyNotUsed(source2, comp3ImageRef, comp1Ref);
void verifyNotUsed(string source2, MetadataReference ref0, MetadataReference ref1)
{
var comp = CreateCompilation(source2, references: new[] { ref0, ref1 });
foreach (var c in CloneCompilationsWithUsings(comp, null, null))
{
var used = c.comp.GetUsedAssemblyReferences();
Assert.DoesNotContain(ref0, used);
Assert.DoesNotContain(ref1, used);
}
}
}
}
[Fact]
public void ArraysAndPointers_01()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
F1 = 0
}
}
public struct S<T>
{ }
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = C1<S<C0>*[]>.E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<S<C0>*[]>;
public class C2
{
public static void Main()
{
_ = E1.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<S<C0>*[]>.E1;
public class C2
{
public static void Main()
{
_ = F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<S<C0>*[]>.E1;
public class C2
{
public static void Main()
{
_ = alias.F1 + 1;
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<S<C0>*[]>;
public class C2
{
public static void Main()
{
_ = alias.E1.F1 + 1;
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void TypeReference_01()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
public class C2
{
public static void Main()
{
_ = nameof(C1<C0>.E1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(E1);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
public class C2
{
public static void Main()
{
_ = nameof(alias);
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
public class C2
{
public static void Main()
{
_ = nameof(alias.E1);
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source)
{
AssertUsedAssemblyReferences(source, reference0, reference1);
}
}
[Fact]
public void TypeReference_02()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
class C2
{
/// <summary>
/// <see cref=""C1{C0}.E1""/>
/// </summary>
static void Main()
{
}
}
",
hasTypeReferencesInUsing: false);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
class C2
{
/// <summary>
/// <see cref=""E1""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
class C2
{
/// <summary>
/// <see cref=""alias""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
class C2
{
/// <summary>
/// <see cref=""alias.E1""/>
/// </summary>
static void Main()
{
}
}
");
var source2 =
@"
class C2
{
static void Main1()
{
}
}
";
var references = new[] { comp0Ref, comp1Ref };
AssertUsedAssemblyReferences(CreateCompilation(source2, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.None),
options: TestOptions.DebugDll.WithUsings("C0")),
comp0Ref);
AssertUsedAssemblyReferences(CreateCompilation(source2, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.Parse),
options: TestOptions.DebugDll.WithUsings("C0")),
comp0Ref);
void verify(MetadataReference reference0, MetadataReference reference1, string source, bool hasTypeReferencesInUsing = true)
{
var references = new[] { reference0, reference1 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, hasTypeReferencesInUsing ? references : new MetadataReference[] { }, references);
var expected = hasTypeReferencesInUsing ? references : new[] { reference1 };
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, expected);
Compilation comp4 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
AssertUsedAssemblyReferences(comp4, expected);
}
}
[Fact]
public void TypeReference_03()
{
var source0 =
@"
public class C0 {}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1<T>
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
verify(comp0Ref, comp1Ref,
@"
class C2
{
/// <summary>
/// <see cref=""M(C1{C0}.E1)""/>
/// </summary>
static void Main()
{
}
void M(int x) {}
}
",
hasTypeReferencesInUsing: false);
verify(comp0Ref, comp1Ref,
@"
using static C1<C0>;
class C2
{
/// <summary>
/// <see cref=""M(E1)""/>
/// </summary>
static void Main()
{
}
void M(int x) {}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>.E1;
class C2
{
/// <summary>
/// <see cref=""M(alias)""/>
/// </summary>
static void Main()
{
}
void M(int x) {}
}
");
verify(comp0Ref, comp1Ref,
@"
using alias = C1<C0>;
class C2
{
/// <summary>
/// <see cref=""M(alias.E1)""/>
/// </summary>
static void Main()
{
}
void M(int x) {}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, string source, bool hasTypeReferencesInUsing = true)
{
var references = new[] { reference0, reference1 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, hasTypeReferencesInUsing ? references : new MetadataReference[] { }, references);
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, references);
}
}
[Fact]
public void TypeReference_04()
{
var source0 =
@"
public class C0
{
public class C1
{
public static void M1() {}
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C2 : C0
{
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
CompileWithUsedAssemblyReferences(@"
public class C3
{
public static void Main()
{
_ = new C2.C1();
}
}
", comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(@"
public class C3 : C2.C1
{
public static void Main()
{
}
}
", comp0Ref, comp1Ref);
var used = CompileWithUsedAssemblyReferences(@"
public class C3 : C0
{
public static void Main()
{
}
}
", comp0Ref, comp1Ref);
Assert.DoesNotContain(comp1Ref, used);
var comp = CreateCompilation(@"
using static C2.C1;
public class C3
{
public static void Main()
{
}
}
", references: new[] { comp0Ref, comp1Ref });
foreach (var c in CloneCompilationsWithUsings(comp, null, null))
{
used = c.comp.GetUsedAssemblyReferences();
Assert.DoesNotContain(comp0Ref, used);
Assert.DoesNotContain(comp1Ref, used);
}
comp = CreateCompilation(@"
using alias = C2.C1;
public class C3
{
public static void Main()
{
}
}
", references: new[] { comp0Ref, comp1Ref });
foreach (var c in CloneCompilationsWithUsings(comp, null, null))
{
used = c.comp.GetUsedAssemblyReferences();
Assert.DoesNotContain(comp0Ref, used);
Assert.DoesNotContain(comp1Ref, used);
}
CompileWithUsedAssemblyReferences(@"
using static C2.C1;
public class C3
{
public static void Main()
{
M1();
}
}
", comp0Ref, comp1Ref);
CompileWithUsedAssemblyReferences(@"
using alias = C2.C1;
public class C3
{
public static void Main()
{
_ = new alias();
}
}
", comp0Ref, comp1Ref);
}
[Fact]
public void NamespaceReference_01()
{
var source0 =
@"
namespace N1.N2
{
public enum E0
{
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace N1.N2
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
namespace N1
{
public enum E2
{
}
}
";
var comp2 = CreateCompilation(source2);
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
verify(comp0Ref, comp1Ref, comp2Ref,
@"
public class C2
{
public static void Main()
{
_ = nameof(N1.N2);
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2;
public class C2
{
public static void Main()
{
_ = nameof(alias);
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1;
public class C2
{
public static void Main()
{
_ = nameof(alias.N2);
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, MetadataReference reference2, string source)
{
AssertUsedAssemblyReferences(source, new[] { reference0, reference1, reference2 }, reference0, reference1);
}
}
[Fact]
public void NamespaceReference_02()
{
var source0 =
@"
namespace N1.N2
{
public enum E0
{
F0
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace N1.N2
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
namespace N1
{
public enum E2
{
}
}
";
var comp2 = CreateCompilation(source2);
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
verify(comp0Ref, comp1Ref, comp2Ref,
@"
public class C2
{
public static void Main()
{
_ = N1.N2.E0.F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2.E0;
public class C2
{
public static void Main()
{
_ = alias.F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using static N1.N2.E0;
public class C2
{
public static void Main()
{
_ = F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2;
public class C2
{
public static void Main()
{
_ = alias.E0.F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using N1.N2;
public class C2
{
public static void Main()
{
_ = E0.F0;
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1;
public class C2
{
public static void Main()
{
_ = alias.N2.E0.F0;
}
}
");
void verify(MetadataReference reference0, MetadataReference reference1, MetadataReference reference2, string source)
{
AssertUsedAssemblyReferences(source, new[] { reference0, reference1, reference2 }, reference0);
}
}
[Fact]
public void NamespaceReference_03()
{
var source0 =
@"
namespace N1.N2
{
public enum E0
{
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace N1.N2
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
namespace N1
{
public enum E2
{
}
}
";
var comp2 = CreateCompilation(source2);
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
verify(comp0Ref, comp1Ref, comp2Ref,
@"
class C2
{
/// <summary>
/// <see cref=""N1.N2""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2;
class C2
{
/// <summary>
/// <see cref=""alias""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 2
);
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1;
class C2
{
/// <summary>
/// <see cref=""alias.N2""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 1
);
var source3 =
@"
using N1.N2;
class C2
{
static void Main()
{
}
}
";
var references = new[] { comp0Ref, comp1Ref, comp2Ref };
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1.N2;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1.N2;").WithLocation(1001, 1)
},
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1.N2;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1.N2;").WithLocation(1001, 1),
// (1001,7): error CS0246: The type or namespace name 'N1' could not be found (are you missing a using directive or an assembly reference?)
// using N1.N2;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "N1").WithArguments("N1").WithLocation(1001, 7)
}, references);
var source4 =
@"
using N1;
class C2
{
static void Main()
{
}
}
";
AssertUsedAssemblyReferences(CreateCompilation(source4, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
references);
AssertUsedAssemblyReferences(CreateCompilation(source4, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1;").WithLocation(1001, 1)
},
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using N1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using N1;").WithLocation(1001, 1),
// (1001,7): error CS0246: The type or namespace name 'N1' could not be found (are you missing a
// using N1;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "N1").WithArguments("N1").WithLocation(1001, 7)
}, references);
var source5 =
@"
class C2
{
static void Main1()
{
}
}
";
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.None),
options: TestOptions.DebugDll.WithUsings("N1.N2")),
comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.Parse),
options: TestOptions.DebugDll.WithUsings("N1.N2")),
comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.None),
options: TestOptions.DebugDll.WithUsings("N1")),
references);
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.Parse),
options: TestOptions.DebugDll.WithUsings("N1")),
references);
void verify(MetadataReference reference0, MetadataReference reference1, MetadataReference reference2, string source, int namespaceOrdinalReferencedInUsings = 0)
{
var references = new[] { reference0, reference1, reference2 };
var expected = new[] { reference0, reference1 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, namespaceOrdinalReferencedInUsings switch { 1 => references, 2 => expected, _ => new MetadataReference[] { } }, references);
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, expected);
Compilation comp4 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
AssertUsedAssemblyReferences(comp4, expected);
}
}
[Fact]
public void NamespaceReference_04()
{
var source0 =
@"
namespace N1.N2
{
public enum E0
{
F0
}
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace N1.N2
{
public enum E1
{
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
namespace N1
{
public enum E2
{
}
}
";
var comp2 = CreateCompilation(source2);
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
verify(comp0Ref, comp1Ref, comp2Ref,
@"
class C2
{
/// <summary>
/// <see cref=""N1.N2.E0""/>
/// </summary>
static void Main()
{
}
}
");
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2;
class C2
{
/// <summary>
/// <see cref=""alias.E0""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 2
);
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1.N2.E0;
class C2
{
/// <summary>
/// <see cref=""alias""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 3
);
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using static N1.N2.E0;
class C2
{
/// <summary>
/// <see cref=""F0""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 3
);
verify(comp0Ref, comp1Ref, comp2Ref,
@"
using alias = N1;
class C2
{
/// <summary>
/// <see cref=""alias.N2.E0""/>
/// </summary>
static void Main()
{
}
}
",
namespaceOrdinalReferencedInUsings: 1
);
var source3 =
@"
using static N1.N2.E0;
class C2
{
static void Main()
{
}
}
";
var references = new[] { comp0Ref, comp1Ref, comp2Ref };
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
new[] { comp0Ref }, references);
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static N1.N2.E0;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N1.N2.E0;").WithLocation(1001, 1)
},
new[] {
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static N1.N2.E0;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N1.N2.E0;").WithLocation(1001, 1),
// (1001,14): error CS0246: The type or namespace name 'N1' could not be found (are you missing a using directive or an assembly reference?)
// using static N1.N2.E0;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "N1").WithArguments("N1").WithLocation(1001, 14)
}, references);
var source5 =
@"
class C2
{
static void Main1()
{
}
}
";
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.None),
options: TestOptions.DebugDll.WithUsings("N1.N2.E0")),
new[] { comp0Ref }, references);
AssertUsedAssemblyReferences(CreateCompilation(source5, references: references,
parseOptions: TestOptions.Script.WithDocumentationMode(DocumentationMode.Parse),
options: TestOptions.DebugDll.WithUsings("N1.N2.E0")),
new[] { comp0Ref }, references);
void verify(MetadataReference reference0, MetadataReference reference1, MetadataReference reference2, string source, int namespaceOrdinalReferencedInUsings = 0)
{
var references = new[] { reference0, reference1, reference2 };
Compilation comp2 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None));
AssertUsedAssemblyReferences(comp2, namespaceOrdinalReferencedInUsings switch { 1 => references, 2 => new[] { reference0, reference1 }, 3 => new[] { reference0 }, _ => new MetadataReference[] { } }, references);
Compilation comp3 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse));
AssertUsedAssemblyReferences(comp3, new[] { reference0 }, references);
Compilation comp4 = CreateCompilation(source, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
AssertUsedAssemblyReferences(comp4, new[] { reference0 }, references);
}
}
[Fact]
public void NamespaceReference_05()
{
var source1 =
@"
using global;
class C2
{
static void Main()
{
}
}
";
CreateCompilation(source1, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)).VerifyDiagnostics(
// (2,7): error CS0246: The type or namespace name 'global' could not be found (are you missing a using directive or an assembly reference?)
// using global;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "global").WithArguments("global").WithLocation(2, 7)
);
var source2 =
@"
using alias = global;
class C2
{
static void Main()
{
}
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)).VerifyDiagnostics(
// (2,15): error CS0246: The type or namespace name 'global' could not be found (are you missing a using directive or an assembly reference?)
// using alias = global;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "global").WithArguments("global").WithLocation(2, 15)
);
}
[Fact]
public void NamespaceReference_06()
{
var source1 =
@"
using global::;
class C2
{
static void Main()
{
}
}
";
CreateCompilation(source1, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)).VerifyDiagnostics(
// (2,15): error CS1001: Identifier expected
// using global::;
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(2, 15)
);
var source2 =
@"
using alias = global::;
class C2
{
static void Main()
{
}
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)).VerifyDiagnostics(
// (2,23): error CS1001: Identifier expected
// using alias = global::;
Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(2, 23)
);
}
[Fact]
public void EventReference_01()
{
var source0 =
@"
public delegate void D0();
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public static event D0 E1;
void Use()
{
E1();
}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
C1.E1 += null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main()
{
C1.E1 -= null;
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
var source4 =
@"
using static C1;
public class C2
{
public static void Main()
{
E1 += null;
}
}
";
AssertUsedAssemblyReferences(source4, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source4, comp0Ref, comp1ImageRef);
var source5 =
@"
using static C1;
public class C3
{
public static void Main()
{
E1 -= null;
}
}
";
AssertUsedAssemblyReferences(source5, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source5, comp0Ref, comp1ImageRef);
}
[Fact]
public void EventReference_02()
{
var source0 =
@"
public delegate void D0();
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public event D0 E1;
void Use()
{
E1();
}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main(C1 x)
{
x.E1 += null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main(C1 x)
{
x.E1 -= null;
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
}
[Fact]
public void PropertyReference_01()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public static C0 P1 {get; set;}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
C1.P1 = null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main()
{
_ = C1.P1;
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
var source4 =
@"
using static C1;
public class C2
{
public static void Main()
{
P1 = null;
}
}
";
AssertUsedAssemblyReferences(source4, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source4, comp0Ref, comp1ImageRef);
var source5 =
@"
using static C1;
public class C3
{
public static void Main()
{
_ = P1;
}
}
";
AssertUsedAssemblyReferences(source5, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source5, comp0Ref, comp1ImageRef);
}
[Fact]
public void PropertyReference_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public C0 P1 {get; set;}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main(C1 x)
{
x.P1 = null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main(C1 x)
{
_ = x.P1;
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
}
[Fact]
public void IndexerReference_01()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0ImageRef = comp0.EmitToImageReference();
var source1 =
@"
Public Class C1
Public Shared Property P1(x As Integer) As C0
Get
Return Nothing
End Get
Set
End Set
End Property
Public Shared Property P2(x As Integer) As C0
Get
Return Nothing
End Get
Set
End Set
End Property
Public Shared Property P2(x As String) As C0
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
";
var comp1 = CreateVisualBasicCompilation(source1, referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { comp0ImageRef }));
comp1.VerifyDiagnostics();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main()
{
C1.P1[0] = null;
}
}
";
var references = new[] { comp0ImageRef, comp1ImageRef };
AssertUsedAssemblyReferences(source2, references,
// (6,12): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// C1.P1[0] = null;
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(6, 12)
);
var source3 =
@"
public class C3
{
public static void Main()
{
_ = C1.P1[0];
}
}
";
AssertUsedAssemblyReferences(source3, references,
// (6,16): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// _ = C1.P1[0];
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(6, 16)
);
var source4 =
@"
using static C1;
public class C2
{
public static void Main()
{
P1[0] = null;
}
}
";
AssertUsedAssemblyReferences(source4, references,
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,9): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// P1[0] = null;
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(2005, 9)
);
var source5 =
@"
using static C1;
public class C3
{
public static void Main()
{
_ = P1[0];
}
}
";
AssertUsedAssemblyReferences(source5, references,
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,13): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// _ = P1[0];
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(2005, 13)
);
var source6 =
@"
public class C3
{
public static void Main()
{
_ = nameof(C1.P1);
}
}
";
AssertUsedAssemblyReferences(source6, references,
// (6,23): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// _ = nameof(C1.P1);
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(6, 23)
);
var source7 =
@"
using static C1;
public class C2
{
public static void Main()
{
_ = nameof(P1);
}
}
";
AssertUsedAssemblyReferences(source7, references,
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,20): error CS1545: Property, indexer, or event 'C1.P1[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P1(int)' or 'C1.set_P1(int, C0)'
// _ = nameof(P1);
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P1").WithArguments("C1.P1[int]", "C1.get_P1(int)", "C1.set_P1(int, C0)").WithLocation(2005, 20)
);
var source8 =
@"
public class C3
{
public static void Main()
{
_ = nameof(C1.P2);
}
}
";
AssertUsedAssemblyReferences(source8, references,
// (6,23): error CS1545: Property, indexer, or event 'C1.P2[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P2(int)' or 'C1.set_P2(int, C0)'
// _ = nameof(C1.P2);
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P2").WithArguments("C1.P2[int]", "C1.get_P2(int)", "C1.set_P2(int, C0)").WithLocation(6, 23)
);
var source9 =
@"
using static C1;
public class C2
{
public static void Main()
{
_ = nameof(P2);
}
}
";
AssertUsedAssemblyReferences(source9, references,
// (1001,1): hidden CS8019: Unnecessary using directive.
// using static C1;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static C1;").WithLocation(1001, 1),
// (2005,20): error CS1545: Property, indexer, or event 'C1.P2[int]' is not supported by the language; try directly calling accessor methods 'C1.get_P2(int)' or 'C1.set_P2(int, C0)'
// _ = nameof(P2);
Diagnostic(ErrorCode.ERR_BindToBogusProp2, "P2").WithArguments("C1.P2[int]", "C1.get_P2(int)", "C1.set_P2(int, C0)").WithLocation(2005, 20)
);
}
[Fact]
public void IndexerReference_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public class C1
{
public C0 this[int x] {get => default; set {}}
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var comp1ImageRef = comp1.EmitToImageReference();
var source2 =
@"
public class C2
{
public static void Main(C1 x)
{
x[0] = null;
}
}
";
AssertUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source2, comp0Ref, comp1ImageRef);
var source3 =
@"
public class C3
{
public static void Main(C1 x)
{
_ = x[0];
}
}
";
AssertUsedAssemblyReferences(source3, comp0Ref, comp1Ref);
AssertUsedAssemblyReferences(source3, comp0Ref, comp1ImageRef);
}
[Fact]
public void WellKnownTypeReference_01()
{
var source0 =
@"
namespace System
{
public class Object {}
public class ValueType {}
public struct Void {}
}
";
var comp0 = CreateEmptyCompilation(source0);
comp0.VerifyDiagnostics();
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
namespace System
{
public class Type
{
public static Type GetTypeFromHandle(RuntimeTypeHandle handle) => default;
}
public struct RuntimeTypeHandle {}
}
";
var comp1 = CreateEmptyCompilation(source1, references: new[] { comp0Ref });
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class Type
{
}
";
var comp2 = CreateEmptyCompilation(source2, references: new[] { comp0Ref });
comp2.VerifyDiagnostics();
var comp2Ref = comp2.ToMetadataReference();
var source3 =
@"
public class C2
{
public static void Main()
{
_ = typeof(C2);
}
}
";
var references = new[] { comp0Ref, comp1Ref, comp2Ref };
var comp3 = CreateEmptyCompilation(source3, references: references);
AssertUsedAssemblyReferences(comp3, new[] { comp1Ref }, references);
var source4 =
@"
public class C2
{
public static void Main()
{
_ = typeof(Type);
}
}
";
var comp4 = CreateEmptyCompilation(source4, references: new[] { comp0Ref, comp1Ref, comp2Ref });
AssertUsedAssemblyReferences(comp4, comp1Ref, comp2Ref);
}
[Fact]
public void WellKnownTypeReference_02()
{
var source3 =
@"
public class C2
{
public static void Main()
{
dynamic x = new C1();
x.M1();
}
}
class C1
{
public void M1() {}
}
";
CompileWithUsedAssemblyReferences(source3, targetFramework: TargetFramework.StandardAndCSharp);
}
[Fact]
public void WellKnownTypeReference_03()
{
var source3 =
@"
public class C2
{
public static void Main()
{
var x = new {a = 1};
x.ToString();
}
}
";
CompileWithUsedAssemblyReferences(source3, targetFramework: TargetFramework.StandardAndCSharp);
}
[Fact]
public void WellKnownTypeReference_04()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
bool b = false;
(c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = b ? default : c.getDeconstructReceiver();
}
public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); }
}
class C1
{
public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
class D3
{
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforX
getHolderforY
getHolderforZ
getDeconstructReceiver
Deconstruct1
Deconstruct2
Conversion1
Conversion2
Conversion3
setX
setY
setZ
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
CompileWithUsedAssemblyReferences(comp, expectedOutput: expected);
}
[Fact]
public void WellKnownTypeReference_05()
{
var source1 =
@"
namespace System.Runtime.CompilerServices
{
public class IsUnmanagedAttribute : System.Attribute { }
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics();
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
#pragma warning disable CS8321
public class Test
{
public void M()
{
void N<T>() where T : unmanaged
{
}
}
}
";
CompileWithUsedAssemblyReferences(source2, options: TestOptions.DebugModule, comp1Ref);
}
[Fact]
public void WellKnownTypeReference_06()
{
var source2 =
@"
public static class Test
{
public static void M(this string x)
{
}
}
";
CompileWithUsedAssemblyReferences(source2, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
}
[Fact]
public void Deconstruction_01()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void Deconstruct(this C0 x, out int y, out int z) => throw null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
var (y, z) = new C0();
_ = y;
_ = z;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
}
[Fact]
public void Deconstruction_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var source1 =
@"
public static class C1
{
public static void Deconstruct(this C0 x, out int y, out int z) => throw null;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var source2 =
@"
public class C2
{
public static void Main()
{
var (x, (y, z)) = (1, new C0());
_ = x;
_ = y;
_ = z;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp1Ref);
}
[Fact]
public void ExternAliases_01()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
var comp0Ref = comp0.ToMetadataReference();
var comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
var source1 =
@"
public static class C1
{
public static C0 F1;
}
";
var comp1 = CreateCompilation(source1, references: new[] { comp0Ref });
var comp1Ref = comp1.ToMetadataReference();
var comp1RefWithAlias = comp1Ref.WithAliases(new[] { "Alias0" });
var source2 =
@"
extern alias Alias0;
public class C2
{
public static void Main()
{
var x = new Alias0::C0();
_ = x;
}
}
";
var used = CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp1RefWithAlias);
Assert.DoesNotContain(comp1RefWithAlias, used);
used = CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp1Ref);
Assert.DoesNotContain(comp1Ref, used);
CreateCompilation(source2, references: new[] { comp0Ref, comp1RefWithAlias }).VerifyDiagnostics(
// (8,29): error CS0234: The type or namespace name 'C0' does not exist in the namespace 'Alias0' (are you missing an assembly reference?)
// var x = new Alias0::C0();
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "C0").WithArguments("C0", "Alias0").WithLocation(8, 29)
);
}
[Fact]
public void ExternAliases_02()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
MetadataReference comp0Ref = comp0.ToMetadataReference();
var comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
var source2 =
@"
extern alias Alias0;
public class C2
{
public static void Main()
{
var x = new Alias0::C0();
_ = x;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
comp0Ref = comp0.EmitToImageReference();
comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
}
[Fact]
public void ExternAliases_03()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
MetadataReference comp0Ref = comp0.ToMetadataReference();
var comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
var source2 =
@"
public class C2
{
public static void Main()
{
var x = new global::C0();
_ = x;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
comp0Ref = comp0.EmitToImageReference();
comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
}
[Fact]
public void ExternAliases_04()
{
var source0 =
@"
public class C0
{
}
";
var comp0 = CreateCompilation(source0);
MetadataReference comp0Ref = comp0.ToMetadataReference();
var comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
var source2 =
@"
public class C2
{
public static void Main()
{
var x = new C0();
_ = x;
}
}
";
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
comp0Ref = comp0.EmitToImageReference();
comp0RefWithAlias = comp0Ref.WithAliases(new[] { "Alias0" });
CompileWithUsedAssemblyReferences(source2, comp0RefWithAlias, comp0Ref);
CompileWithUsedAssemblyReferences(source2, comp0Ref, comp0RefWithAlias);
}
[Fact]
public void ExternAliases_05()
{
var source1 =
@"
namespace N1
{
public static class C1
{
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference().WithAliases(new[] { "N1C1" });
var source2 =
@"
namespace N1
{
public static class C2
{
}
}
";
var comp2 = CreateCompilation(source2);
var comp2Ref = comp2.ToMetadataReference();
var source3 =
@"
extern alias N1C1;
public class C2
{
}
";
var references = new[] { comp1Ref, comp2Ref };
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
comp1Ref);
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1)
},
new[] {
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1),
// (2,14): error CS0430: The extern alias 'N1C1' was not specified in a /reference option
// extern alias N1C1;
Diagnostic(ErrorCode.ERR_BadExternAlias, "N1C1").WithArguments("N1C1").WithLocation(2, 14)
}, references);
comp2Ref = comp2.ToMetadataReference().WithAliases(new[] { "N1C1" });
references = new[] { comp1Ref, comp2Ref };
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)),
references);
AssertUsedAssemblyReferences(CreateCompilation(source3, references: references, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)),
new MetadataReference[] { },
new[] {
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1)
},
new[] {
// (2,1): hidden CS8020: Unused extern alias.
// extern alias N1C1;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias N1C1;").WithLocation(2, 1),
// (2,14): error CS0430: The extern alias 'N1C1' was not specified in a /reference option
// extern alias N1C1;
Diagnostic(ErrorCode.ERR_BadExternAlias, "N1C1").WithArguments("N1C1").WithLocation(2, 14)
}, references);
var source4 =
@"
extern alias N1C1;
public class C2
{
static void Main()
{
_ = nameof(N1C1);
}
}
";
CompileWithUsedAssemblyReferences(source4, references);
}
[Fact]
public void ExternAliases_06()
{
var source1 =
@"
namespace N1
{
public static class C1
{
}
}
";
var comp1 = CreateCompilation(source1);
var comp1Ref = comp1.ToMetadataReference().WithAliases(new[] { "N1C1" });
var source4 =
@"
extern alias N1C1;
public class C2
{
#pragma warning disable CS1574 //: XML comment has cref attribute 'N1C1::BadType' that could not be resolved
/// <summary>
/// See <see cref=""N1C1::BadType""/>.
/// </summary>
static void Main()
{
}
}
";
CompileWithUsedAssemblyReferences(source4, comp1Ref);
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/Compilers/Core/Portable/Operations/OperationFactory.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.Operations
{
internal static class OperationFactory
{
public static IInvalidOperation CreateInvalidOperation(SemanticModel semanticModel, SyntaxNode syntax, ImmutableArray<IOperation> children, bool isImplicit)
{
return new InvalidOperation(children, semanticModel, syntax, type: null, constantValue: null, isImplicit: isImplicit);
}
public static readonly IConvertibleConversion IdentityConversion = new IdentityConvertibleConversion();
private class IdentityConvertibleConversion : IConvertibleConversion
{
public CommonConversion ToCommonConversion() => new CommonConversion(exists: true, isIdentity: true, isNumeric: false, isReference: false, methodSymbol: null, isImplicit: true, isNullable: false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Operations
{
internal static class OperationFactory
{
public static IInvalidOperation CreateInvalidOperation(SemanticModel semanticModel, SyntaxNode syntax, ImmutableArray<IOperation> children, bool isImplicit)
{
return new InvalidOperation(children, semanticModel, syntax, type: null, constantValue: null, isImplicit: isImplicit);
}
public static readonly IConvertibleConversion IdentityConversion = new IdentityConvertibleConversion();
private class IdentityConvertibleConversion : IConvertibleConversion
{
public CommonConversion ToCommonConversion() => new CommonConversion(exists: true, isIdentity: true, isNumeric: false, isReference: false, methodSymbol: null, isImplicit: true, isNullable: false);
}
}
}
| -1 |
dotnet/roslyn | 55,365 | Fix emit of synthesized types nested in a reloadable type | Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | tmat | 2021-08-03T02:36:07Z | 2021-08-04T15:48:13Z | 3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239 | d04e8ab856c3e97eecb244fdf7b275c7944025dd | Fix emit of synthesized types nested in a reloadable type. Fixes emit for the following scenario:
```C#
[System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute]
internal class Test
{
public void Do()
{
Task.Run(async() => {}).Wait();
}
}
``` | ./src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerBrowsableAttributeTests.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.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class DebuggerBrowsableAttributeTests : CSharpResultProviderTestBase
{
[Fact]
public void Never()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object F = 1;
object P { get { return 3; } }
}
class P
{
public P(C c) { }
public object G = 2;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object Q { get { return 4; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("new C()", value);
Verify(evalResult,
EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("G", "2", "object {int}", "new P(new C()).G"),
EvalResult("Raw View", null, "", "new C(), raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
children = GetChildren(children[1]);
Verify(children,
EvalResult("P", "3", "object {int}", "(new C()).P", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DebuggerBrowsableAttributes are not inherited.
/// </summary>
[Fact]
public void Never_OverridesAndImplements()
{
var source =
@"using System.Diagnostics;
interface I
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P1 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P2 { get; }
object P3 { get; }
object P4 { get; }
}
abstract class A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P5 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal virtual object P6 { get { return 0; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P7 { get; }
internal abstract object P8 { get; }
}
class B : A, I
{
public object P1 { get { return 1; } }
object I.P2 { get { return 2; } }
object I.P3 { get { return 3; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object I.P4 { get { return 4; } }
internal override object P5 { get { return 5; } }
internal override object P6 { get { return 6; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P7 { get { return 7; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P8 { get { return 8; } }
}
class C
{
I o = new B();
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("c", value);
Verify(evalResult,
EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("o", "{B}", "I {B}", "c.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite));
children = GetChildren(children[0]);
Verify(children,
EvalResult("I.P2", "2", "object {int}", "c.o.P2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("I.P3", "3", "object {int}", "c.o.P3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("P1", "1", "object {int}", "((B)c.o).P1", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite),
EvalResult("P5", "5", "object {int}", "((B)c.o).P5", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite),
EvalResult("P6", "6", "object {int}", "((B)c.o).P6", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite));
}
[Fact]
public void DuplicateAttributes()
{
var source =
@"using System.Diagnostics;
abstract class A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object P1;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object P2;
internal object P3 => 0;
}
class B : A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
new public object P1 => base.P1;
new public object P2 => 1;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal new object P3 => 2;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.Synthetic);
var evalResult = FormatResult("this", value);
Verify(evalResult,
EvalResult("this", "{B}", "B", "this", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("P3 (A)", "0", "object {int}", "((A)this).P3", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DkmClrDebuggerBrowsableAttributes are obtained from the
/// containing type and associated with the member name. For
/// explicit interface implementations, the name will include
/// namespace and type.
/// </summary>
[Fact]
public void Never_ExplicitNamespaceGeneric()
{
var source =
@"using System.Diagnostics;
namespace N1
{
namespace N2
{
class A<T>
{
internal interface I<U>
{
T P { get; }
U Q { get; }
}
}
}
class B : N2.A<object>.I<int>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object N2.A<object>.I<int>.P { get { return 1; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int Q { get { return 2; } }
}
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("N1.B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{N1.B}", "N1.B", "o"));
}
[Fact]
public void RootHidden()
{
var source =
@"using System.Diagnostics;
struct S
{
internal S(int[] x, object[] y) : this()
{
this.F = x;
this.Q = y;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int[] F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int P { get { return this.F.Length; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object[] Q { get; private set; }
}
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly B G = new B { H = 4 };
}
class B
{
internal object H;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeA = assembly.GetType("A");
var value = CreateDkmClrValue(
value: typeS.Instantiate(new int[] { 1, 2 }, new object[] { 3, typeA.Instantiate() }),
type: new DkmClrType((TypeImpl)typeS),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{S}", "S", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.F[0]"),
EvalResult("[1]", "2", "int", "o.F[1]"),
EvalResult("[0]", "3", "object {int}", "o.Q[0]"),
EvalResult("[1]", "{A}", "object {A}", "o.Q[1]", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[3]),
EvalResult("H", "4", "object {int}", "((A)o.Q[1]).G.H"));
}
[Fact]
public void RootHidden_Exception()
{
var source =
@"using System;
using System.Diagnostics;
class E : Exception
{
}
class F : E
{
object G = 1;
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
object P { get { throw new F(); } }
}";
using (new EnsureEnglishUICulture())
{
var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source)));
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = type.Instantiate();
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children[1],
EvalResult("G", "1", "object {int}", null));
Verify(children[7],
EvalResult("Message", "\"Exception of type 'F' was thrown.\"", "string", null,
DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly));
}
}
}
/// <summary>
/// Instance of type where all members are marked
/// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)].
/// </summary>
[WorkItem(934800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/934800")]
[Fact]
public void RootHidden_Empty()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F1 = new C();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F2 = new C();
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F3 = new object();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F4 = null;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // Ideally, not expandable.
var children = GetChildren(evalResult);
Verify(children); // No children.
}
[Fact]
public void DebuggerBrowsable_GenericType()
{
var source =
@"using System.Diagnostics;
class C<T>
{
internal C(T f, T g)
{
this.F = f;
this.G = g;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal readonly T F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly T G;
}
struct S
{
internal S(object o)
{
this.O = o;
}
internal readonly object O;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeC = assembly.GetType("C`1").MakeGenericType(typeS);
var value = CreateDkmClrValue(
value: typeC.Instantiate(typeS.Instantiate(1), typeS.Instantiate(2)),
type: new DkmClrType((TypeImpl)typeC),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<S>}", "C<S>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("O", "2", "object {int}", "o.G.O", DkmEvaluationResultFlags.ReadOnly));
}
[Fact]
public void RootHidden_ExplicitImplementation()
{
var source =
@"using System.Diagnostics;
interface I<T>
{
T P { get; }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
T Q { get; }
}
class A
{
internal object F;
}
class B : I<A>
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
A I<A>.P { get { return new A() { F = 1 }; } }
A I<A>.Q { get { return new A() { F = 2 }; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "1", "object {int}", "((I<A>)o).P.F"),
EvalResult("I<A>.Q", "{A}", "A", "((I<A>)o).Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("F", "2", "object {int}", "((I<A>)o).Q.F", DkmEvaluationResultFlags.CanFavorite));
}
[Fact]
public void RootHidden_ProxyType()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class A
{
internal A(int f)
{
this.F = f;
}
internal int F;
}
class P
{
private readonly A a;
public P(A a)
{
this.a = a;
}
public object Q { get { return this.a.F; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object R { get { return this.a.F + 1; } }
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F = new A(1);
internal object G = new A(3);
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Q", "1", "object {int}", "new P(o.F).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("G", "{A}", "object {A}", "o.G", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[1]),
EvalResult("F", "1", "int", "((A)o.F).F"));
Verify(GetChildren(children[2]),
EvalResult("Q", "3", "object {int}", "new P(o.G).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.G, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
}
[Fact]
public void RootHidden_Recursive()
{
var source =
@"using System.Diagnostics;
class A
{
internal A(object o)
{
this.F = o;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F;
}
class B
{
internal B(object o)
{
this.F = o;
}
internal object F;
}";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("A");
var typeB = assembly.GetType("B");
var value = CreateDkmClrValue(
value: typeA.Instantiate(typeA.Instantiate(typeA.Instantiate(typeB.Instantiate(4)))),
type: new DkmClrType((TypeImpl)typeA),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "4", "object {int}", "((B)((A)((A)o.F).F).F).F"));
}
[Fact]
public void RootHidden_OnStaticMembers()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object F = new B();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object P { get { return new C(); } }
internal static object G = 1;
}
class C
{
internal static object Q { get { return 3; } }
internal object H = 2;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("A");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("G", "1", "object {int}", "B.G"),
EvalResult("H", "2", "object {int}", "((C)B.P).H"),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[2]);
Verify(children,
EvalResult("Q", "3", "object {int}", "C.Q", DkmEvaluationResultFlags.ReadOnly));
}
// Dev12 exposes the contents of RootHidden members even
// if the members are private (e.g.: ImmutableArray<T>).
[Fact]
public void RootHidden_OnNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class C<T>
{
public C(params T[] items)
{
this.items = items;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private T[] items;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(1, 2, 3),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.items[0]"),
EvalResult("[1]", "2", "int", "o.items[1]"),
EvalResult("[2]", "3", "int", "o.items[2]"));
}
// Dev12 does not merge "Static members" (or "Non-Public
// members") across multiple RootHidden members. In
// other words, there may be multiple "Static members" (or
// "Non-Public members") rows within the same container.
[Fact]
public void RootHidden_WithStaticAndNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class A
{
public static int PA { get { return 1; } }
internal int FA = 2;
}
public class B
{
internal int PB { get { return 3; } }
public static int FB = 4;
}
public class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public readonly object FA = new A();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object PB { get { return new B(); } }
public static int PC { get { return 5; } }
internal int FC = 6;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers);
var evalResult = FormatResult("o", value, inspectionContext: inspectionContext);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult, inspectionContext: inspectionContext);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.FA, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.PB, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
Verify(GetChildren(children[0]),
EvalResult("PA", "1", "int", "A.PA", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("FA", "2", "int", "((A)o.FA).FA"));
Verify(GetChildren(children[2]),
EvalResult("FB", "4", "int", "B.FB"));
Verify(GetChildren(children[3]),
EvalResult("PB", "3", "int", "((B)o.PB).PB", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[4]),
EvalResult("PC", "5", "int", "C.PC", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[5]),
EvalResult("FC", "6", "int", "o.FC"));
}
[Fact]
public void ConstructedGenericType()
{
var source = @"
using System.Diagnostics;
public class C<T>
{
public T X;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Y;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(evalResult),
EvalResult("X", "0", "int", "o.X", DkmEvaluationResultFlags.CanFavorite));
}
[WorkItem(18581, "https://github.com/dotnet/roslyn/issues/18581")]
[Fact]
public void AccessibilityNotTrumpedByAttribute()
{
var source =
@"using System.Diagnostics;
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int[] _someArray = { 10, 20 };
private object SomethingPrivate = 3;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
internal object InternalCollapsed { get { return 1; } }
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
private object PrivateCollapsed { get { return 3; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private int[] PrivateRootHidden { get { return _someArray; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("new C()", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "10", "int", "(new C()).PrivateRootHidden[0]"),
EvalResult("[1]", "20", "int", "(new C()).PrivateRootHidden[1]"),
EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
var nonPublicChildren = GetChildren(children[2]);
Verify(nonPublicChildren,
EvalResult("InternalCollapsed", "1", "object {int}", "(new C()).InternalCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Internal),
EvalResult("PrivateCollapsed", "3", "object {int}", "(new C()).PrivateCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private),
EvalResult("SomethingPrivate", "3", "object {int}", "(new C()).SomethingPrivate", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Private));
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class DebuggerBrowsableAttributeTests : CSharpResultProviderTestBase
{
[Fact]
public void Never()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object F = 1;
object P { get { return 3; } }
}
class P
{
public P(C c) { }
public object G = 2;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object Q { get { return 4; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("new C()", value);
Verify(evalResult,
EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("G", "2", "object {int}", "new P(new C()).G"),
EvalResult("Raw View", null, "", "new C(), raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
children = GetChildren(children[1]);
Verify(children,
EvalResult("P", "3", "object {int}", "(new C()).P", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DebuggerBrowsableAttributes are not inherited.
/// </summary>
[Fact]
public void Never_OverridesAndImplements()
{
var source =
@"using System.Diagnostics;
interface I
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P1 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P2 { get; }
object P3 { get; }
object P4 { get; }
}
abstract class A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P5 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal virtual object P6 { get { return 0; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P7 { get; }
internal abstract object P8 { get; }
}
class B : A, I
{
public object P1 { get { return 1; } }
object I.P2 { get { return 2; } }
object I.P3 { get { return 3; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object I.P4 { get { return 4; } }
internal override object P5 { get { return 5; } }
internal override object P6 { get { return 6; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P7 { get { return 7; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P8 { get { return 8; } }
}
class C
{
I o = new B();
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("c", value);
Verify(evalResult,
EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("o", "{B}", "I {B}", "c.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite));
children = GetChildren(children[0]);
Verify(children,
EvalResult("I.P2", "2", "object {int}", "c.o.P2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("I.P3", "3", "object {int}", "c.o.P3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("P1", "1", "object {int}", "((B)c.o).P1", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite),
EvalResult("P5", "5", "object {int}", "((B)c.o).P5", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite),
EvalResult("P6", "6", "object {int}", "((B)c.o).P6", DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.CanFavorite));
}
[Fact]
public void DuplicateAttributes()
{
var source =
@"using System.Diagnostics;
abstract class A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object P1;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object P2;
internal object P3 => 0;
}
class B : A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
new public object P1 => base.P1;
new public object P2 => 1;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal new object P3 => 2;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.Synthetic);
var evalResult = FormatResult("this", value);
Verify(evalResult,
EvalResult("this", "{B}", "B", "this", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("P3 (A)", "0", "object {int}", "((A)this).P3", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DkmClrDebuggerBrowsableAttributes are obtained from the
/// containing type and associated with the member name. For
/// explicit interface implementations, the name will include
/// namespace and type.
/// </summary>
[Fact]
public void Never_ExplicitNamespaceGeneric()
{
var source =
@"using System.Diagnostics;
namespace N1
{
namespace N2
{
class A<T>
{
internal interface I<U>
{
T P { get; }
U Q { get; }
}
}
}
class B : N2.A<object>.I<int>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object N2.A<object>.I<int>.P { get { return 1; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int Q { get { return 2; } }
}
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("N1.B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{N1.B}", "N1.B", "o"));
}
[Fact]
public void RootHidden()
{
var source =
@"using System.Diagnostics;
struct S
{
internal S(int[] x, object[] y) : this()
{
this.F = x;
this.Q = y;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int[] F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int P { get { return this.F.Length; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object[] Q { get; private set; }
}
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly B G = new B { H = 4 };
}
class B
{
internal object H;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeA = assembly.GetType("A");
var value = CreateDkmClrValue(
value: typeS.Instantiate(new int[] { 1, 2 }, new object[] { 3, typeA.Instantiate() }),
type: new DkmClrType((TypeImpl)typeS),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{S}", "S", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.F[0]"),
EvalResult("[1]", "2", "int", "o.F[1]"),
EvalResult("[0]", "3", "object {int}", "o.Q[0]"),
EvalResult("[1]", "{A}", "object {A}", "o.Q[1]", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[3]),
EvalResult("H", "4", "object {int}", "((A)o.Q[1]).G.H"));
}
[Fact]
public void RootHidden_Exception()
{
var source =
@"using System;
using System.Diagnostics;
class E : Exception
{
}
class F : E
{
object G = 1;
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
object P { get { throw new F(); } }
}";
using (new EnsureEnglishUICulture())
{
var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source)));
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = type.Instantiate();
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children[1],
EvalResult("G", "1", "object {int}", null));
Verify(children[7],
EvalResult("Message", "\"Exception of type 'F' was thrown.\"", "string", null,
DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly));
}
}
}
/// <summary>
/// Instance of type where all members are marked
/// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)].
/// </summary>
[WorkItem(934800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/934800")]
[Fact]
public void RootHidden_Empty()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F1 = new C();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F2 = new C();
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F3 = new object();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F4 = null;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // Ideally, not expandable.
var children = GetChildren(evalResult);
Verify(children); // No children.
}
[Fact]
public void DebuggerBrowsable_GenericType()
{
var source =
@"using System.Diagnostics;
class C<T>
{
internal C(T f, T g)
{
this.F = f;
this.G = g;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal readonly T F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly T G;
}
struct S
{
internal S(object o)
{
this.O = o;
}
internal readonly object O;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeC = assembly.GetType("C`1").MakeGenericType(typeS);
var value = CreateDkmClrValue(
value: typeC.Instantiate(typeS.Instantiate(1), typeS.Instantiate(2)),
type: new DkmClrType((TypeImpl)typeC),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<S>}", "C<S>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("O", "2", "object {int}", "o.G.O", DkmEvaluationResultFlags.ReadOnly));
}
[Fact]
public void RootHidden_ExplicitImplementation()
{
var source =
@"using System.Diagnostics;
interface I<T>
{
T P { get; }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
T Q { get; }
}
class A
{
internal object F;
}
class B : I<A>
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
A I<A>.P { get { return new A() { F = 1 }; } }
A I<A>.Q { get { return new A() { F = 2 }; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "1", "object {int}", "((I<A>)o).P.F"),
EvalResult("I<A>.Q", "{A}", "A", "((I<A>)o).Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("F", "2", "object {int}", "((I<A>)o).Q.F", DkmEvaluationResultFlags.CanFavorite));
}
[Fact]
public void RootHidden_ProxyType()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class A
{
internal A(int f)
{
this.F = f;
}
internal int F;
}
class P
{
private readonly A a;
public P(A a)
{
this.a = a;
}
public object Q { get { return this.a.F; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object R { get { return this.a.F + 1; } }
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F = new A(1);
internal object G = new A(3);
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Q", "1", "object {int}", "new P(o.F).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("G", "{A}", "object {A}", "o.G", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[1]),
EvalResult("F", "1", "int", "((A)o.F).F"));
Verify(GetChildren(children[2]),
EvalResult("Q", "3", "object {int}", "new P(o.G).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.G, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
}
[Fact]
public void RootHidden_Recursive()
{
var source =
@"using System.Diagnostics;
class A
{
internal A(object o)
{
this.F = o;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F;
}
class B
{
internal B(object o)
{
this.F = o;
}
internal object F;
}";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("A");
var typeB = assembly.GetType("B");
var value = CreateDkmClrValue(
value: typeA.Instantiate(typeA.Instantiate(typeA.Instantiate(typeB.Instantiate(4)))),
type: new DkmClrType((TypeImpl)typeA),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "4", "object {int}", "((B)((A)((A)o.F).F).F).F"));
}
[Fact]
public void RootHidden_OnStaticMembers()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object F = new B();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object P { get { return new C(); } }
internal static object G = 1;
}
class C
{
internal static object Q { get { return 3; } }
internal object H = 2;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("A");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("G", "1", "object {int}", "B.G"),
EvalResult("H", "2", "object {int}", "((C)B.P).H"),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[2]);
Verify(children,
EvalResult("Q", "3", "object {int}", "C.Q", DkmEvaluationResultFlags.ReadOnly));
}
// Dev12 exposes the contents of RootHidden members even
// if the members are private (e.g.: ImmutableArray<T>).
[Fact]
public void RootHidden_OnNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class C<T>
{
public C(params T[] items)
{
this.items = items;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private T[] items;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(1, 2, 3),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.items[0]"),
EvalResult("[1]", "2", "int", "o.items[1]"),
EvalResult("[2]", "3", "int", "o.items[2]"));
}
// Dev12 does not merge "Static members" (or "Non-Public
// members") across multiple RootHidden members. In
// other words, there may be multiple "Static members" (or
// "Non-Public members") rows within the same container.
[Fact]
public void RootHidden_WithStaticAndNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class A
{
public static int PA { get { return 1; } }
internal int FA = 2;
}
public class B
{
internal int PB { get { return 3; } }
public static int FB = 4;
}
public class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public readonly object FA = new A();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object PB { get { return new B(); } }
public static int PC { get { return 5; } }
internal int FC = 6;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers);
var evalResult = FormatResult("o", value, inspectionContext: inspectionContext);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult, inspectionContext: inspectionContext);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.FA, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.PB, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
Verify(GetChildren(children[0]),
EvalResult("PA", "1", "int", "A.PA", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("FA", "2", "int", "((A)o.FA).FA"));
Verify(GetChildren(children[2]),
EvalResult("FB", "4", "int", "B.FB"));
Verify(GetChildren(children[3]),
EvalResult("PB", "3", "int", "((B)o.PB).PB", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[4]),
EvalResult("PC", "5", "int", "C.PC", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[5]),
EvalResult("FC", "6", "int", "o.FC"));
}
[Fact]
public void ConstructedGenericType()
{
var source = @"
using System.Diagnostics;
public class C<T>
{
public T X;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Y;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(evalResult),
EvalResult("X", "0", "int", "o.X", DkmEvaluationResultFlags.CanFavorite));
}
[WorkItem(18581, "https://github.com/dotnet/roslyn/issues/18581")]
[Fact]
public void AccessibilityNotTrumpedByAttribute()
{
var source =
@"using System.Diagnostics;
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int[] _someArray = { 10, 20 };
private object SomethingPrivate = 3;
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
internal object InternalCollapsed { get { return 1; } }
[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
private object PrivateCollapsed { get { return 3; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private int[] PrivateRootHidden { get { return _someArray; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("new C()", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "10", "int", "(new C()).PrivateRootHidden[0]"),
EvalResult("[1]", "20", "int", "(new C()).PrivateRootHidden[1]"),
EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
var nonPublicChildren = GetChildren(children[2]);
Verify(nonPublicChildren,
EvalResult("InternalCollapsed", "1", "object {int}", "(new C()).InternalCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Internal),
EvalResult("PrivateCollapsed", "3", "object {int}", "(new C()).PrivateCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private),
EvalResult("SomethingPrivate", "3", "object {int}", "(new C()).SomethingPrivate", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Private));
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace
{
using static ConvertNamespaceAnalysis;
using static ConvertNamespaceTransform;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertNamespace), Shared]
internal class ConvertNamespaceCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ConvertNamespaceCodeFixProvider()
{
}
internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseBlockScopedNamespaceDiagnosticId, IDEDiagnosticIds.UseFileScopedNamespaceDiagnosticId);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var (title, equivalenceKey) = GetInfo(
diagnostic.Id switch
{
IDEDiagnosticIds.UseBlockScopedNamespaceDiagnosticId => NamespaceDeclarationPreference.BlockScoped,
IDEDiagnosticIds.UseFileScopedNamespaceDiagnosticId => NamespaceDeclarationPreference.FileScoped,
_ => throw ExceptionUtilities.UnexpectedValue(diagnostic.Id),
});
context.RegisterCodeFix(
new MyCodeAction(title, c => FixAsync(context.Document, diagnostic, c), equivalenceKey),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var diagnostic = diagnostics.First();
var namespaceDecl = (BaseNamespaceDeclarationSyntax)diagnostic.Location.FindNode(cancellationToken);
var converted = Convert(namespaceDecl);
editor.ReplaceNode(namespaceDecl, converted);
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey)
: base(title, createChangedDocument, equivalenceKey)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace
{
using static ConvertNamespaceAnalysis;
using static ConvertNamespaceTransform;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertNamespace), Shared]
internal class ConvertNamespaceCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ConvertNamespaceCodeFixProvider()
{
}
internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseBlockScopedNamespaceDiagnosticId, IDEDiagnosticIds.UseFileScopedNamespaceDiagnosticId);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var (title, equivalenceKey) = GetInfo(
diagnostic.Id switch
{
IDEDiagnosticIds.UseBlockScopedNamespaceDiagnosticId => NamespaceDeclarationPreference.BlockScoped,
IDEDiagnosticIds.UseFileScopedNamespaceDiagnosticId => NamespaceDeclarationPreference.FileScoped,
_ => throw ExceptionUtilities.UnexpectedValue(diagnostic.Id),
});
context.RegisterCodeFix(
new MyCodeAction(title, c => FixAsync(context.Document, diagnostic, c), equivalenceKey),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var diagnostic = diagnostics.First();
var namespaceDecl = (BaseNamespaceDeclarationSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken);
var converted = Convert(namespaceDecl);
editor.ReplaceNode(namespaceDecl, converted);
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey)
: base(title, createChangedDocument, equivalenceKey)
{
}
}
}
}
| 1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Dependencies/PooledObjects/Microsoft.CodeAnalysis.PooledObjects.Package.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>
<TargetFrameworks>netstandard1.3;net45</TargetFrameworks>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<DebugType>none</DebugType>
<GenerateDependencyFile>false</GenerateDependencyFile>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<IsSourcePackage>true</IsSourcePackage>
<PackageId>Microsoft.CodeAnalysis.PooledObjects</PackageId>
<IncludeBuildOutput>false</IncludeBuildOutput>
<PackageDescription>
Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") pooled objects.
</PackageDescription>
<!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed -->
<NoWarn>$(NoWarn);NU5128</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Debugging.Package"/>
</ItemGroup>
</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>
<TargetFrameworks>netstandard1.3;net45</TargetFrameworks>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<DebugType>none</DebugType>
<GenerateDependencyFile>false</GenerateDependencyFile>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<IsSourcePackage>true</IsSourcePackage>
<PackageId>Microsoft.CodeAnalysis.PooledObjects</PackageId>
<IncludeBuildOutput>false</IncludeBuildOutput>
<PackageDescription>
Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") pooled objects.
</PackageDescription>
<!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed -->
<NoWarn>$(NoWarn);NU5128</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Debugging.Package"/>
</ItemGroup>
</Project>
| 1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/EditorFeatures/CSharpTest/ConvertNamespace/ConvertToBlockScopedNamespaceAnalyzerTests.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.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.ConvertNamespace;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNamespace
{
using VerifyCS = CSharpCodeFixVerifier<ConvertToBlockScopedNamespaceDiagnosticAnalyzer, ConvertNamespaceCodeFixProvider>;
public class ConvertToBlockScopedNamespaceAnalyzerTests
{
#region Convert To Block Scoped
[Fact]
public async Task TestConvertToBlockScopedInCSharp9()
{
await new VerifyCS.Test
{
TestCode = @"
[|{|CS8773:namespace|} N;|]
",
FixedCode = @"
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp9,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertToBlockScopedInCSharp10WithBlockScopedPreference()
{
var code = @"
namespace N {}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedInCSharp10WithFileScopedPreference()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
",
FixedCode = @"
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockSpan()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
",
FixedCode = @"
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithMultipleNamespaces()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
namespace {|CS8955:N2|}
{
}
",
FixedCode = @"
namespace N
{
namespace N2
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithNestedNamespaces1()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
[|namespace {|CS8954:N2|};|]",
FixedCode = @"
namespace N
{
namespace N2
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
NumberOfFixAllIterations = 2,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithNestedNamespaces2()
{
await new VerifyCS.Test
{
TestCode = @"
namespace N
{
[|namespace {|CS8955:N2|};|]
}
",
FixedCode = @"
namespace N
{
namespace $$N2
{
}
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithTopLevelStatement1()
{
await new VerifyCS.Test
{
TestCode = @"
{|CS8805:int i = 0;|}
[|namespace {|CS8956:N|};|]
",
FixedCode = @"
{|CS8805:int i = 0;|}
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithTopLevelStatement2()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
int {|CS0116:i|} = 0;
",
FixedCode = @"
namespace N
{
int {|CS0116:i|} = 0;
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithUsing1()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
[|namespace N;|]
",
FixedCode = @"
using System;
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithUsing2()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
using System;
",
FixedCode = @"
namespace $$N
{
using System;
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithClass()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
class C
{
}
",
FixedCode = @"
namespace $$N
{
class C
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithClassWithDocComment()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
/// <summary/>
class C
{
}
",
FixedCode = @"
namespace N
{
/// <summary/>
class C
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithMissingCloseBrace()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
/// <summary/>
class C
{{|CS1513:|}",
FixedCode = @"
namespace N
{
/// <summary/>
class C
{}{|CS1513:|}",
LanguageVersion = LanguageVersion.CSharp10,
CodeActionValidationMode = CodeActionValidationMode.None,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithCommentOnSemicolon()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|] // comment
class C
{
}
",
FixedCode = @"
namespace N
{ // comment
class C
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithLeadingComment()
{
await new VerifyCS.Test
{
TestCode = @"
// copyright
[|namespace N;|]
class C
{
}
",
FixedCode = @"
// copyright
namespace N
{
class C
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
#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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.ConvertNamespace;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNamespace
{
using VerifyCS = CSharpCodeFixVerifier<ConvertToBlockScopedNamespaceDiagnosticAnalyzer, ConvertNamespaceCodeFixProvider>;
public class ConvertToBlockScopedNamespaceAnalyzerTests
{
#region Convert To Block Scoped
[Fact]
public async Task TestConvertToBlockScopedInCSharp9()
{
await new VerifyCS.Test
{
TestCode = @"
[|{|CS8773:namespace|} N;|]
",
FixedCode = @"
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp9,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedInCSharp9_NotSilent()
{
await new VerifyCS.Test
{
TestCode = @"
{|CS8773:namespace|} [|N|];
",
FixedCode = @"
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp9,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Suggestion }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertToBlockScopedInCSharp10WithBlockScopedPreference()
{
var code = @"
namespace N {}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedInCSharp10WithFileScopedPreference()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
",
FixedCode = @"
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockSpan()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
",
FixedCode = @"
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithMultipleNamespaces()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
namespace {|CS8955:N2|}
{
}
",
FixedCode = @"
namespace N
{
namespace N2
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithNestedNamespaces1()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
[|namespace {|CS8954:N2|};|]",
FixedCode = @"
namespace N
{
namespace N2
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
NumberOfFixAllIterations = 2,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithNestedNamespaces2()
{
await new VerifyCS.Test
{
TestCode = @"
namespace N
{
[|namespace {|CS8955:N2|};|]
}
",
FixedCode = @"
namespace N
{
namespace $$N2
{
}
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithTopLevelStatement1()
{
await new VerifyCS.Test
{
TestCode = @"
{|CS8805:int i = 0;|}
[|namespace {|CS8956:N|};|]
",
FixedCode = @"
{|CS8805:int i = 0;|}
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockWithTopLevelStatement2()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
int {|CS0116:i|} = 0;
",
FixedCode = @"
namespace N
{
int {|CS0116:i|} = 0;
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithUsing1()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
[|namespace N;|]
",
FixedCode = @"
using System;
namespace N
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithUsing2()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
using System;
",
FixedCode = @"
namespace $$N
{
using System;
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithClass()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
class C
{
}
",
FixedCode = @"
namespace $$N
{
class C
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithClassWithDocComment()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
/// <summary/>
class C
{
}
",
FixedCode = @"
namespace N
{
/// <summary/>
class C
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithMissingCloseBrace()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|]
/// <summary/>
class C
{{|CS1513:|}",
FixedCode = @"
namespace N
{
/// <summary/>
class C
{}{|CS1513:|}",
LanguageVersion = LanguageVersion.CSharp10,
CodeActionValidationMode = CodeActionValidationMode.None,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithCommentOnSemicolon()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N;|] // comment
class C
{
}
",
FixedCode = @"
namespace N
{ // comment
class C
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToBlockScopedWithLeadingComment()
{
await new VerifyCS.Test
{
TestCode = @"
// copyright
[|namespace N;|]
class C
{
}
",
FixedCode = @"
// copyright
namespace N
{
class C
{
}
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
#endregion
}
}
| 1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/EditorFeatures/CSharpTest/ConvertNamespace/ConvertToFileScopedNamespaceAnalyzerTests.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.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.ConvertNamespace;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNamespace
{
using VerifyCS = CSharpCodeFixVerifier<ConvertToFileScopedNamespaceDiagnosticAnalyzer, ConvertNamespaceCodeFixProvider>;
public class ConvertToFileScopedNamespaceAnalyzerTests
{
#region Convert To File Scoped
[Fact]
public async Task TestNoConvertToFileScopedInCSharp9()
{
var code = @"
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp9,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertToFileScopedInCSharp10WithBlockScopedPreference()
{
var code = @"
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
}
",
FixedCode = @"
namespace $$N;
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertWithMultipleNamespaces()
{
var code = @"
namespace N
{
}
namespace N2
{
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertWithNestedNamespaces1()
{
var code = @"
namespace N
{
namespace N2
{
}
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertWithTopLevelStatement1()
{
var code = @"
{|CS8805:int i = 0;|}
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertWithTopLevelStatement2()
{
var code = @"
namespace N
{
}
int i = 0;
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
ExpectedDiagnostics =
{
// /0/Test0.cs(6,1): error CS8803: Top-level statements must precede namespace and type declarations.
DiagnosticResult.CompilerError("CS8803").WithSpan(6, 1, 6, 11),
// /0/Test0.cs(6,1): error CS8805: Program using top-level statements must be an executable.
DiagnosticResult.CompilerError("CS8805").WithSpan(6, 1, 6, 11),
},
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithUsing1()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
[|namespace N|]
{
}
",
FixedCode = @"
using System;
namespace $$N;
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithUsing2()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
using System;
}
",
FixedCode = @"
namespace $$N;
using System;
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithClass()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
class C
{
}
}
",
FixedCode = @"
namespace $$N;
class C
{
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithClassWithDocComment()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
/// <summary/>
class C
{
}
}
",
FixedCode = @"
namespace $$N;
/// <summary/>
class C
{
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithMissingCloseBrace()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
/// <summary/>
class C
{
}{|CS1513:|}",
FixedCode = @"
namespace N;
/// <summary/>
class C
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithCommentOnOpenCurly()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{ // comment
class C
{
}
}
",
FixedCode = @"
namespace $$N; // comment
class C
{
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithLeadingComment()
{
await new VerifyCS.Test
{
TestCode = @"
// copyright
[|namespace N|]
{
class C
{
}
}
",
FixedCode = @"
// copyright
namespace $$N;
class C
{
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
#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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.ConvertNamespace;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNamespace
{
using VerifyCS = CSharpCodeFixVerifier<ConvertToFileScopedNamespaceDiagnosticAnalyzer, ConvertNamespaceCodeFixProvider>;
public class ConvertToFileScopedNamespaceAnalyzerTests
{
#region Convert To File Scoped
[Fact]
public async Task TestNoConvertToFileScopedInCSharp9()
{
var code = @"
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp9,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertToFileScopedInCSharp10WithBlockScopedPreference()
{
var code = @"
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
}
",
FixedCode = @"
namespace $$N;
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference_NotSilent()
{
await new VerifyCS.Test
{
TestCode = @"
namespace [|N|]
{
}
",
FixedCode = @"
namespace $$N;
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Suggestion }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertWithMultipleNamespaces()
{
var code = @"
namespace N
{
}
namespace N2
{
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertWithNestedNamespaces1()
{
var code = @"
namespace N
{
namespace N2
{
}
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertWithTopLevelStatement1()
{
var code = @"
{|CS8805:int i = 0;|}
namespace N
{
}
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestNoConvertWithTopLevelStatement2()
{
var code = @"
namespace N
{
}
int i = 0;
";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = code,
LanguageVersion = LanguageVersion.CSharp10,
ExpectedDiagnostics =
{
// /0/Test0.cs(6,1): error CS8803: Top-level statements must precede namespace and type declarations.
DiagnosticResult.CompilerError("CS8803").WithSpan(6, 1, 6, 11),
// /0/Test0.cs(6,1): error CS8805: Program using top-level statements must be an executable.
DiagnosticResult.CompilerError("CS8805").WithSpan(6, 1, 6, 11),
},
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithUsing1()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
[|namespace N|]
{
}
",
FixedCode = @"
using System;
namespace $$N;
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithUsing2()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
using System;
}
",
FixedCode = @"
namespace $$N;
using System;
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithClass()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
class C
{
}
}
",
FixedCode = @"
namespace $$N;
class C
{
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithClassWithDocComment()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
/// <summary/>
class C
{
}
}
",
FixedCode = @"
namespace $$N;
/// <summary/>
class C
{
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithMissingCloseBrace()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{
/// <summary/>
class C
{
}{|CS1513:|}",
FixedCode = @"
namespace N;
/// <summary/>
class C
{
}",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithCommentOnOpenCurly()
{
await new VerifyCS.Test
{
TestCode = @"
[|namespace N|]
{ // comment
class C
{
}
}
",
FixedCode = @"
namespace $$N; // comment
class C
{
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
[Fact]
public async Task TestConvertToFileScopedWithLeadingComment()
{
await new VerifyCS.Test
{
TestCode = @"
// copyright
[|namespace N|]
{
class C
{
}
}
",
FixedCode = @"
// copyright
namespace $$N;
class C
{
}
",
LanguageVersion = LanguageVersion.CSharp10,
Options =
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped }
}
}.RunAsync();
}
#endregion
}
}
| 1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Dependencies/Collections/ImmutableSegmentedList`1+Builder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Collections.Internal;
namespace Microsoft.CodeAnalysis.Collections
{
internal partial struct ImmutableSegmentedList<T>
{
public sealed class Builder : IList<T>, IReadOnlyList<T>, IList
{
/// <summary>
/// The immutable collection this builder is based on.
/// </summary>
private ValueBuilder _builder;
internal Builder(ImmutableSegmentedList<T> list)
=> _builder = new ValueBuilder(list);
public int Count => _builder.Count;
bool ICollection<T>.IsReadOnly => ICollectionCalls<T>.IsReadOnly(ref _builder);
bool IList.IsFixedSize => IListCalls.IsFixedSize(ref _builder);
bool IList.IsReadOnly => IListCalls.IsReadOnly(ref _builder);
bool ICollection.IsSynchronized => ICollectionCalls.IsSynchronized(ref _builder);
object ICollection.SyncRoot => this;
public T this[int index]
{
get => _builder[index];
set => _builder[index] = value;
}
object? IList.this[int index]
{
get => IListCalls.GetItem(ref _builder, index);
set => IListCalls.SetItem(ref _builder, index, value);
}
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.ItemRef(int)"/>
public ref readonly T ItemRef(int index)
=> ref _builder.ItemRef(index);
public void Add(T item)
=> _builder.Add(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.AddRange(IEnumerable{T})"/>
public void AddRange(IEnumerable<T> items)
=> _builder.AddRange(items);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.BinarySearch(T)"/>
public int BinarySearch(T item)
=> _builder.BinarySearch(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.BinarySearch(T, IComparer{T}?)"/>
public int BinarySearch(T item, IComparer<T>? comparer)
=> _builder.BinarySearch(item, comparer);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.BinarySearch(int, int, T, IComparer{T}?)"/>
public int BinarySearch(int index, int count, T item, IComparer<T>? comparer)
=> _builder.BinarySearch(index, count, item, comparer);
public void Clear()
=> _builder.Clear();
public bool Contains(T item)
=> _builder.Contains(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.ConvertAll{TOutput}(Func{T, TOutput})"/>
public ImmutableSegmentedList<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)
=> _builder.ConvertAll(converter);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.CopyTo(T[])"/>
public void CopyTo(T[] array)
=> _builder.CopyTo(array);
public void CopyTo(T[] array, int arrayIndex)
=> _builder.CopyTo(array, arrayIndex);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.CopyTo(int, T[], int, int)"/>
public void CopyTo(int index, T[] array, int arrayIndex, int count)
=> _builder.CopyTo(index, array, arrayIndex, count);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Exists(Predicate{T})"/>
public bool Exists(Predicate<T> match)
=> _builder.Exists(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Find(Predicate{T})"/>
public T? Find(Predicate<T> match)
=> _builder.Find(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindAll(Predicate{T})"/>
public ImmutableSegmentedList<T> FindAll(Predicate<T> match)
=> _builder.FindAll(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindIndex(Predicate{T})"/>
public int FindIndex(Predicate<T> match)
=> _builder.FindIndex(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindIndex(int, Predicate{T})"/>
public int FindIndex(int startIndex, Predicate<T> match)
=> _builder.FindIndex(startIndex, match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindIndex(int, int, Predicate{T})"/>
public int FindIndex(int startIndex, int count, Predicate<T> match)
=> _builder.FindIndex(startIndex, count, match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindLast(Predicate{T})"/>
public T? FindLast(Predicate<T> match)
=> _builder.FindLast(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindLastIndex(Predicate{T})"/>
public int FindLastIndex(Predicate<T> match)
=> _builder.FindLastIndex(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindLastIndex(int, Predicate{T})"/>
public int FindLastIndex(int startIndex, Predicate<T> match)
=> _builder.FindLastIndex(startIndex, match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindLastIndex(int, int, Predicate{T})"/>
public int FindLastIndex(int startIndex, int count, Predicate<T> match)
=> _builder.FindLastIndex(startIndex, count, match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.ForEach(Action{T})"/>
public void ForEach(Action<T> action)
=> _builder.ForEach(action);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.GetEnumerator()"/>
public Enumerator GetEnumerator()
=> _builder.GetEnumerator();
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.GetRange(int, int)"/>
public ImmutableSegmentedList<T> GetRange(int index, int count)
=> _builder.GetRange(index, count);
public int IndexOf(T item)
=> _builder.IndexOf(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.IndexOf(T, int)"/>
public int IndexOf(T item, int index)
=> _builder.IndexOf(item, index);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.IndexOf(T, int, int)"/>
public int IndexOf(T item, int index, int count)
=> _builder.IndexOf(item, index, count);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.IndexOf(T, int, int, IEqualityComparer{T}?)"/>
public int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer)
=> _builder.IndexOf(item, index, count, equalityComparer);
public void Insert(int index, T item)
=> _builder.Insert(index, item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.InsertRange(int, IEnumerable{T})"/>
public void InsertRange(int index, IEnumerable<T> items)
=> _builder.InsertRange(index, items);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.LastIndexOf(T)"/>
public int LastIndexOf(T item)
=> _builder.LastIndexOf(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.LastIndexOf(T, int)"/>
public int LastIndexOf(T item, int startIndex)
=> _builder.LastIndexOf(item, startIndex);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.LastIndexOf(T, int, int)"/>
public int LastIndexOf(T item, int startIndex, int count)
=> _builder.LastIndexOf(item, startIndex, count);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.LastIndexOf(T, int, int, IEqualityComparer{T}?)"/>
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer)
=> _builder.LastIndexOf(item, startIndex, count, equalityComparer);
public bool Remove(T item)
=> _builder.Remove(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.RemoveAll(Predicate{T})"/>
public int RemoveAll(Predicate<T> match)
=> _builder.RemoveAll(match);
public void RemoveAt(int index)
=> _builder.RemoveAt(index);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Reverse()"/>
public void Reverse()
=> _builder.Reverse();
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Reverse(int, int)"/>
public void Reverse(int index, int count)
=> _builder.Reverse(index, count);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Sort()"/>
public void Sort()
=> _builder.Sort();
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Sort(IComparer{T}?)"/>
public void Sort(IComparer<T>? comparer)
=> _builder.Sort(comparer);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Sort(Comparison{T})"/>
public void Sort(Comparison<T> comparison)
=> _builder.Sort(comparison);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Sort(int, int, IComparer{T}?)"/>
public void Sort(int index, int count, IComparer<T>? comparer)
=> _builder.Sort(index, count, comparer);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.ToImmutable()"/>
public ImmutableSegmentedList<T> ToImmutable()
=> _builder.ToImmutable();
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.TrueForAll(Predicate{T})"/>
public bool TrueForAll(Predicate<T> match)
=> _builder.TrueForAll(match);
IEnumerator<T> IEnumerable<T>.GetEnumerator()
=> IEnumerableCalls<T>.GetEnumerator(ref _builder);
IEnumerator IEnumerable.GetEnumerator()
=> IEnumerableCalls.GetEnumerator(ref _builder);
int IList.Add(object? value)
=> IListCalls.Add(ref _builder, value);
bool IList.Contains(object? value)
=> IListCalls.Contains(ref _builder, value);
int IList.IndexOf(object? value)
=> IListCalls.IndexOf(ref _builder, value);
void IList.Insert(int index, object? value)
=> IListCalls.Insert(ref _builder, index, value);
void IList.Remove(object? value)
=> IListCalls.Remove(ref _builder, value);
void ICollection.CopyTo(Array array, int index)
=> ICollectionCalls.CopyTo(ref _builder, array, index);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Collections.Internal;
namespace Microsoft.CodeAnalysis.Collections
{
internal partial struct ImmutableSegmentedList<T>
{
public sealed class Builder : IList<T>, IReadOnlyList<T>, IList
{
/// <summary>
/// The immutable collection this builder is based on.
/// </summary>
private ValueBuilder _builder;
internal Builder(ImmutableSegmentedList<T> list)
=> _builder = new ValueBuilder(list);
public int Count => _builder.Count;
bool ICollection<T>.IsReadOnly => ICollectionCalls<T>.IsReadOnly(ref _builder);
bool IList.IsFixedSize => IListCalls.IsFixedSize(ref _builder);
bool IList.IsReadOnly => IListCalls.IsReadOnly(ref _builder);
bool ICollection.IsSynchronized => ICollectionCalls.IsSynchronized(ref _builder);
object ICollection.SyncRoot => this;
public T this[int index]
{
get => _builder[index];
set => _builder[index] = value;
}
object? IList.this[int index]
{
get => IListCalls.GetItem(ref _builder, index);
set => IListCalls.SetItem(ref _builder, index, value);
}
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.ItemRef(int)"/>
public ref readonly T ItemRef(int index)
=> ref _builder.ItemRef(index);
public void Add(T item)
=> _builder.Add(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.AddRange(IEnumerable{T})"/>
public void AddRange(IEnumerable<T> items)
=> _builder.AddRange(items);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.BinarySearch(T)"/>
public int BinarySearch(T item)
=> _builder.BinarySearch(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.BinarySearch(T, IComparer{T}?)"/>
public int BinarySearch(T item, IComparer<T>? comparer)
=> _builder.BinarySearch(item, comparer);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.BinarySearch(int, int, T, IComparer{T}?)"/>
public int BinarySearch(int index, int count, T item, IComparer<T>? comparer)
=> _builder.BinarySearch(index, count, item, comparer);
public void Clear()
=> _builder.Clear();
public bool Contains(T item)
=> _builder.Contains(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.ConvertAll{TOutput}(Func{T, TOutput})"/>
public ImmutableSegmentedList<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)
=> _builder.ConvertAll(converter);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.CopyTo(T[])"/>
public void CopyTo(T[] array)
=> _builder.CopyTo(array);
public void CopyTo(T[] array, int arrayIndex)
=> _builder.CopyTo(array, arrayIndex);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.CopyTo(int, T[], int, int)"/>
public void CopyTo(int index, T[] array, int arrayIndex, int count)
=> _builder.CopyTo(index, array, arrayIndex, count);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Exists(Predicate{T})"/>
public bool Exists(Predicate<T> match)
=> _builder.Exists(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Find(Predicate{T})"/>
public T? Find(Predicate<T> match)
=> _builder.Find(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindAll(Predicate{T})"/>
public ImmutableSegmentedList<T> FindAll(Predicate<T> match)
=> _builder.FindAll(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindIndex(Predicate{T})"/>
public int FindIndex(Predicate<T> match)
=> _builder.FindIndex(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindIndex(int, Predicate{T})"/>
public int FindIndex(int startIndex, Predicate<T> match)
=> _builder.FindIndex(startIndex, match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindIndex(int, int, Predicate{T})"/>
public int FindIndex(int startIndex, int count, Predicate<T> match)
=> _builder.FindIndex(startIndex, count, match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindLast(Predicate{T})"/>
public T? FindLast(Predicate<T> match)
=> _builder.FindLast(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindLastIndex(Predicate{T})"/>
public int FindLastIndex(Predicate<T> match)
=> _builder.FindLastIndex(match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindLastIndex(int, Predicate{T})"/>
public int FindLastIndex(int startIndex, Predicate<T> match)
=> _builder.FindLastIndex(startIndex, match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.FindLastIndex(int, int, Predicate{T})"/>
public int FindLastIndex(int startIndex, int count, Predicate<T> match)
=> _builder.FindLastIndex(startIndex, count, match);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.ForEach(Action{T})"/>
public void ForEach(Action<T> action)
=> _builder.ForEach(action);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.GetEnumerator()"/>
public Enumerator GetEnumerator()
=> _builder.GetEnumerator();
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.GetRange(int, int)"/>
public ImmutableSegmentedList<T> GetRange(int index, int count)
=> _builder.GetRange(index, count);
public int IndexOf(T item)
=> _builder.IndexOf(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.IndexOf(T, int)"/>
public int IndexOf(T item, int index)
=> _builder.IndexOf(item, index);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.IndexOf(T, int, int)"/>
public int IndexOf(T item, int index, int count)
=> _builder.IndexOf(item, index, count);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.IndexOf(T, int, int, IEqualityComparer{T}?)"/>
public int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer)
=> _builder.IndexOf(item, index, count, equalityComparer);
public void Insert(int index, T item)
=> _builder.Insert(index, item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.InsertRange(int, IEnumerable{T})"/>
public void InsertRange(int index, IEnumerable<T> items)
=> _builder.InsertRange(index, items);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.LastIndexOf(T)"/>
public int LastIndexOf(T item)
=> _builder.LastIndexOf(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.LastIndexOf(T, int)"/>
public int LastIndexOf(T item, int startIndex)
=> _builder.LastIndexOf(item, startIndex);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.LastIndexOf(T, int, int)"/>
public int LastIndexOf(T item, int startIndex, int count)
=> _builder.LastIndexOf(item, startIndex, count);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.LastIndexOf(T, int, int, IEqualityComparer{T}?)"/>
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer)
=> _builder.LastIndexOf(item, startIndex, count, equalityComparer);
public bool Remove(T item)
=> _builder.Remove(item);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.RemoveAll(Predicate{T})"/>
public int RemoveAll(Predicate<T> match)
=> _builder.RemoveAll(match);
public void RemoveAt(int index)
=> _builder.RemoveAt(index);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Reverse()"/>
public void Reverse()
=> _builder.Reverse();
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Reverse(int, int)"/>
public void Reverse(int index, int count)
=> _builder.Reverse(index, count);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Sort()"/>
public void Sort()
=> _builder.Sort();
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Sort(IComparer{T}?)"/>
public void Sort(IComparer<T>? comparer)
=> _builder.Sort(comparer);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Sort(Comparison{T})"/>
public void Sort(Comparison<T> comparison)
=> _builder.Sort(comparison);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.Sort(int, int, IComparer{T}?)"/>
public void Sort(int index, int count, IComparer<T>? comparer)
=> _builder.Sort(index, count, comparer);
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.ToImmutable()"/>
public ImmutableSegmentedList<T> ToImmutable()
=> _builder.ToImmutable();
/// <inheritdoc cref="System.Collections.Immutable.ImmutableList{T}.Builder.TrueForAll(Predicate{T})"/>
public bool TrueForAll(Predicate<T> match)
=> _builder.TrueForAll(match);
IEnumerator<T> IEnumerable<T>.GetEnumerator()
=> IEnumerableCalls<T>.GetEnumerator(ref _builder);
IEnumerator IEnumerable.GetEnumerator()
=> IEnumerableCalls.GetEnumerator(ref _builder);
int IList.Add(object? value)
=> IListCalls.Add(ref _builder, value);
bool IList.Contains(object? value)
=> IListCalls.Contains(ref _builder, value);
int IList.IndexOf(object? value)
=> IListCalls.IndexOf(ref _builder, value);
void IList.Insert(int index, object? value)
=> IListCalls.Insert(ref _builder, index, value);
void IList.Remove(object? value)
=> IListCalls.Remove(ref _builder, value);
void ICollection.CopyTo(Array array, int index)
=> ICollectionCalls.CopyTo(ref _builder, array, index);
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.Empty.Collection.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;
namespace Roslyn.Utilities
{
internal static partial class SpecializedCollections
{
private static partial class Empty
{
internal class Collection<T> : Enumerable<T>, ICollection<T>
{
public static readonly ICollection<T> Instance = new Collection<T>();
protected Collection()
{
}
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
}
public int Count => 0;
public bool IsReadOnly => true;
public bool Remove(T item)
{
throw new NotSupportedException();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Roslyn.Utilities
{
internal static partial class SpecializedCollections
{
private static partial class Empty
{
internal class Collection<T> : Enumerable<T>, ICollection<T>
{
public static readonly ICollection<T> Instance = new Collection<T>();
protected Collection()
{
}
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
}
public int Count => 0;
public bool IsReadOnly => true;
public bool Remove(T item)
{
throw new NotSupportedException();
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Compilers/CSharp/Portable/CSharpFileSystemExtensions.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.IO;
using System.Threading;
using Microsoft.CodeAnalysis.Emit;
namespace Microsoft.CodeAnalysis.CSharp
{
public static class CSharpFileSystemExtensions
{
/// <summary>
/// Emit the IL for the compilation into the specified stream.
/// </summary>
/// <param name="compilation">Compilation.</param>
/// <param name="outputPath">Path of the file to which the PE image will be written.</param>
/// <param name="pdbPath">Path of the file to which the compilation's debug info will be written.
/// Also embedded in the output file. Null to forego PDB generation.
/// </param>
/// <param name="xmlDocumentationPath">Path of the file to which the compilation's XML documentation will be written. Null to forego XML generation.</param>
/// <param name="win32ResourcesPath">Path of the file from which the compilation's Win32 resources will be read (in RES format).
/// Null to indicate that there are none.</param>
/// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param>
/// <param name="cancellationToken">To cancel the emit process.</param>
/// <exception cref="ArgumentNullException">Compilation or path is null.</exception>
/// <exception cref="ArgumentException">Path is empty or invalid.</exception>
/// <exception cref="IOException">An error occurred while reading or writing a file.</exception>
public static EmitResult Emit(
this CSharpCompilation compilation,
string outputPath,
string? pdbPath = null,
string? xmlDocumentationPath = null,
string? win32ResourcesPath = null,
IEnumerable<ResourceDescription>? manifestResources = null,
CancellationToken cancellationToken = default)
{
return FileSystemExtensions.Emit(compilation, outputPath, pdbPath, xmlDocumentationPath, win32ResourcesPath, manifestResources, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Microsoft.CodeAnalysis.Emit;
namespace Microsoft.CodeAnalysis.CSharp
{
public static class CSharpFileSystemExtensions
{
/// <summary>
/// Emit the IL for the compilation into the specified stream.
/// </summary>
/// <param name="compilation">Compilation.</param>
/// <param name="outputPath">Path of the file to which the PE image will be written.</param>
/// <param name="pdbPath">Path of the file to which the compilation's debug info will be written.
/// Also embedded in the output file. Null to forego PDB generation.
/// </param>
/// <param name="xmlDocumentationPath">Path of the file to which the compilation's XML documentation will be written. Null to forego XML generation.</param>
/// <param name="win32ResourcesPath">Path of the file from which the compilation's Win32 resources will be read (in RES format).
/// Null to indicate that there are none.</param>
/// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param>
/// <param name="cancellationToken">To cancel the emit process.</param>
/// <exception cref="ArgumentNullException">Compilation or path is null.</exception>
/// <exception cref="ArgumentException">Path is empty or invalid.</exception>
/// <exception cref="IOException">An error occurred while reading or writing a file.</exception>
public static EmitResult Emit(
this CSharpCompilation compilation,
string outputPath,
string? pdbPath = null,
string? xmlDocumentationPath = null,
string? win32ResourcesPath = null,
IEnumerable<ResourceDescription>? manifestResources = null,
CancellationToken cancellationToken = default)
{
return FileSystemExtensions.Emit(compilation, outputPath, pdbPath, xmlDocumentationPath, win32ResourcesPath, manifestResources, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/TypeVariablesExpansion.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.Diagnostics;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class TypeVariablesExpansion : Expansion
{
private readonly Type[] _typeParameters;
private readonly Type[] _typeArguments;
private readonly CustomTypeInfoTypeArgumentMap _customTypeInfoMap;
internal TypeVariablesExpansion(TypeAndCustomInfo declaredTypeAndInfo)
{
var declaredType = declaredTypeAndInfo.Type;
Debug.Assert(declaredType.IsGenericType);
Debug.Assert(!declaredType.IsGenericTypeDefinition);
_customTypeInfoMap = CustomTypeInfoTypeArgumentMap.Create(declaredTypeAndInfo);
var typeDef = declaredType.GetGenericTypeDefinition();
_typeParameters = typeDef.GetGenericArguments();
_typeArguments = declaredType.GetGenericArguments();
Debug.Assert(_typeParameters.Length == _typeArguments.Length);
Debug.Assert(Array.TrueForAll(_typeParameters, t => t.IsGenericParameter));
Debug.Assert(Array.TrueForAll(_typeArguments, t => !t.IsGenericParameter));
}
internal override void GetRows(
ResultProvider resultProvider,
ArrayBuilder<EvalResult> rows,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
DkmClrValue value,
int startIndex,
int count,
bool visitAll,
ref int index)
{
int startIndex2;
int count2;
GetIntersection(startIndex, count, index, _typeArguments.Length, out startIndex2, out count2);
int offset = startIndex2 - index;
for (int i = 0; i < count2; i++)
{
rows.Add(GetRow(inspectionContext, value, i + offset, parent));
}
index += _typeArguments.Length;
}
private EvalResult GetRow(
DkmInspectionContext inspectionContext,
DkmClrValue value,
int index,
EvalResultDataItem parent)
{
var typeParameter = _typeParameters[index];
var typeArgument = _typeArguments[index];
var typeArgumentInfo = _customTypeInfoMap.SubstituteCustomTypeInfo(typeParameter, customInfo: null);
var formatSpecifiers = Formatter.NoFormatSpecifiers;
return new EvalResult(
ExpansionKind.TypeVariable,
typeParameter.Name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: new TypeAndCustomInfo(DkmClrType.Create(value.Type.AppDomain, typeArgument), typeArgumentInfo),
useDebuggerDisplay: parent != null,
value: value,
displayValue: inspectionContext.GetTypeName(DkmClrType.Create(value.Type.AppDomain, typeArgument), typeArgumentInfo, formatSpecifiers),
expansion: null,
childShouldParenthesize: false,
fullName: null,
childFullNamePrefixOpt: null,
formatSpecifiers: formatSpecifiers,
category: DkmEvaluationResultCategory.Data,
flags: DkmEvaluationResultFlags.ReadOnly,
editableValue: null,
inspectionContext: inspectionContext);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class TypeVariablesExpansion : Expansion
{
private readonly Type[] _typeParameters;
private readonly Type[] _typeArguments;
private readonly CustomTypeInfoTypeArgumentMap _customTypeInfoMap;
internal TypeVariablesExpansion(TypeAndCustomInfo declaredTypeAndInfo)
{
var declaredType = declaredTypeAndInfo.Type;
Debug.Assert(declaredType.IsGenericType);
Debug.Assert(!declaredType.IsGenericTypeDefinition);
_customTypeInfoMap = CustomTypeInfoTypeArgumentMap.Create(declaredTypeAndInfo);
var typeDef = declaredType.GetGenericTypeDefinition();
_typeParameters = typeDef.GetGenericArguments();
_typeArguments = declaredType.GetGenericArguments();
Debug.Assert(_typeParameters.Length == _typeArguments.Length);
Debug.Assert(Array.TrueForAll(_typeParameters, t => t.IsGenericParameter));
Debug.Assert(Array.TrueForAll(_typeArguments, t => !t.IsGenericParameter));
}
internal override void GetRows(
ResultProvider resultProvider,
ArrayBuilder<EvalResult> rows,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
DkmClrValue value,
int startIndex,
int count,
bool visitAll,
ref int index)
{
int startIndex2;
int count2;
GetIntersection(startIndex, count, index, _typeArguments.Length, out startIndex2, out count2);
int offset = startIndex2 - index;
for (int i = 0; i < count2; i++)
{
rows.Add(GetRow(inspectionContext, value, i + offset, parent));
}
index += _typeArguments.Length;
}
private EvalResult GetRow(
DkmInspectionContext inspectionContext,
DkmClrValue value,
int index,
EvalResultDataItem parent)
{
var typeParameter = _typeParameters[index];
var typeArgument = _typeArguments[index];
var typeArgumentInfo = _customTypeInfoMap.SubstituteCustomTypeInfo(typeParameter, customInfo: null);
var formatSpecifiers = Formatter.NoFormatSpecifiers;
return new EvalResult(
ExpansionKind.TypeVariable,
typeParameter.Name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: new TypeAndCustomInfo(DkmClrType.Create(value.Type.AppDomain, typeArgument), typeArgumentInfo),
useDebuggerDisplay: parent != null,
value: value,
displayValue: inspectionContext.GetTypeName(DkmClrType.Create(value.Type.AppDomain, typeArgument), typeArgumentInfo, formatSpecifiers),
expansion: null,
childShouldParenthesize: false,
fullName: null,
childFullNamePrefixOpt: null,
formatSpecifiers: formatSpecifiers,
category: DkmEvaluationResultCategory.Data,
flags: DkmEvaluationResultFlags.ReadOnly,
editableValue: null,
inspectionContext: inspectionContext);
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Compilers/Core/MSBuildTask/Utilities.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.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// General utilities.
/// </summary>
internal static class Utilities
{
private const string MSBuildRoslynFolderName = "Roslyn";
/// <summary>
/// Copied from msbuild. ItemSpecs are normalized using this method.
/// </summary>
public static string FixFilePath(string path)
=> string.IsNullOrEmpty(path) || Path.DirectorySeparatorChar == '\\' ? path : path.Replace('\\', '/');
/// <summary>
/// Convert a task item metadata to bool. Throw an exception if the string is badly formed and can't
/// be converted.
///
/// If the metadata is not found, then set metadataFound to false and then return false.
/// </summary>
/// <param name="item">The item that contains the metadata.</param>
/// <param name="itemMetadataName">The name of the metadata.</param>
/// <returns>The resulting boolean value.</returns>
internal static bool TryConvertItemMetadataToBool(ITaskItem item, string itemMetadataName)
{
string metadataValue = item.GetMetadata(itemMetadataName);
if (metadataValue == null || metadataValue.Length == 0)
{
return false;
}
try
{
return ConvertStringToBool(metadataValue);
}
catch (System.ArgumentException e)
{
throw Utilities.GetLocalizedArgumentException(
e,
ErrorString.General_InvalidAttributeMetadata,
item.ItemSpec, itemMetadataName, metadataValue, "bool");
}
}
/// <summary>
/// Converts a string to a bool. We consider "true/false", "on/off", and
/// "yes/no" to be valid boolean representations in the XML.
/// </summary>
/// <param name="parameterValue">The string to convert.</param>
/// <returns>Boolean true or false, corresponding to the string.</returns>
internal static bool ConvertStringToBool(string parameterValue)
{
if (ValidBooleanTrue(parameterValue))
{
return true;
}
else if (ValidBooleanFalse(parameterValue))
{
return false;
}
else
{
// Unsupported boolean representation.
throw Utilities.GetLocalizedArgumentException(
ErrorString.General_CannotConvertStringToBool,
parameterValue);
}
}
/// <summary>
/// Returns true if the string can be successfully converted to a bool,
/// such as "on" or "yes"
/// </summary>
internal static bool CanConvertStringToBool(string parameterValue) =>
ValidBooleanTrue(parameterValue) || ValidBooleanFalse(parameterValue);
/// <summary>
/// Returns true if the string represents a valid MSBuild boolean true value,
/// such as "on", "!false", "yes"
/// </summary>
private static bool ValidBooleanTrue(string parameterValue) =>
String.Compare(parameterValue, "true", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "on", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "yes", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!false", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!off", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!no", StringComparison.OrdinalIgnoreCase) == 0;
/// <summary>
/// Returns true if the string represents a valid MSBuild boolean false value,
/// such as "!on" "off" "no" "!true"
/// </summary>
private static bool ValidBooleanFalse(string parameterValue) =>
String.Compare(parameterValue, "false", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "off", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "no", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!true", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!on", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!yes", StringComparison.OrdinalIgnoreCase) == 0;
internal static string GetFullPathNoThrow(string path)
{
try
{
path = Path.GetFullPath(path);
}
catch (Exception e) when (IsIoRelatedException(e)) { }
return path;
}
internal static void DeleteNoThrow(string path)
{
try
{
File.Delete(path);
}
catch (Exception e) when (IsIoRelatedException(e)) { }
}
internal static bool IsIoRelatedException(Exception e) =>
e is UnauthorizedAccessException ||
e is NotSupportedException ||
(e is ArgumentException && !(e is ArgumentNullException)) ||
e is SecurityException ||
e is IOException;
internal static Exception GetLocalizedArgumentException(Exception e,
string errorString,
params object[] args)
{
return new ArgumentException(string.Format(CultureInfo.CurrentCulture, errorString, args), e);
}
internal static Exception GetLocalizedArgumentException(string errorString,
params object[] args)
{
return new ArgumentException(string.Format(CultureInfo.CurrentCulture, errorString, args));
}
internal static string? TryGetAssemblyPath(Assembly assembly)
{
if (assembly.GlobalAssemblyCache)
{
return null;
}
if (assembly.CodeBase is { } codebase)
{
var uri = new Uri(codebase);
return uri.IsFile ? uri.LocalPath : assembly.Location;
}
return null;
}
/// <summary>
/// Generate the full path to the tool that is deployed with our build tasks.
/// </summary>
internal static string GenerateFullPathToTool(string toolName)
{
var buildTask = typeof(Utilities).GetTypeInfo().Assembly;
var assemblyPath = buildTask.Location;
var assemblyDirectory = Path.GetDirectoryName(assemblyPath);
return RuntimeHostInfo.IsDesktopRuntime
? Path.Combine(assemblyDirectory!, toolName)
: Path.Combine(assemblyDirectory!, "bincore", toolName);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// General utilities.
/// </summary>
internal static class Utilities
{
private const string MSBuildRoslynFolderName = "Roslyn";
/// <summary>
/// Copied from msbuild. ItemSpecs are normalized using this method.
/// </summary>
public static string FixFilePath(string path)
=> string.IsNullOrEmpty(path) || Path.DirectorySeparatorChar == '\\' ? path : path.Replace('\\', '/');
/// <summary>
/// Convert a task item metadata to bool. Throw an exception if the string is badly formed and can't
/// be converted.
///
/// If the metadata is not found, then set metadataFound to false and then return false.
/// </summary>
/// <param name="item">The item that contains the metadata.</param>
/// <param name="itemMetadataName">The name of the metadata.</param>
/// <returns>The resulting boolean value.</returns>
internal static bool TryConvertItemMetadataToBool(ITaskItem item, string itemMetadataName)
{
string metadataValue = item.GetMetadata(itemMetadataName);
if (metadataValue == null || metadataValue.Length == 0)
{
return false;
}
try
{
return ConvertStringToBool(metadataValue);
}
catch (System.ArgumentException e)
{
throw Utilities.GetLocalizedArgumentException(
e,
ErrorString.General_InvalidAttributeMetadata,
item.ItemSpec, itemMetadataName, metadataValue, "bool");
}
}
/// <summary>
/// Converts a string to a bool. We consider "true/false", "on/off", and
/// "yes/no" to be valid boolean representations in the XML.
/// </summary>
/// <param name="parameterValue">The string to convert.</param>
/// <returns>Boolean true or false, corresponding to the string.</returns>
internal static bool ConvertStringToBool(string parameterValue)
{
if (ValidBooleanTrue(parameterValue))
{
return true;
}
else if (ValidBooleanFalse(parameterValue))
{
return false;
}
else
{
// Unsupported boolean representation.
throw Utilities.GetLocalizedArgumentException(
ErrorString.General_CannotConvertStringToBool,
parameterValue);
}
}
/// <summary>
/// Returns true if the string can be successfully converted to a bool,
/// such as "on" or "yes"
/// </summary>
internal static bool CanConvertStringToBool(string parameterValue) =>
ValidBooleanTrue(parameterValue) || ValidBooleanFalse(parameterValue);
/// <summary>
/// Returns true if the string represents a valid MSBuild boolean true value,
/// such as "on", "!false", "yes"
/// </summary>
private static bool ValidBooleanTrue(string parameterValue) =>
String.Compare(parameterValue, "true", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "on", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "yes", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!false", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!off", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!no", StringComparison.OrdinalIgnoreCase) == 0;
/// <summary>
/// Returns true if the string represents a valid MSBuild boolean false value,
/// such as "!on" "off" "no" "!true"
/// </summary>
private static bool ValidBooleanFalse(string parameterValue) =>
String.Compare(parameterValue, "false", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "off", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "no", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!true", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!on", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(parameterValue, "!yes", StringComparison.OrdinalIgnoreCase) == 0;
internal static string GetFullPathNoThrow(string path)
{
try
{
path = Path.GetFullPath(path);
}
catch (Exception e) when (IsIoRelatedException(e)) { }
return path;
}
internal static void DeleteNoThrow(string path)
{
try
{
File.Delete(path);
}
catch (Exception e) when (IsIoRelatedException(e)) { }
}
internal static bool IsIoRelatedException(Exception e) =>
e is UnauthorizedAccessException ||
e is NotSupportedException ||
(e is ArgumentException && !(e is ArgumentNullException)) ||
e is SecurityException ||
e is IOException;
internal static Exception GetLocalizedArgumentException(Exception e,
string errorString,
params object[] args)
{
return new ArgumentException(string.Format(CultureInfo.CurrentCulture, errorString, args), e);
}
internal static Exception GetLocalizedArgumentException(string errorString,
params object[] args)
{
return new ArgumentException(string.Format(CultureInfo.CurrentCulture, errorString, args));
}
internal static string? TryGetAssemblyPath(Assembly assembly)
{
if (assembly.GlobalAssemblyCache)
{
return null;
}
if (assembly.CodeBase is { } codebase)
{
var uri = new Uri(codebase);
return uri.IsFile ? uri.LocalPath : assembly.Location;
}
return null;
}
/// <summary>
/// Generate the full path to the tool that is deployed with our build tasks.
/// </summary>
internal static string GenerateFullPathToTool(string toolName)
{
var buildTask = typeof(Utilities).GetTypeInfo().Assembly;
var assemblyPath = buildTask.Location;
var assemblyDirectory = Path.GetDirectoryName(assemblyPath);
return RuntimeHostInfo.IsDesktopRuntime
? Path.Combine(assemblyDirectory!, toolName)
: Path.Combine(assemblyDirectory!, "bincore", toolName);
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker_ResolveReferences.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.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
public partial class MSBuildProjectLoader
{
private partial class Worker
{
private readonly struct ResolvedReferences
{
public ImmutableHashSet<ProjectReference> ProjectReferences { get; }
public ImmutableArray<MetadataReference> MetadataReferences { get; }
public ResolvedReferences(ImmutableHashSet<ProjectReference> projectReferences, ImmutableArray<MetadataReference> metadataReferences)
{
ProjectReferences = projectReferences;
MetadataReferences = metadataReferences;
}
}
/// <summary>
/// This type helps produces lists of metadata and project references. Initially, it contains a list of metadata references.
/// As project references are added, the metadata references that match those project references are removed.
/// </summary>
private class ResolvedReferencesBuilder
{
/// <summary>
/// The full list of <see cref="MetadataReference"/>s.
/// </summary>
private readonly ImmutableArray<MetadataReference> _metadataReferences;
/// <summary>
/// A map of every metadata reference file paths to a set of indices whether than file path
/// exists in the list. It is expected that there may be multiple metadata references for the
/// same file path in the case where multiple extern aliases are provided.
/// </summary>
private readonly ImmutableDictionary<string, HashSet<int>> _pathToIndicesMap;
/// <summary>
/// A set of indeces into <see cref="_metadataReferences"/> that are to be removed.
/// </summary>
private readonly HashSet<int> _indicesToRemove;
private readonly ImmutableHashSet<ProjectReference>.Builder _projectReferences;
public ResolvedReferencesBuilder(IEnumerable<MetadataReference> metadataReferences)
{
_metadataReferences = metadataReferences.ToImmutableArray();
_pathToIndicesMap = CreatePathToIndexMap(_metadataReferences);
_indicesToRemove = new HashSet<int>();
_projectReferences = ImmutableHashSet.CreateBuilder<ProjectReference>();
}
private static ImmutableDictionary<string, HashSet<int>> CreatePathToIndexMap(ImmutableArray<MetadataReference> metadataReferences)
{
var builder = ImmutableDictionary.CreateBuilder<string, HashSet<int>>(PathUtilities.Comparer);
for (var index = 0; index < metadataReferences.Length; index++)
{
var filePath = GetFilePath(metadataReferences[index]);
if (filePath != null)
{
builder.MultiAdd(filePath, index);
}
}
return builder.ToImmutable();
}
private static string? GetFilePath(MetadataReference metadataReference)
{
return metadataReference switch
{
PortableExecutableReference portableExecutableReference => portableExecutableReference.FilePath,
UnresolvedMetadataReference unresolvedMetadataReference => unresolvedMetadataReference.Reference,
_ => null,
};
}
public void AddProjectReference(ProjectReference projectReference)
{
_projectReferences.Add(projectReference);
}
public void SwapMetadataReferenceForProjectReference(ProjectReference projectReference, params string?[] possibleMetadataReferencePaths)
{
foreach (var path in possibleMetadataReferencePaths)
{
if (path != null)
{
Remove(path);
}
}
AddProjectReference(projectReference);
}
/// <summary>
/// Returns true if a metadata reference with the given file path is contained within this list.
/// </summary>
public bool Contains(string? filePath)
=> filePath != null
&& _pathToIndicesMap.ContainsKey(filePath);
/// <summary>
/// Removes the metadata reference with the given file path from this list.
/// </summary>
public void Remove(string filePath)
{
if (filePath != null && _pathToIndicesMap.TryGetValue(filePath, out var indices))
{
_indicesToRemove.AddRange(indices);
}
}
public ProjectInfo? SelectProjectInfoByOutput(IEnumerable<ProjectInfo> projectInfos)
{
foreach (var projectInfo in projectInfos)
{
var outputFilePath = projectInfo.OutputFilePath;
var outputRefFilePath = projectInfo.OutputRefFilePath;
if (outputFilePath != null &&
outputRefFilePath != null &&
(Contains(outputFilePath) || Contains(outputRefFilePath)))
{
return projectInfo;
}
}
return null;
}
public ImmutableArray<UnresolvedMetadataReference> GetUnresolvedMetadataReferences()
{
var builder = ImmutableArray.CreateBuilder<UnresolvedMetadataReference>();
foreach (var metadataReference in GetMetadataReferences())
{
if (metadataReference is UnresolvedMetadataReference unresolvedMetadataReference)
{
builder.Add(unresolvedMetadataReference);
}
}
return builder.ToImmutable();
}
private ImmutableArray<MetadataReference> GetMetadataReferences()
{
var builder = ImmutableArray.CreateBuilder<MetadataReference>();
// used to eliminate duplicates
var _ = PooledHashSet<MetadataReference>.GetInstance(out var set);
for (var index = 0; index < _metadataReferences.Length; index++)
{
var reference = _metadataReferences[index];
if (!_indicesToRemove.Contains(index) && set.Add(reference))
{
builder.Add(reference);
}
}
return builder.ToImmutable();
}
private ImmutableHashSet<ProjectReference> GetProjectReferences()
=> _projectReferences.ToImmutable();
public ResolvedReferences ToResolvedReferences()
=> new(GetProjectReferences(), GetMetadataReferences());
}
private async Task<ResolvedReferences> ResolveReferencesAsync(ProjectId id, ProjectFileInfo projectFileInfo, CommandLineArguments commandLineArgs, CancellationToken cancellationToken)
{
// First, gather all of the metadata references from the command-line arguments.
var resolvedMetadataReferences = commandLineArgs.ResolveMetadataReferences(
new WorkspaceMetadataFileReferenceResolver(
metadataService: GetWorkspaceService<IMetadataService>(),
pathResolver: new RelativePathResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory)));
var builder = new ResolvedReferencesBuilder(resolvedMetadataReferences);
var projectDirectory = Path.GetDirectoryName(projectFileInfo.FilePath);
RoslynDebug.AssertNotNull(projectDirectory);
// Next, iterate through all project references in the file and create project references.
foreach (var projectFileReference in projectFileInfo.ProjectReferences)
{
var aliases = projectFileReference.Aliases;
if (_pathResolver.TryGetAbsoluteProjectPath(projectFileReference.Path, baseDirectory: projectDirectory, _discoveredProjectOptions.OnPathFailure, out var projectReferencePath))
{
// The easiest case is to add a reference to a project we already know about.
if (TryAddReferenceToKnownProject(id, projectReferencePath, aliases, builder))
{
continue;
}
// If we don't know how to load a project (that is, it's not a language we support), we can still
// attempt to verify that its output exists on disk and is included in our set of metadata references.
// If it is, we'll just leave it in place.
if (!IsProjectLoadable(projectReferencePath) &&
await VerifyUnloadableProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false))
{
continue;
}
// If metadata is preferred, see if the project reference's output exists on disk and is included
// in our metadata references. If it is, don't create a project reference; we'll just use the metadata.
if (_preferMetadataForReferencesOfDiscoveredProjects &&
await VerifyProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false))
{
continue;
}
// Finally, we'll try to load and reference the project.
if (await TryLoadAndAddReferenceAsync(id, projectReferencePath, aliases, builder, cancellationToken).ConfigureAwait(false))
{
continue;
}
}
// We weren't able to handle this project reference, so add it without further processing.
var unknownProjectId = _projectMap.GetOrCreateProjectId(projectFileReference.Path);
var newProjectReference = CreateProjectReference(from: id, to: unknownProjectId, aliases);
builder.AddProjectReference(newProjectReference);
}
// Are there still any unresolved metadata references? If so, remove them and report diagnostics.
foreach (var unresolvedMetadataReference in builder.GetUnresolvedMetadataReferences())
{
var filePath = unresolvedMetadataReference.Reference;
builder.Remove(filePath);
_diagnosticReporter.Report(new ProjectDiagnostic(
WorkspaceDiagnosticKind.Warning,
string.Format(WorkspaceMSBuildResources.Unresolved_metadata_reference_removed_from_project_0, filePath),
id));
}
return builder.ToResolvedReferences();
}
private async Task<bool> TryLoadAndAddReferenceAsync(ProjectId id, string projectReferencePath, ImmutableArray<string> aliases, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
{
var projectReferenceInfos = await LoadProjectInfosFromPathAsync(projectReferencePath, _discoveredProjectOptions, cancellationToken).ConfigureAwait(false);
if (projectReferenceInfos.IsEmpty)
{
return false;
}
// Find the project reference info whose output we have a metadata reference for.
ProjectInfo? projectReferenceInfo = null;
foreach (var info in projectReferenceInfos)
{
var outputFilePath = info.OutputFilePath;
var outputRefFilePath = info.OutputRefFilePath;
if (outputFilePath != null &&
outputRefFilePath != null &&
(builder.Contains(outputFilePath) || builder.Contains(outputRefFilePath)))
{
projectReferenceInfo = info;
break;
}
}
if (projectReferenceInfo is null)
{
// We didn't find the project reference info that matches any of our metadata references.
// In this case, we'll go ahead and use the first project reference info that was found,
// but report a warning because this likely means that either a metadata reference path
// or a project output path is incorrect.
projectReferenceInfo = projectReferenceInfos[0];
_diagnosticReporter.Report(new ProjectDiagnostic(
WorkspaceDiagnosticKind.Warning,
string.Format(WorkspaceMSBuildResources.Found_project_reference_without_a_matching_metadata_reference_0, projectReferencePath),
id));
}
if (!ProjectReferenceExists(to: id, from: projectReferenceInfo))
{
var newProjectReference = CreateProjectReference(from: id, to: projectReferenceInfo.Id, aliases);
builder.SwapMetadataReferenceForProjectReference(newProjectReference, projectReferenceInfo.OutputRefFilePath, projectReferenceInfo.OutputFilePath);
}
else
{
// This project already has a reference on us. Don't introduce a circularity by referencing it.
// However, if the project's output doesn't exist on disk, we need to remove from our list of
// metadata references to avoid failures later. Essentially, the concern here is that the metadata
// reference is an UnresolvedMetadataReference, which will throw when we try to create a
// Compilation with it.
var outputRefFilePath = projectReferenceInfo.OutputRefFilePath;
if (outputRefFilePath != null && !File.Exists(outputRefFilePath))
{
builder.Remove(outputRefFilePath);
}
var outputFilePath = projectReferenceInfo.OutputFilePath;
if (outputFilePath != null && !File.Exists(outputFilePath))
{
builder.Remove(outputFilePath);
}
}
// Note that we return true even if we don't actually add a reference due to a circularity because,
// in that case, we've still handled everything.
return true;
}
private bool IsProjectLoadable(string projectPath)
=> _projectFileLoaderRegistry.TryGetLoaderFromProjectPath(projectPath, DiagnosticReportingMode.Ignore, out _);
private async Task<bool> VerifyUnloadableProjectOutputExistsAsync(string projectPath, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
{
var outputFilePath = await _buildManager.TryGetOutputFilePathAsync(projectPath, cancellationToken).ConfigureAwait(false);
return outputFilePath != null
&& builder.Contains(outputFilePath)
&& File.Exists(outputFilePath);
}
private async Task<bool> VerifyProjectOutputExistsAsync(string projectPath, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
{
// Note: Load the project, but don't report failures.
var projectFileInfos = await LoadProjectFileInfosAsync(projectPath, DiagnosticReportingOptions.IgnoreAll, cancellationToken).ConfigureAwait(false);
foreach (var projectFileInfo in projectFileInfos)
{
var outputFilePath = projectFileInfo.OutputFilePath;
var outputRefFilePath = projectFileInfo.OutputRefFilePath;
if ((builder.Contains(outputFilePath) && File.Exists(outputFilePath)) ||
(builder.Contains(outputRefFilePath) && File.Exists(outputRefFilePath)))
{
return true;
}
}
return false;
}
private ProjectReference CreateProjectReference(ProjectId from, ProjectId to, ImmutableArray<string> aliases)
{
var newReference = new ProjectReference(to, aliases);
_projectIdToProjectReferencesMap.MultiAdd(from, newReference);
return newReference;
}
private bool ProjectReferenceExists(ProjectId to, ProjectId from)
=> _projectIdToProjectReferencesMap.TryGetValue(from, out var references)
&& references.Contains(pr => pr.ProjectId == to);
private static bool ProjectReferenceExists(ProjectId to, ProjectInfo from)
=> from.ProjectReferences.Any(pr => pr.ProjectId == to);
private bool TryAddReferenceToKnownProject(
ProjectId id,
string projectReferencePath,
ImmutableArray<string> aliases,
ResolvedReferencesBuilder builder)
{
if (_projectMap.TryGetIdsByProjectPath(projectReferencePath, out var projectReferenceIds))
{
foreach (var projectReferenceId in projectReferenceIds)
{
// Don't add a reference if the project already has a reference on us. Otherwise, it will cause a circularity.
if (ProjectReferenceExists(to: id, from: projectReferenceId))
{
return false;
}
var outputRefFilePath = _projectMap.GetOutputRefFilePathById(projectReferenceId);
var outputFilePath = _projectMap.GetOutputFilePathById(projectReferenceId);
if (builder.Contains(outputRefFilePath) ||
builder.Contains(outputFilePath))
{
var newProjectReference = CreateProjectReference(from: id, to: projectReferenceId, aliases);
builder.SwapMetadataReferenceForProjectReference(newProjectReference, outputRefFilePath, outputFilePath);
return true;
}
}
}
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
public partial class MSBuildProjectLoader
{
private partial class Worker
{
private readonly struct ResolvedReferences
{
public ImmutableHashSet<ProjectReference> ProjectReferences { get; }
public ImmutableArray<MetadataReference> MetadataReferences { get; }
public ResolvedReferences(ImmutableHashSet<ProjectReference> projectReferences, ImmutableArray<MetadataReference> metadataReferences)
{
ProjectReferences = projectReferences;
MetadataReferences = metadataReferences;
}
}
/// <summary>
/// This type helps produces lists of metadata and project references. Initially, it contains a list of metadata references.
/// As project references are added, the metadata references that match those project references are removed.
/// </summary>
private class ResolvedReferencesBuilder
{
/// <summary>
/// The full list of <see cref="MetadataReference"/>s.
/// </summary>
private readonly ImmutableArray<MetadataReference> _metadataReferences;
/// <summary>
/// A map of every metadata reference file paths to a set of indices whether than file path
/// exists in the list. It is expected that there may be multiple metadata references for the
/// same file path in the case where multiple extern aliases are provided.
/// </summary>
private readonly ImmutableDictionary<string, HashSet<int>> _pathToIndicesMap;
/// <summary>
/// A set of indeces into <see cref="_metadataReferences"/> that are to be removed.
/// </summary>
private readonly HashSet<int> _indicesToRemove;
private readonly ImmutableHashSet<ProjectReference>.Builder _projectReferences;
public ResolvedReferencesBuilder(IEnumerable<MetadataReference> metadataReferences)
{
_metadataReferences = metadataReferences.ToImmutableArray();
_pathToIndicesMap = CreatePathToIndexMap(_metadataReferences);
_indicesToRemove = new HashSet<int>();
_projectReferences = ImmutableHashSet.CreateBuilder<ProjectReference>();
}
private static ImmutableDictionary<string, HashSet<int>> CreatePathToIndexMap(ImmutableArray<MetadataReference> metadataReferences)
{
var builder = ImmutableDictionary.CreateBuilder<string, HashSet<int>>(PathUtilities.Comparer);
for (var index = 0; index < metadataReferences.Length; index++)
{
var filePath = GetFilePath(metadataReferences[index]);
if (filePath != null)
{
builder.MultiAdd(filePath, index);
}
}
return builder.ToImmutable();
}
private static string? GetFilePath(MetadataReference metadataReference)
{
return metadataReference switch
{
PortableExecutableReference portableExecutableReference => portableExecutableReference.FilePath,
UnresolvedMetadataReference unresolvedMetadataReference => unresolvedMetadataReference.Reference,
_ => null,
};
}
public void AddProjectReference(ProjectReference projectReference)
{
_projectReferences.Add(projectReference);
}
public void SwapMetadataReferenceForProjectReference(ProjectReference projectReference, params string?[] possibleMetadataReferencePaths)
{
foreach (var path in possibleMetadataReferencePaths)
{
if (path != null)
{
Remove(path);
}
}
AddProjectReference(projectReference);
}
/// <summary>
/// Returns true if a metadata reference with the given file path is contained within this list.
/// </summary>
public bool Contains(string? filePath)
=> filePath != null
&& _pathToIndicesMap.ContainsKey(filePath);
/// <summary>
/// Removes the metadata reference with the given file path from this list.
/// </summary>
public void Remove(string filePath)
{
if (filePath != null && _pathToIndicesMap.TryGetValue(filePath, out var indices))
{
_indicesToRemove.AddRange(indices);
}
}
public ProjectInfo? SelectProjectInfoByOutput(IEnumerable<ProjectInfo> projectInfos)
{
foreach (var projectInfo in projectInfos)
{
var outputFilePath = projectInfo.OutputFilePath;
var outputRefFilePath = projectInfo.OutputRefFilePath;
if (outputFilePath != null &&
outputRefFilePath != null &&
(Contains(outputFilePath) || Contains(outputRefFilePath)))
{
return projectInfo;
}
}
return null;
}
public ImmutableArray<UnresolvedMetadataReference> GetUnresolvedMetadataReferences()
{
var builder = ImmutableArray.CreateBuilder<UnresolvedMetadataReference>();
foreach (var metadataReference in GetMetadataReferences())
{
if (metadataReference is UnresolvedMetadataReference unresolvedMetadataReference)
{
builder.Add(unresolvedMetadataReference);
}
}
return builder.ToImmutable();
}
private ImmutableArray<MetadataReference> GetMetadataReferences()
{
var builder = ImmutableArray.CreateBuilder<MetadataReference>();
// used to eliminate duplicates
var _ = PooledHashSet<MetadataReference>.GetInstance(out var set);
for (var index = 0; index < _metadataReferences.Length; index++)
{
var reference = _metadataReferences[index];
if (!_indicesToRemove.Contains(index) && set.Add(reference))
{
builder.Add(reference);
}
}
return builder.ToImmutable();
}
private ImmutableHashSet<ProjectReference> GetProjectReferences()
=> _projectReferences.ToImmutable();
public ResolvedReferences ToResolvedReferences()
=> new(GetProjectReferences(), GetMetadataReferences());
}
private async Task<ResolvedReferences> ResolveReferencesAsync(ProjectId id, ProjectFileInfo projectFileInfo, CommandLineArguments commandLineArgs, CancellationToken cancellationToken)
{
// First, gather all of the metadata references from the command-line arguments.
var resolvedMetadataReferences = commandLineArgs.ResolveMetadataReferences(
new WorkspaceMetadataFileReferenceResolver(
metadataService: GetWorkspaceService<IMetadataService>(),
pathResolver: new RelativePathResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory)));
var builder = new ResolvedReferencesBuilder(resolvedMetadataReferences);
var projectDirectory = Path.GetDirectoryName(projectFileInfo.FilePath);
RoslynDebug.AssertNotNull(projectDirectory);
// Next, iterate through all project references in the file and create project references.
foreach (var projectFileReference in projectFileInfo.ProjectReferences)
{
var aliases = projectFileReference.Aliases;
if (_pathResolver.TryGetAbsoluteProjectPath(projectFileReference.Path, baseDirectory: projectDirectory, _discoveredProjectOptions.OnPathFailure, out var projectReferencePath))
{
// The easiest case is to add a reference to a project we already know about.
if (TryAddReferenceToKnownProject(id, projectReferencePath, aliases, builder))
{
continue;
}
// If we don't know how to load a project (that is, it's not a language we support), we can still
// attempt to verify that its output exists on disk and is included in our set of metadata references.
// If it is, we'll just leave it in place.
if (!IsProjectLoadable(projectReferencePath) &&
await VerifyUnloadableProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false))
{
continue;
}
// If metadata is preferred, see if the project reference's output exists on disk and is included
// in our metadata references. If it is, don't create a project reference; we'll just use the metadata.
if (_preferMetadataForReferencesOfDiscoveredProjects &&
await VerifyProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false))
{
continue;
}
// Finally, we'll try to load and reference the project.
if (await TryLoadAndAddReferenceAsync(id, projectReferencePath, aliases, builder, cancellationToken).ConfigureAwait(false))
{
continue;
}
}
// We weren't able to handle this project reference, so add it without further processing.
var unknownProjectId = _projectMap.GetOrCreateProjectId(projectFileReference.Path);
var newProjectReference = CreateProjectReference(from: id, to: unknownProjectId, aliases);
builder.AddProjectReference(newProjectReference);
}
// Are there still any unresolved metadata references? If so, remove them and report diagnostics.
foreach (var unresolvedMetadataReference in builder.GetUnresolvedMetadataReferences())
{
var filePath = unresolvedMetadataReference.Reference;
builder.Remove(filePath);
_diagnosticReporter.Report(new ProjectDiagnostic(
WorkspaceDiagnosticKind.Warning,
string.Format(WorkspaceMSBuildResources.Unresolved_metadata_reference_removed_from_project_0, filePath),
id));
}
return builder.ToResolvedReferences();
}
private async Task<bool> TryLoadAndAddReferenceAsync(ProjectId id, string projectReferencePath, ImmutableArray<string> aliases, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
{
var projectReferenceInfos = await LoadProjectInfosFromPathAsync(projectReferencePath, _discoveredProjectOptions, cancellationToken).ConfigureAwait(false);
if (projectReferenceInfos.IsEmpty)
{
return false;
}
// Find the project reference info whose output we have a metadata reference for.
ProjectInfo? projectReferenceInfo = null;
foreach (var info in projectReferenceInfos)
{
var outputFilePath = info.OutputFilePath;
var outputRefFilePath = info.OutputRefFilePath;
if (outputFilePath != null &&
outputRefFilePath != null &&
(builder.Contains(outputFilePath) || builder.Contains(outputRefFilePath)))
{
projectReferenceInfo = info;
break;
}
}
if (projectReferenceInfo is null)
{
// We didn't find the project reference info that matches any of our metadata references.
// In this case, we'll go ahead and use the first project reference info that was found,
// but report a warning because this likely means that either a metadata reference path
// or a project output path is incorrect.
projectReferenceInfo = projectReferenceInfos[0];
_diagnosticReporter.Report(new ProjectDiagnostic(
WorkspaceDiagnosticKind.Warning,
string.Format(WorkspaceMSBuildResources.Found_project_reference_without_a_matching_metadata_reference_0, projectReferencePath),
id));
}
if (!ProjectReferenceExists(to: id, from: projectReferenceInfo))
{
var newProjectReference = CreateProjectReference(from: id, to: projectReferenceInfo.Id, aliases);
builder.SwapMetadataReferenceForProjectReference(newProjectReference, projectReferenceInfo.OutputRefFilePath, projectReferenceInfo.OutputFilePath);
}
else
{
// This project already has a reference on us. Don't introduce a circularity by referencing it.
// However, if the project's output doesn't exist on disk, we need to remove from our list of
// metadata references to avoid failures later. Essentially, the concern here is that the metadata
// reference is an UnresolvedMetadataReference, which will throw when we try to create a
// Compilation with it.
var outputRefFilePath = projectReferenceInfo.OutputRefFilePath;
if (outputRefFilePath != null && !File.Exists(outputRefFilePath))
{
builder.Remove(outputRefFilePath);
}
var outputFilePath = projectReferenceInfo.OutputFilePath;
if (outputFilePath != null && !File.Exists(outputFilePath))
{
builder.Remove(outputFilePath);
}
}
// Note that we return true even if we don't actually add a reference due to a circularity because,
// in that case, we've still handled everything.
return true;
}
private bool IsProjectLoadable(string projectPath)
=> _projectFileLoaderRegistry.TryGetLoaderFromProjectPath(projectPath, DiagnosticReportingMode.Ignore, out _);
private async Task<bool> VerifyUnloadableProjectOutputExistsAsync(string projectPath, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
{
var outputFilePath = await _buildManager.TryGetOutputFilePathAsync(projectPath, cancellationToken).ConfigureAwait(false);
return outputFilePath != null
&& builder.Contains(outputFilePath)
&& File.Exists(outputFilePath);
}
private async Task<bool> VerifyProjectOutputExistsAsync(string projectPath, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
{
// Note: Load the project, but don't report failures.
var projectFileInfos = await LoadProjectFileInfosAsync(projectPath, DiagnosticReportingOptions.IgnoreAll, cancellationToken).ConfigureAwait(false);
foreach (var projectFileInfo in projectFileInfos)
{
var outputFilePath = projectFileInfo.OutputFilePath;
var outputRefFilePath = projectFileInfo.OutputRefFilePath;
if ((builder.Contains(outputFilePath) && File.Exists(outputFilePath)) ||
(builder.Contains(outputRefFilePath) && File.Exists(outputRefFilePath)))
{
return true;
}
}
return false;
}
private ProjectReference CreateProjectReference(ProjectId from, ProjectId to, ImmutableArray<string> aliases)
{
var newReference = new ProjectReference(to, aliases);
_projectIdToProjectReferencesMap.MultiAdd(from, newReference);
return newReference;
}
private bool ProjectReferenceExists(ProjectId to, ProjectId from)
=> _projectIdToProjectReferencesMap.TryGetValue(from, out var references)
&& references.Contains(pr => pr.ProjectId == to);
private static bool ProjectReferenceExists(ProjectId to, ProjectInfo from)
=> from.ProjectReferences.Any(pr => pr.ProjectId == to);
private bool TryAddReferenceToKnownProject(
ProjectId id,
string projectReferencePath,
ImmutableArray<string> aliases,
ResolvedReferencesBuilder builder)
{
if (_projectMap.TryGetIdsByProjectPath(projectReferencePath, out var projectReferenceIds))
{
foreach (var projectReferenceId in projectReferenceIds)
{
// Don't add a reference if the project already has a reference on us. Otherwise, it will cause a circularity.
if (ProjectReferenceExists(to: id, from: projectReferenceId))
{
return false;
}
var outputRefFilePath = _projectMap.GetOutputRefFilePathById(projectReferenceId);
var outputFilePath = _projectMap.GetOutputFilePathById(projectReferenceId);
if (builder.Contains(outputRefFilePath) ||
builder.Contains(outputFilePath))
{
var newProjectReference = CreateProjectReference(from: id, to: projectReferenceId, aliases);
builder.SwapMetadataReferenceForProjectReference(newProjectReference, outputRefFilePath, outputFilePath);
return true;
}
}
}
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/EditorFeatures/Core/Implementation/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractEditorInlineRenameService
{
private class FailureInlineRenameInfo : IInlineRenameInfo
{
public FailureInlineRenameInfo(string localizedErrorMessage)
=> this.LocalizedErrorMessage = localizedErrorMessage;
public bool CanRename => false;
public bool HasOverloads => false;
public bool ForceRenameOverloads => false;
public string LocalizedErrorMessage { get; }
public TextSpan TriggerSpan => default;
public string DisplayName => null;
public string FullDisplayName => null;
public Glyph Glyph => Glyph.None;
public ImmutableArray<DocumentSpan> DefinitionLocations => default;
public string GetFinalSymbolName(string replacementText) => null;
public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) => default;
public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) => null;
public Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) => Task.FromResult<IInlineRenameLocationSet>(null);
public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => false;
public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractEditorInlineRenameService
{
private class FailureInlineRenameInfo : IInlineRenameInfo
{
public FailureInlineRenameInfo(string localizedErrorMessage)
=> this.LocalizedErrorMessage = localizedErrorMessage;
public bool CanRename => false;
public bool HasOverloads => false;
public bool ForceRenameOverloads => false;
public string LocalizedErrorMessage { get; }
public TextSpan TriggerSpan => default;
public string DisplayName => null;
public string FullDisplayName => null;
public Glyph Glyph => Glyph.None;
public ImmutableArray<DocumentSpan> DefinitionLocations => default;
public string GetFinalSymbolName(string replacementText) => null;
public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) => default;
public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) => null;
public Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) => Task.FromResult<IInlineRenameLocationSet>(null);
public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => false;
public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => false;
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrDebuggerTypeProxyAttribute.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\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using Microsoft.VisualStudio.Debugger.Clr;
namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
{
public class DkmClrDebuggerTypeProxyAttribute : DkmClrEvalAttribute
{
internal DkmClrDebuggerTypeProxyAttribute(DkmClrType proxyType) :
base(null)
{
this.ProxyType = proxyType;
}
public readonly DkmClrType ProxyType;
}
}
| // Licensed to the .NET Foundation under one or more 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\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using Microsoft.VisualStudio.Debugger.Clr;
namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
{
public class DkmClrDebuggerTypeProxyAttribute : DkmClrEvalAttribute
{
internal DkmClrDebuggerTypeProxyAttribute(DkmClrType proxyType) :
base(null)
{
this.ProxyType = proxyType;
}
public readonly DkmClrType ProxyType;
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Compilers/Core/Portable/Operations/ArgumentKind.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.Operations
{
/// <summary>
/// Kinds of arguments.
/// </summary>
public enum ArgumentKind
{
/// <summary>
/// Represents unknown argument kind.
/// </summary>
None = 0x0,
/// <summary>
/// Argument value is explicitly supplied.
/// </summary>
Explicit = 0x1,
/// <summary>
/// Argument is a param array created by compilers for the matching C# params or VB ParamArray parameter.
/// Note, the value is a an array creation expression that encapsulates all the elements, if any.
/// </summary>
ParamArray = 0x2,
/// <summary>
/// Argument is a default value supplied automatically by the compilers.
/// </summary>
DefaultValue = 0x3
}
}
| // Licensed to the .NET Foundation under one or more 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.Operations
{
/// <summary>
/// Kinds of arguments.
/// </summary>
public enum ArgumentKind
{
/// <summary>
/// Represents unknown argument kind.
/// </summary>
None = 0x0,
/// <summary>
/// Argument value is explicitly supplied.
/// </summary>
Explicit = 0x1,
/// <summary>
/// Argument is a param array created by compilers for the matching C# params or VB ParamArray parameter.
/// Note, the value is a an array creation expression that encapsulates all the elements, if any.
/// </summary>
ParamArray = 0x2,
/// <summary>
/// Argument is a default value supplied automatically by the compilers.
/// </summary>
DefaultValue = 0x3
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Compilers/Core/Portable/ReferenceManager/AssemblyReferenceCandidate.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
{
internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol>
{
/// <summary>
/// Private helper class to capture information about AssemblySymbol instance we
/// should check for suitability. Used by the Bind method.
/// </summary>
private readonly struct AssemblyReferenceCandidate
{
/// <summary>
/// An index of the AssemblyData object in the input array. AssemblySymbol instance should
/// be checked for suitability against assembly described by that object, taking into account
/// assemblies described by other AssemblyData objects in the input array.
/// </summary>
public readonly int DefinitionIndex;
/// <summary>
/// AssemblySymbol instance to check for suitability.
/// </summary>
public readonly TAssemblySymbol? AssemblySymbol;
/// <summary>
/// Convenience constructor to initialize fields of this structure.
/// </summary>
public AssemblyReferenceCandidate(int definitionIndex, TAssemblySymbol symbol)
{
DefinitionIndex = definitionIndex;
AssemblySymbol = 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.
namespace Microsoft.CodeAnalysis
{
internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol>
{
/// <summary>
/// Private helper class to capture information about AssemblySymbol instance we
/// should check for suitability. Used by the Bind method.
/// </summary>
private readonly struct AssemblyReferenceCandidate
{
/// <summary>
/// An index of the AssemblyData object in the input array. AssemblySymbol instance should
/// be checked for suitability against assembly described by that object, taking into account
/// assemblies described by other AssemblyData objects in the input array.
/// </summary>
public readonly int DefinitionIndex;
/// <summary>
/// AssemblySymbol instance to check for suitability.
/// </summary>
public readonly TAssemblySymbol? AssemblySymbol;
/// <summary>
/// Convenience constructor to initialize fields of this structure.
/// </summary>
public AssemblyReferenceCandidate(int definitionIndex, TAssemblySymbol symbol)
{
DefinitionIndex = definitionIndex;
AssemblySymbol = symbol;
}
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IDynamicObjectCreationExpression.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.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IDynamicObjectCreationExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_DynamicArgument()
{
string source = @"
class C
{
public C(int i)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d)')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_MultipleApplicableSymbols()
{
string source = @"
class C
{
public C(int i)
{
}
public C(long i)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d)')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_MultipleArgumentsAndApplicableSymbols()
{
string source = @"
class C
{
public C(int i, char c)
{
}
public C(long i, char c)
{
}
void M(dynamic d)
{
char c = 'c';
var x = /*<bind>*/new C(d, c)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d, c)')
Arguments(2):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Char) (Syntax: 'c')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_ArgumentNames()
{
string source = @"
class C
{
public C(int i, char c)
{
}
public C(long i, char c)
{
}
void M(dynamic d, dynamic e)
{
var x = /*<bind>*/new C(i: d, c: e)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(i: d, c: e)')
Arguments(2):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e')
ArgumentNames(2):
""i""
""c""
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_ArgumentRefKinds()
{
string source = @"
class C
{
public C(ref object i, out int j, char c)
{
j = 0;
}
void M(object d, dynamic e)
{
int k;
var x = /*<bind>*/new C(ref d, out k, e)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(ref d, out k, e)')
Arguments(3):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd')
ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k')
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e')
ArgumentNames(0)
ArgumentRefKinds(3):
Ref
Out
None
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_Initializer()
{
string source = @"
class C
{
public int X;
public C(char c)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d) { X = 0 }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d) { X = 0 }')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 0 }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 0')
Left:
IFieldReferenceOperation: System.Int32 C.X (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_AllFields()
{
string source = @"
class C
{
public int X;
public C(ref int i, char c)
{
}
public C(ref int i, long c)
{
}
void M(dynamic d)
{
int i = 0;
var x = /*<bind>*/new C(ref i, c: d) { X = 0 }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(ref i ... ) { X = 0 }')
Arguments(2):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(2):
""null""
""c""
ArgumentRefKinds(2):
Ref
None
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 0 }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 0')
Left:
IFieldReferenceOperation: System.Int32 C.X (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_ErrorBadDynamicMethodArgLambda()
{
string source = @"
using System;
class C
{
static void Main()
{
dynamic y = null;
/*<bind>*/new C(delegate { }, y)/*</bind>*/;
}
public C(Action a, Action y)
{
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C, IsInvalid) (Syntax: 'new C(delegate { }, y)')
Arguments(2):
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// /*<bind>*/new C(delegate { }, y)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_OVerloadResolutionFailure()
{
string source = @"
class C
{
public C()
{
}
public C(int i, int j)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid) (Syntax: 'new C(d)')
Children(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.C(int, int)'
// var x = /*<bind>*/new C(d)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("j", "C.C(int, int)").WithLocation(14, 31)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DynamicObjectCreationFlow_01()
{
string source = @"
class C1
{
C1(int i) { }
/*<bind>*/void M(C1 c1, dynamic d)
{
c1 = new C1(d);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1(d);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1(d)')
Left:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1')
Right:
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d)')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DynamicObjectCreationFlow_02()
{
string source = @"
class C1
{
C1(int i) { }
/*<bind>*/void M(C1 c1, dynamic d, bool b)
{
c1 = new C1(d) { I1 = 1, I2 = b ? 2 : 3 };
}/*</bind>*/
int I1 { get; set; }
int I2 { get; set; }
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Value:
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'I1 = 1')
Left:
IPropertyReferenceOperation: System.Int32 C1.I1 { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'I1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'I2 = b ? 2 : 3')
Left:
IPropertyReferenceOperation: System.Int32 C1.I2 { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'I2')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? 2 : 3')
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1 ... ? 2 : 3 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1 ... b ? 2 : 3 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DynamicObjectCreationFlow_03()
{
string source = @"
using System.Collections;
using System.Collections.Generic;
class C1 : IEnumerable<int>
{
C1(int i) { }
/*<bind>*/void M(C1 c1, dynamic d, bool b)
{
c1 = new C1(d) { 1, b ? 2 : 3 };
}/*</bind>*/
public IEnumerator<int> GetEnumerator() => throw new System.NotImplementedException();
IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException();
public void Add(int i) { }
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Value:
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
IInvocationOperation ( void C1.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IInvocationOperation ( void C1.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? 2 : 3')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'b ? 2 : 3')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? 2 : 3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1 ... ? 2 : 3 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1 ... b ? 2 : 3 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IDynamicObjectCreationExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_DynamicArgument()
{
string source = @"
class C
{
public C(int i)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d)')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_MultipleApplicableSymbols()
{
string source = @"
class C
{
public C(int i)
{
}
public C(long i)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d)')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_MultipleArgumentsAndApplicableSymbols()
{
string source = @"
class C
{
public C(int i, char c)
{
}
public C(long i, char c)
{
}
void M(dynamic d)
{
char c = 'c';
var x = /*<bind>*/new C(d, c)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d, c)')
Arguments(2):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Char) (Syntax: 'c')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_ArgumentNames()
{
string source = @"
class C
{
public C(int i, char c)
{
}
public C(long i, char c)
{
}
void M(dynamic d, dynamic e)
{
var x = /*<bind>*/new C(i: d, c: e)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(i: d, c: e)')
Arguments(2):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e')
ArgumentNames(2):
""i""
""c""
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_ArgumentRefKinds()
{
string source = @"
class C
{
public C(ref object i, out int j, char c)
{
j = 0;
}
void M(object d, dynamic e)
{
int k;
var x = /*<bind>*/new C(ref d, out k, e)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(ref d, out k, e)')
Arguments(3):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd')
ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k')
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e')
ArgumentNames(0)
ArgumentRefKinds(3):
Ref
Out
None
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_Initializer()
{
string source = @"
class C
{
public int X;
public C(char c)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d) { X = 0 }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d) { X = 0 }')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 0 }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 0')
Left:
IFieldReferenceOperation: System.Int32 C.X (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_AllFields()
{
string source = @"
class C
{
public int X;
public C(ref int i, char c)
{
}
public C(ref int i, long c)
{
}
void M(dynamic d)
{
int i = 0;
var x = /*<bind>*/new C(ref i, c: d) { X = 0 }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(ref i ... ) { X = 0 }')
Arguments(2):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(2):
""null""
""c""
ArgumentRefKinds(2):
Ref
None
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 0 }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 0')
Left:
IFieldReferenceOperation: System.Int32 C.X (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_ErrorBadDynamicMethodArgLambda()
{
string source = @"
using System;
class C
{
static void Main()
{
dynamic y = null;
/*<bind>*/new C(delegate { }, y)/*</bind>*/;
}
public C(Action a, Action y)
{
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C, IsInvalid) (Syntax: 'new C(delegate { }, y)')
Arguments(2):
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// /*<bind>*/new C(delegate { }, y)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_OVerloadResolutionFailure()
{
string source = @"
class C
{
public C()
{
}
public C(int i, int j)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid) (Syntax: 'new C(d)')
Children(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.C(int, int)'
// var x = /*<bind>*/new C(d)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("j", "C.C(int, int)").WithLocation(14, 31)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DynamicObjectCreationFlow_01()
{
string source = @"
class C1
{
C1(int i) { }
/*<bind>*/void M(C1 c1, dynamic d)
{
c1 = new C1(d);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1(d);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1(d)')
Left:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1')
Right:
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d)')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DynamicObjectCreationFlow_02()
{
string source = @"
class C1
{
C1(int i) { }
/*<bind>*/void M(C1 c1, dynamic d, bool b)
{
c1 = new C1(d) { I1 = 1, I2 = b ? 2 : 3 };
}/*</bind>*/
int I1 { get; set; }
int I2 { get; set; }
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Value:
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'I1 = 1')
Left:
IPropertyReferenceOperation: System.Int32 C1.I1 { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'I1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'I2 = b ? 2 : 3')
Left:
IPropertyReferenceOperation: System.Int32 C1.I2 { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'I2')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? 2 : 3')
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1 ... ? 2 : 3 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1 ... b ? 2 : 3 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DynamicObjectCreationFlow_03()
{
string source = @"
using System.Collections;
using System.Collections.Generic;
class C1 : IEnumerable<int>
{
C1(int i) { }
/*<bind>*/void M(C1 c1, dynamic d, bool b)
{
c1 = new C1(d) { 1, b ? 2 : 3 };
}/*</bind>*/
public IEnumerator<int> GetEnumerator() => throw new System.NotImplementedException();
IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException();
public void Add(int i) { }
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Value:
IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Arguments(1):
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
IInvocationOperation ( void C1.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IInvocationOperation ( void C1.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? 2 : 3')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'b ? 2 : 3')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? 2 : 3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1 ... ? 2 : 3 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1 ... b ? 2 : 3 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/VisualStudio/CSharp/Impl/ProjectSystemShim/CSharpProjectShim.ICSharpProjectSite.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim
{
internal partial class CSharpProjectShim : ICSharpProjectSite
{
/// <summary>
/// When the project property page calls GetValidStartupClasses on us, it assumes
/// the strings passed to it are in the native C# language service's string table
/// and never frees them. To avoid leaking our strings, we allocate them on the
/// native heap for each call and keep the pointers here. On subsequent calls
/// or on disposal, we free the old strings before allocating the new ones.
/// </summary>
private IntPtr[] _startupClasses = null;
public void GetCompiler(out ICSCompiler compiler, out ICSInputSet inputSet)
{
compiler = this;
inputSet = this;
}
public bool CheckInputFileTimes(System.Runtime.InteropServices.ComTypes.FILETIME output)
=> throw new NotImplementedException();
public void BuildProject(object progress)
=> throw new NotImplementedException();
public void Unused()
=> throw new NotImplementedException();
public void OnSourceFileAdded(string filename)
{
// TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
//var sourceCodeKind = extension.Equals(".csx", StringComparison.OrdinalIgnoreCase)
// ? SourceCodeKind.Script
// : SourceCodeKind.Regular;
AddFile(filename, SourceCodeKind.Regular);
}
public void OnSourceFileRemoved(string filename)
=> RemoveFile(filename);
public int OnResourceFileAdded(string filename, string resourceName, bool embedded)
=> VSConstants.S_OK;
public int OnResourceFileRemoved(string filename)
=> VSConstants.S_OK;
public int OnImportAdded(string filename, string project)
{
// OnImportAdded is superseded by OnImportAddedEx. We maintain back-compat by treating
// it as a non-NoPIA reference.
return OnImportAddedEx(filename, project, CompilerOptions.OPTID_IMPORTS);
}
public int OnImportAddedEx(string filename, string project, CompilerOptions optionID)
{
if (optionID != CompilerOptions.OPTID_IMPORTS && optionID != CompilerOptions.OPTID_IMPORTSUSINGNOPIA)
{
throw new ArgumentException("optionID was an unexpected value.", nameof(optionID));
}
var embedInteropTypes = optionID == CompilerOptions.OPTID_IMPORTSUSINGNOPIA;
VisualStudioProject.AddMetadataReference(filename, new MetadataReferenceProperties(embedInteropTypes: embedInteropTypes));
return VSConstants.S_OK;
}
public void OnImportRemoved(string filename, string project)
{
filename = FileUtilities.NormalizeAbsolutePath(filename);
VisualStudioProject.RemoveMetadataReference(filename, VisualStudioProject.GetPropertiesForMetadataReference(filename).Single());
}
public void OnOutputFileChanged(string filename)
{
// We have nothing to do here
}
public void OnActiveConfigurationChanged(string configName)
{
// We have nothing to do here
}
public void OnProjectLoadCompletion()
{
// Despite the name, this is not necessarily called when the project has actually been
// completely loaded. If you plan on using this, be careful!
}
public int CreateCodeModel(object parent, out EnvDTE.CodeModel codeModel)
{
codeModel = ProjectCodeModel.GetOrCreateRootCodeModel((EnvDTE.Project)parent);
return VSConstants.S_OK;
}
public int CreateFileCodeModel(string fileName, object parent, out EnvDTE.FileCodeModel ppFileCodeModel)
{
ppFileCodeModel = ProjectCodeModel.GetOrCreateFileCodeModel(fileName, parent);
return VSConstants.S_OK;
}
public void OnModuleAdded(string filename)
=> throw new NotImplementedException();
public void OnModuleRemoved(string filename)
=> throw new NotImplementedException();
public int GetValidStartupClasses(IntPtr[] classNames, ref int count)
{
// If classNames is NULL, then we need to populate the number of valid startup
// classes only
var project = Workspace.CurrentSolution.GetProject(VisualStudioProject.Id);
var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var entryPoints = EntryPointFinder.FindEntryPoints(compilation.Assembly.GlobalNamespace);
if (classNames == null)
{
count = entryPoints.Count();
return VSConstants.S_OK;
}
else
{
// We return S_FALSE if we have more entrypoints than places in the array.
var entryPointNames = entryPoints.Select(e => e.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted))).ToArray();
if (entryPointNames.Length > classNames.Length)
{
return VSConstants.S_FALSE;
}
// The old language service stored startup class names in its string table,
// so the property page never freed them. To avoid leaking memory, we're
// going to allocate our strings on the native heap and keep the pointers to them.
// Subsequent calls to this function will free the old strings and allocate the
// new ones. The last set of marshalled strings is freed in the destructor.
if (_startupClasses != null)
{
foreach (var @class in _startupClasses)
{
Marshal.FreeHGlobal(@class);
}
}
_startupClasses = entryPointNames.Select(Marshal.StringToHGlobalUni).ToArray();
Array.Copy(_startupClasses, classNames, _startupClasses.Length);
count = entryPointNames.Length;
return VSConstants.S_OK;
}
}
public void OnAliasesChanged(string file, string project, int previousAliasesCount, string[] previousAliases, int currentAliasesCount, string[] currentAliases)
{
using (VisualStudioProject.CreateBatchScope())
{
var existingProperties = VisualStudioProject.GetPropertiesForMetadataReference(file).Single();
VisualStudioProject.RemoveMetadataReference(file, existingProperties);
VisualStudioProject.AddMetadataReference(file, existingProperties.WithAliases(currentAliases));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim
{
internal partial class CSharpProjectShim : ICSharpProjectSite
{
/// <summary>
/// When the project property page calls GetValidStartupClasses on us, it assumes
/// the strings passed to it are in the native C# language service's string table
/// and never frees them. To avoid leaking our strings, we allocate them on the
/// native heap for each call and keep the pointers here. On subsequent calls
/// or on disposal, we free the old strings before allocating the new ones.
/// </summary>
private IntPtr[] _startupClasses = null;
public void GetCompiler(out ICSCompiler compiler, out ICSInputSet inputSet)
{
compiler = this;
inputSet = this;
}
public bool CheckInputFileTimes(System.Runtime.InteropServices.ComTypes.FILETIME output)
=> throw new NotImplementedException();
public void BuildProject(object progress)
=> throw new NotImplementedException();
public void Unused()
=> throw new NotImplementedException();
public void OnSourceFileAdded(string filename)
{
// TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
//var sourceCodeKind = extension.Equals(".csx", StringComparison.OrdinalIgnoreCase)
// ? SourceCodeKind.Script
// : SourceCodeKind.Regular;
AddFile(filename, SourceCodeKind.Regular);
}
public void OnSourceFileRemoved(string filename)
=> RemoveFile(filename);
public int OnResourceFileAdded(string filename, string resourceName, bool embedded)
=> VSConstants.S_OK;
public int OnResourceFileRemoved(string filename)
=> VSConstants.S_OK;
public int OnImportAdded(string filename, string project)
{
// OnImportAdded is superseded by OnImportAddedEx. We maintain back-compat by treating
// it as a non-NoPIA reference.
return OnImportAddedEx(filename, project, CompilerOptions.OPTID_IMPORTS);
}
public int OnImportAddedEx(string filename, string project, CompilerOptions optionID)
{
if (optionID != CompilerOptions.OPTID_IMPORTS && optionID != CompilerOptions.OPTID_IMPORTSUSINGNOPIA)
{
throw new ArgumentException("optionID was an unexpected value.", nameof(optionID));
}
var embedInteropTypes = optionID == CompilerOptions.OPTID_IMPORTSUSINGNOPIA;
VisualStudioProject.AddMetadataReference(filename, new MetadataReferenceProperties(embedInteropTypes: embedInteropTypes));
return VSConstants.S_OK;
}
public void OnImportRemoved(string filename, string project)
{
filename = FileUtilities.NormalizeAbsolutePath(filename);
VisualStudioProject.RemoveMetadataReference(filename, VisualStudioProject.GetPropertiesForMetadataReference(filename).Single());
}
public void OnOutputFileChanged(string filename)
{
// We have nothing to do here
}
public void OnActiveConfigurationChanged(string configName)
{
// We have nothing to do here
}
public void OnProjectLoadCompletion()
{
// Despite the name, this is not necessarily called when the project has actually been
// completely loaded. If you plan on using this, be careful!
}
public int CreateCodeModel(object parent, out EnvDTE.CodeModel codeModel)
{
codeModel = ProjectCodeModel.GetOrCreateRootCodeModel((EnvDTE.Project)parent);
return VSConstants.S_OK;
}
public int CreateFileCodeModel(string fileName, object parent, out EnvDTE.FileCodeModel ppFileCodeModel)
{
ppFileCodeModel = ProjectCodeModel.GetOrCreateFileCodeModel(fileName, parent);
return VSConstants.S_OK;
}
public void OnModuleAdded(string filename)
=> throw new NotImplementedException();
public void OnModuleRemoved(string filename)
=> throw new NotImplementedException();
public int GetValidStartupClasses(IntPtr[] classNames, ref int count)
{
// If classNames is NULL, then we need to populate the number of valid startup
// classes only
var project = Workspace.CurrentSolution.GetProject(VisualStudioProject.Id);
var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var entryPoints = EntryPointFinder.FindEntryPoints(compilation.Assembly.GlobalNamespace);
if (classNames == null)
{
count = entryPoints.Count();
return VSConstants.S_OK;
}
else
{
// We return S_FALSE if we have more entrypoints than places in the array.
var entryPointNames = entryPoints.Select(e => e.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted))).ToArray();
if (entryPointNames.Length > classNames.Length)
{
return VSConstants.S_FALSE;
}
// The old language service stored startup class names in its string table,
// so the property page never freed them. To avoid leaking memory, we're
// going to allocate our strings on the native heap and keep the pointers to them.
// Subsequent calls to this function will free the old strings and allocate the
// new ones. The last set of marshalled strings is freed in the destructor.
if (_startupClasses != null)
{
foreach (var @class in _startupClasses)
{
Marshal.FreeHGlobal(@class);
}
}
_startupClasses = entryPointNames.Select(Marshal.StringToHGlobalUni).ToArray();
Array.Copy(_startupClasses, classNames, _startupClasses.Length);
count = entryPointNames.Length;
return VSConstants.S_OK;
}
}
public void OnAliasesChanged(string file, string project, int previousAliasesCount, string[] previousAliases, int currentAliasesCount, string[] currentAliases)
{
using (VisualStudioProject.CreateBatchScope())
{
var existingProperties = VisualStudioProject.GetPropertiesForMetadataReference(file).Single();
VisualStudioProject.RemoveMetadataReference(file, existingProperties);
VisualStudioProject.AddMetadataReference(file, existingProperties.WithAliases(currentAliases));
}
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Compilers/Core/MSBuildTask/IVbcHostObject6.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.Runtime.InteropServices;
using Microsoft.Build.Tasks.Hosting;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// Defines an interface that proffers a free threaded host object that
/// allows for background threads to call directly (avoids marshalling
/// to the UI thread.
/// </summary>
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComVisible(true)]
[Guid("10617623-DD4E-4E81-B4C3-46F55DC76E52")]
public interface IVbcHostObject6 : IVbcHostObject5
{
bool SetErrorLog(string? errorLogFile);
bool SetReportAnalyzer(bool reportAnalyzerInDiagnosticOutput);
}
}
| // Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices;
using Microsoft.Build.Tasks.Hosting;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// Defines an interface that proffers a free threaded host object that
/// allows for background threads to call directly (avoids marshalling
/// to the UI thread.
/// </summary>
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComVisible(true)]
[Guid("10617623-DD4E-4E81-B4C3-46F55DC76E52")]
public interface IVbcHostObject6 : IVbcHostObject5
{
bool SetErrorLog(string? errorLogFile);
bool SetReportAnalyzer(bool reportAnalyzerInDiagnosticOutput);
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Workspaces/Remote/Core/Serialization/RoslynJsonConverter.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.Concurrent;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Text;
using Newtonsoft.Json;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class AggregateJsonConverter : JsonConverter
{
public static readonly AggregateJsonConverter Instance = new AggregateJsonConverter();
private readonly ConcurrentDictionary<Type, JsonConverter> _map;
private AggregateJsonConverter()
=> _map = new ConcurrentDictionary<Type, JsonConverter>(CreateConverterMap());
public override bool CanConvert(Type objectType)
=> _map.ContainsKey(objectType);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
=> _map[objectType].ReadJson(reader, objectType, existingValue, serializer);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
=> _map[value.GetType()].WriteJson(writer, value, serializer);
// this type is shared by multiple teams such as Razor, LUT and etc which have either
// separated/shared/shim repo so some types might not available to those context. this
// partial method let us add Roslyn specific types without breaking them
partial void AppendRoslynSpecificJsonConverters(ImmutableDictionary<Type, JsonConverter>.Builder builder);
private ImmutableDictionary<Type, JsonConverter> CreateConverterMap()
{
var builder = ImmutableDictionary.CreateBuilder<Type, JsonConverter>();
Add(builder, new ChecksumJsonConverter());
Add(builder, new SolutionIdJsonConverter());
Add(builder, new ProjectIdJsonConverter());
Add(builder, new DocumentIdJsonConverter());
Add(builder, new TextSpanJsonConverter());
Add(builder, new TextChangeJsonConverter());
Add(builder, new SymbolKeyJsonConverter());
Add(builder, new PinnedSolutionInfoJsonConverter());
AppendRoslynSpecificJsonConverters(builder);
return builder.ToImmutable();
}
private static void Add<T>(
ImmutableDictionary<Type, JsonConverter>.Builder builder,
BaseJsonConverter<T> converter)
=> builder.Add(typeof(T), converter);
internal bool TryAdd(Type type, JsonConverter converter)
=> _map.TryAdd(type, converter);
private abstract class BaseJsonConverter<T> : JsonConverter
{
public sealed override bool CanConvert(Type objectType) => typeof(T) == objectType;
public sealed override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
=> ReadValue(reader, serializer);
public sealed override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
=> WriteValue(writer, (T)value, serializer);
protected abstract T ReadValue(JsonReader reader, JsonSerializer serializer);
protected abstract void WriteValue(JsonWriter writer, T value, JsonSerializer serializer);
protected static U ReadProperty<U>(JsonReader reader, JsonSerializer serializer)
{
// read property
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.PropertyName);
Contract.ThrowIfFalse(reader.Read());
return serializer.Deserialize<U>(reader);
}
protected static U ReadProperty<U>(JsonReader reader)
{
// read property
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.PropertyName);
Contract.ThrowIfFalse(reader.Read());
return (U)reader.Value;
}
}
private class TextSpanJsonConverter : BaseJsonConverter<TextSpan>
{
protected override TextSpan ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var start = ReadProperty<long>(reader);
var length = ReadProperty<long>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TextSpan((int)start, (int)length);
}
protected override void WriteValue(JsonWriter writer, TextSpan span, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(TextSpan.Start));
writer.WriteValue(span.Start);
writer.WritePropertyName(nameof(TextSpan.Length));
writer.WriteValue(span.Length);
writer.WriteEndObject();
}
}
private class TextChangeJsonConverter : BaseJsonConverter<TextChange>
{
protected override TextChange ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var start = ReadProperty<long>(reader);
var length = ReadProperty<long>(reader);
var newText = ReadProperty<string>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TextChange(new TextSpan((int)start, (int)length), newText);
}
protected override void WriteValue(JsonWriter writer, TextChange change, JsonSerializer serializer)
{
var span = change.Span;
writer.WriteStartObject();
writer.WritePropertyName(nameof(TextSpan.Start));
writer.WriteValue(span.Start);
writer.WritePropertyName(nameof(TextSpan.Length));
writer.WriteValue(span.Length);
writer.WritePropertyName(nameof(TextChange.NewText));
writer.WriteValue(change.NewText);
writer.WriteEndObject();
}
}
private class SymbolKeyJsonConverter : BaseJsonConverter<SymbolKey>
{
protected override SymbolKey ReadValue(JsonReader reader, JsonSerializer serializer)
=> new SymbolKey((string)reader.Value);
protected override void WriteValue(JsonWriter writer, SymbolKey value, JsonSerializer serializer)
=> writer.WriteValue(value.ToString());
}
private class ChecksumJsonConverter : BaseJsonConverter<Checksum>
{
protected override Checksum ReadValue(JsonReader reader, JsonSerializer serializer)
=> Checksum.FromBase64String((string)reader.Value);
protected override void WriteValue(JsonWriter writer, Checksum value, JsonSerializer serializer)
=> writer.WriteValue(value?.ToBase64String());
}
private class PinnedSolutionInfoJsonConverter : BaseJsonConverter<PinnedSolutionInfo>
{
protected override PinnedSolutionInfo ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var scopeId = ReadProperty<long>(reader);
var fromPrimaryBranch = ReadProperty<bool>(reader);
var workspaceVersion = ReadProperty<long>(reader);
var checksum = ReadProperty<Checksum>(reader, serializer);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new PinnedSolutionInfo((int)scopeId, fromPrimaryBranch, (int)workspaceVersion, checksum);
}
protected override void WriteValue(JsonWriter writer, PinnedSolutionInfo scope, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName("scopeId");
writer.WriteValue(scope.ScopeId);
writer.WritePropertyName("primary");
writer.WriteValue(scope.FromPrimaryBranch);
writer.WritePropertyName("version");
writer.WriteValue(scope.WorkspaceVersion);
writer.WritePropertyName("checksum");
serializer.Serialize(writer, scope.SolutionChecksum);
writer.WriteEndObject();
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Concurrent;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Text;
using Newtonsoft.Json;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class AggregateJsonConverter : JsonConverter
{
public static readonly AggregateJsonConverter Instance = new AggregateJsonConverter();
private readonly ConcurrentDictionary<Type, JsonConverter> _map;
private AggregateJsonConverter()
=> _map = new ConcurrentDictionary<Type, JsonConverter>(CreateConverterMap());
public override bool CanConvert(Type objectType)
=> _map.ContainsKey(objectType);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
=> _map[objectType].ReadJson(reader, objectType, existingValue, serializer);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
=> _map[value.GetType()].WriteJson(writer, value, serializer);
// this type is shared by multiple teams such as Razor, LUT and etc which have either
// separated/shared/shim repo so some types might not available to those context. this
// partial method let us add Roslyn specific types without breaking them
partial void AppendRoslynSpecificJsonConverters(ImmutableDictionary<Type, JsonConverter>.Builder builder);
private ImmutableDictionary<Type, JsonConverter> CreateConverterMap()
{
var builder = ImmutableDictionary.CreateBuilder<Type, JsonConverter>();
Add(builder, new ChecksumJsonConverter());
Add(builder, new SolutionIdJsonConverter());
Add(builder, new ProjectIdJsonConverter());
Add(builder, new DocumentIdJsonConverter());
Add(builder, new TextSpanJsonConverter());
Add(builder, new TextChangeJsonConverter());
Add(builder, new SymbolKeyJsonConverter());
Add(builder, new PinnedSolutionInfoJsonConverter());
AppendRoslynSpecificJsonConverters(builder);
return builder.ToImmutable();
}
private static void Add<T>(
ImmutableDictionary<Type, JsonConverter>.Builder builder,
BaseJsonConverter<T> converter)
=> builder.Add(typeof(T), converter);
internal bool TryAdd(Type type, JsonConverter converter)
=> _map.TryAdd(type, converter);
private abstract class BaseJsonConverter<T> : JsonConverter
{
public sealed override bool CanConvert(Type objectType) => typeof(T) == objectType;
public sealed override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
=> ReadValue(reader, serializer);
public sealed override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
=> WriteValue(writer, (T)value, serializer);
protected abstract T ReadValue(JsonReader reader, JsonSerializer serializer);
protected abstract void WriteValue(JsonWriter writer, T value, JsonSerializer serializer);
protected static U ReadProperty<U>(JsonReader reader, JsonSerializer serializer)
{
// read property
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.PropertyName);
Contract.ThrowIfFalse(reader.Read());
return serializer.Deserialize<U>(reader);
}
protected static U ReadProperty<U>(JsonReader reader)
{
// read property
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.PropertyName);
Contract.ThrowIfFalse(reader.Read());
return (U)reader.Value;
}
}
private class TextSpanJsonConverter : BaseJsonConverter<TextSpan>
{
protected override TextSpan ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var start = ReadProperty<long>(reader);
var length = ReadProperty<long>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TextSpan((int)start, (int)length);
}
protected override void WriteValue(JsonWriter writer, TextSpan span, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(TextSpan.Start));
writer.WriteValue(span.Start);
writer.WritePropertyName(nameof(TextSpan.Length));
writer.WriteValue(span.Length);
writer.WriteEndObject();
}
}
private class TextChangeJsonConverter : BaseJsonConverter<TextChange>
{
protected override TextChange ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var start = ReadProperty<long>(reader);
var length = ReadProperty<long>(reader);
var newText = ReadProperty<string>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TextChange(new TextSpan((int)start, (int)length), newText);
}
protected override void WriteValue(JsonWriter writer, TextChange change, JsonSerializer serializer)
{
var span = change.Span;
writer.WriteStartObject();
writer.WritePropertyName(nameof(TextSpan.Start));
writer.WriteValue(span.Start);
writer.WritePropertyName(nameof(TextSpan.Length));
writer.WriteValue(span.Length);
writer.WritePropertyName(nameof(TextChange.NewText));
writer.WriteValue(change.NewText);
writer.WriteEndObject();
}
}
private class SymbolKeyJsonConverter : BaseJsonConverter<SymbolKey>
{
protected override SymbolKey ReadValue(JsonReader reader, JsonSerializer serializer)
=> new SymbolKey((string)reader.Value);
protected override void WriteValue(JsonWriter writer, SymbolKey value, JsonSerializer serializer)
=> writer.WriteValue(value.ToString());
}
private class ChecksumJsonConverter : BaseJsonConverter<Checksum>
{
protected override Checksum ReadValue(JsonReader reader, JsonSerializer serializer)
=> Checksum.FromBase64String((string)reader.Value);
protected override void WriteValue(JsonWriter writer, Checksum value, JsonSerializer serializer)
=> writer.WriteValue(value?.ToBase64String());
}
private class PinnedSolutionInfoJsonConverter : BaseJsonConverter<PinnedSolutionInfo>
{
protected override PinnedSolutionInfo ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var scopeId = ReadProperty<long>(reader);
var fromPrimaryBranch = ReadProperty<bool>(reader);
var workspaceVersion = ReadProperty<long>(reader);
var checksum = ReadProperty<Checksum>(reader, serializer);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new PinnedSolutionInfo((int)scopeId, fromPrimaryBranch, (int)workspaceVersion, checksum);
}
protected override void WriteValue(JsonWriter writer, PinnedSolutionInfo scope, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName("scopeId");
writer.WriteValue(scope.ScopeId);
writer.WritePropertyName("primary");
writer.WriteValue(scope.FromPrimaryBranch);
writer.WritePropertyName("version");
writer.WriteValue(scope.WorkspaceVersion);
writer.WritePropertyName("checksum");
serializer.Serialize(writer, scope.SolutionChecksum);
writer.WriteEndObject();
}
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Compilers/CSharp/Portable/Symbols/PublicModel/RangeVariableSymbol.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;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class RangeVariableSymbol : Symbol, IRangeVariableSymbol
{
private readonly Symbols.RangeVariableSymbol _underlying;
public RangeVariableSymbol(Symbols.RangeVariableSymbol underlying)
{
Debug.Assert(underlying is object);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitRangeVariable(this);
}
protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitRangeVariable(this);
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class RangeVariableSymbol : Symbol, IRangeVariableSymbol
{
private readonly Symbols.RangeVariableSymbol _underlying;
public RangeVariableSymbol(Symbols.RangeVariableSymbol underlying)
{
Debug.Assert(underlying is object);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitRangeVariable(this);
}
protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitRangeVariable(this);
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/VisualStudio/IntegrationTest/TestUtilities/Input/SendKeys.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;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input
{
public class SendKeys : AbstractSendKeys
{
private readonly VisualStudioInstance _visualStudioInstance;
public SendKeys(VisualStudioInstance visualStudioInstance)
{
_visualStudioInstance = visualStudioInstance;
}
protected override void ActivateMainWindow()
{
_visualStudioInstance.ActivateMainWindow();
}
protected override void WaitForApplicationIdle(CancellationToken cancellationToken)
{
_visualStudioInstance.WaitForApplicationIdle(cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input
{
public class SendKeys : AbstractSendKeys
{
private readonly VisualStudioInstance _visualStudioInstance;
public SendKeys(VisualStudioInstance visualStudioInstance)
{
_visualStudioInstance = visualStudioInstance;
}
protected override void ActivateMainWindow()
{
_visualStudioInstance.ActivateMainWindow();
}
protected override void WaitForApplicationIdle(CancellationToken cancellationToken)
{
_visualStudioInstance.WaitForApplicationIdle(cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Features/Core/Portable/Completion/Providers/MemberInsertingCompletionItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
internal class MemberInsertionCompletionItem
{
public static CompletionItem Create(
string displayText,
string displayTextSuffix,
DeclarationModifiers modifiers,
int line,
ISymbol symbol,
SyntaxToken token,
int descriptionPosition,
CompletionItemRules rules)
{
var props = ImmutableDictionary<string, string>.Empty
.Add("Line", line.ToString())
.Add("Modifiers", modifiers.ToString())
.Add("TokenSpanEnd", token.Span.End.ToString());
return SymbolCompletionItem.CreateWithSymbolId(
displayText: displayText,
displayTextSuffix: displayTextSuffix,
symbols: ImmutableArray.Create(symbol),
contextPosition: descriptionPosition,
properties: props,
rules: rules,
isComplexTextEdit: true);
}
public static Task<CompletionDescription> GetDescriptionAsync(CompletionItem item, Document document, CancellationToken cancellationToken)
=> SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken);
public static DeclarationModifiers GetModifiers(CompletionItem item)
{
if (item.Properties.TryGetValue("Modifiers", out var text) &&
DeclarationModifiers.TryParse(text, out var modifiers))
{
return modifiers;
}
return default;
}
public static int GetLine(CompletionItem item)
{
if (item.Properties.TryGetValue("Line", out var text)
&& int.TryParse(text, out var number))
{
return number;
}
return 0;
}
public static int GetTokenSpanEnd(CompletionItem item)
{
if (item.Properties.TryGetValue("TokenSpanEnd", out var text)
&& int.TryParse(text, out var number))
{
return number;
}
return 0;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
internal class MemberInsertionCompletionItem
{
public static CompletionItem Create(
string displayText,
string displayTextSuffix,
DeclarationModifiers modifiers,
int line,
ISymbol symbol,
SyntaxToken token,
int descriptionPosition,
CompletionItemRules rules)
{
var props = ImmutableDictionary<string, string>.Empty
.Add("Line", line.ToString())
.Add("Modifiers", modifiers.ToString())
.Add("TokenSpanEnd", token.Span.End.ToString());
return SymbolCompletionItem.CreateWithSymbolId(
displayText: displayText,
displayTextSuffix: displayTextSuffix,
symbols: ImmutableArray.Create(symbol),
contextPosition: descriptionPosition,
properties: props,
rules: rules,
isComplexTextEdit: true);
}
public static Task<CompletionDescription> GetDescriptionAsync(CompletionItem item, Document document, CancellationToken cancellationToken)
=> SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken);
public static DeclarationModifiers GetModifiers(CompletionItem item)
{
if (item.Properties.TryGetValue("Modifiers", out var text) &&
DeclarationModifiers.TryParse(text, out var modifiers))
{
return modifiers;
}
return default;
}
public static int GetLine(CompletionItem item)
{
if (item.Properties.TryGetValue("Line", out var text)
&& int.TryParse(text, out var number))
{
return number;
}
return 0;
}
public static int GetTokenSpanEnd(CompletionItem item)
{
if (item.Properties.TryGetValue("TokenSpanEnd", out var text)
&& int.TryParse(text, out var number))
{
return number;
}
return 0;
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Scripting/CSharpTest/PrintOptionsTests.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.Scripting.Hosting;
using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests
{
public class PrintOptionsTests : ObjectFormatterTestBase
{
private static readonly ObjectFormatter s_formatter = new TestCSharpObjectFormatter();
[Fact]
public void NullOptions()
{
Assert.Throws<ArgumentNullException>(() => s_formatter.FormatObject("hello", options: null));
}
[Fact]
public void InvalidNumberRadix()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().NumberRadix = 3);
}
[Fact]
public void InvalidMemberDisplayFormat()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MemberDisplayFormat = (MemberDisplayFormat)(-1));
}
[Fact]
public void InvalidMaximumOutputLength()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MaximumOutputLength = -1);
Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MaximumOutputLength = 0);
}
[Fact]
public void ValidNumberRadix()
{
var formatter = new TestCSharpObjectFormatter(includeCodePoints: true);
var options = new PrintOptions();
options.NumberRadix = 10;
Assert.Equal("10", formatter.FormatObject(10, options));
Assert.Equal("int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }", formatter.FormatObject(new int[10], options));
Assert.Equal(@"16 '\u0010'", formatter.FormatObject('\u0010', options));
options.NumberRadix = 16;
Assert.Equal("0x0000000a", formatter.FormatObject(10, options));
Assert.Equal("int[0x0000000a] { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }", formatter.FormatObject(new int[10], options));
Assert.Equal(@"0x0010 '\u0010'", formatter.FormatObject('\u0010', options));
}
[Fact]
public void ValidMemberDisplayFormat()
{
var options = new PrintOptions();
options.MemberDisplayFormat = MemberDisplayFormat.Hidden;
Assert.Equal("PrintOptions", s_formatter.FormatObject(options, options));
options.MemberDisplayFormat = MemberDisplayFormat.SingleLine;
Assert.Equal("PrintOptions { Ellipsis=\"...\", EscapeNonPrintableCharacters=true, MaximumOutputLength=1024, MemberDisplayFormat=SingleLine, NumberRadix=10 }", s_formatter.FormatObject(options, options));
options.MemberDisplayFormat = MemberDisplayFormat.SeparateLines;
Assert.Equal(@"PrintOptions {
Ellipsis: ""..."",
EscapeNonPrintableCharacters: true,
MaximumOutputLength: 1024,
MemberDisplayFormat: SeparateLines,
NumberRadix: 10,
_maximumOutputLength: 1024,
_memberDisplayFormat: SeparateLines,
_numberRadix: 10
}
", s_formatter.FormatObject(options, options));
}
[Fact]
public void ValidEscapeNonPrintableCharacters()
{
var options = new PrintOptions();
options.EscapeNonPrintableCharacters = true;
Assert.Equal(@"""\t""", s_formatter.FormatObject("\t", options));
Assert.Equal(@"'\t'", s_formatter.FormatObject('\t', options));
options.EscapeNonPrintableCharacters = false;
Assert.Equal("\"\t\"", s_formatter.FormatObject("\t", options));
Assert.Equal("'\t'", s_formatter.FormatObject('\t', options));
}
[Fact]
public void ValidMaximumOutputLength()
{
var options = new PrintOptions();
options.MaximumOutputLength = 1;
Assert.Equal("1...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 2;
Assert.Equal("12...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 3;
Assert.Equal("123...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 4;
Assert.Equal("1234...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 5;
Assert.Equal("12345...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 6;
Assert.Equal("123456", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 7;
Assert.Equal("123456", s_formatter.FormatObject(123456, options));
}
[Fact]
public void ValidEllipsis()
{
var options = new PrintOptions();
options.MaximumOutputLength = 1;
options.Ellipsis = ".";
Assert.Equal("1.", s_formatter.FormatObject(123456, options));
options.Ellipsis = "..";
Assert.Equal("1..", s_formatter.FormatObject(123456, options));
options.Ellipsis = "";
Assert.Equal("1", s_formatter.FormatObject(123456, options));
options.Ellipsis = null;
Assert.Equal("1", s_formatter.FormatObject(123456, options));
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Scripting.Hosting;
using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests
{
public class PrintOptionsTests : ObjectFormatterTestBase
{
private static readonly ObjectFormatter s_formatter = new TestCSharpObjectFormatter();
[Fact]
public void NullOptions()
{
Assert.Throws<ArgumentNullException>(() => s_formatter.FormatObject("hello", options: null));
}
[Fact]
public void InvalidNumberRadix()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().NumberRadix = 3);
}
[Fact]
public void InvalidMemberDisplayFormat()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MemberDisplayFormat = (MemberDisplayFormat)(-1));
}
[Fact]
public void InvalidMaximumOutputLength()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MaximumOutputLength = -1);
Assert.Throws<ArgumentOutOfRangeException>(() => new PrintOptions().MaximumOutputLength = 0);
}
[Fact]
public void ValidNumberRadix()
{
var formatter = new TestCSharpObjectFormatter(includeCodePoints: true);
var options = new PrintOptions();
options.NumberRadix = 10;
Assert.Equal("10", formatter.FormatObject(10, options));
Assert.Equal("int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }", formatter.FormatObject(new int[10], options));
Assert.Equal(@"16 '\u0010'", formatter.FormatObject('\u0010', options));
options.NumberRadix = 16;
Assert.Equal("0x0000000a", formatter.FormatObject(10, options));
Assert.Equal("int[0x0000000a] { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }", formatter.FormatObject(new int[10], options));
Assert.Equal(@"0x0010 '\u0010'", formatter.FormatObject('\u0010', options));
}
[Fact]
public void ValidMemberDisplayFormat()
{
var options = new PrintOptions();
options.MemberDisplayFormat = MemberDisplayFormat.Hidden;
Assert.Equal("PrintOptions", s_formatter.FormatObject(options, options));
options.MemberDisplayFormat = MemberDisplayFormat.SingleLine;
Assert.Equal("PrintOptions { Ellipsis=\"...\", EscapeNonPrintableCharacters=true, MaximumOutputLength=1024, MemberDisplayFormat=SingleLine, NumberRadix=10 }", s_formatter.FormatObject(options, options));
options.MemberDisplayFormat = MemberDisplayFormat.SeparateLines;
Assert.Equal(@"PrintOptions {
Ellipsis: ""..."",
EscapeNonPrintableCharacters: true,
MaximumOutputLength: 1024,
MemberDisplayFormat: SeparateLines,
NumberRadix: 10,
_maximumOutputLength: 1024,
_memberDisplayFormat: SeparateLines,
_numberRadix: 10
}
", s_formatter.FormatObject(options, options));
}
[Fact]
public void ValidEscapeNonPrintableCharacters()
{
var options = new PrintOptions();
options.EscapeNonPrintableCharacters = true;
Assert.Equal(@"""\t""", s_formatter.FormatObject("\t", options));
Assert.Equal(@"'\t'", s_formatter.FormatObject('\t', options));
options.EscapeNonPrintableCharacters = false;
Assert.Equal("\"\t\"", s_formatter.FormatObject("\t", options));
Assert.Equal("'\t'", s_formatter.FormatObject('\t', options));
}
[Fact]
public void ValidMaximumOutputLength()
{
var options = new PrintOptions();
options.MaximumOutputLength = 1;
Assert.Equal("1...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 2;
Assert.Equal("12...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 3;
Assert.Equal("123...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 4;
Assert.Equal("1234...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 5;
Assert.Equal("12345...", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 6;
Assert.Equal("123456", s_formatter.FormatObject(123456, options));
options.MaximumOutputLength = 7;
Assert.Equal("123456", s_formatter.FormatObject(123456, options));
}
[Fact]
public void ValidEllipsis()
{
var options = new PrintOptions();
options.MaximumOutputLength = 1;
options.Ellipsis = ".";
Assert.Equal("1.", s_formatter.FormatObject(123456, options));
options.Ellipsis = "..";
Assert.Equal("1..", s_formatter.FormatObject(123456, options));
options.Ellipsis = "";
Assert.Equal("1", s_formatter.FormatObject(123456, options));
options.Ellipsis = null;
Assert.Equal("1", s_formatter.FormatObject(123456, options));
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Compilers/Core/Portable/InternalUtilities/RoslynString.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace Roslyn.Utilities
{
internal static class RoslynString
{
/// <inheritdoc cref="string.IsNullOrEmpty(string)"/>
public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] string? value)
=> string.IsNullOrEmpty(value);
#if !NET20
/// <inheritdoc cref="string.IsNullOrWhiteSpace(string)"/>
public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] string? value)
=> string.IsNullOrWhiteSpace(value);
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace Roslyn.Utilities
{
internal static class RoslynString
{
/// <inheritdoc cref="string.IsNullOrEmpty(string)"/>
public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] string? value)
=> string.IsNullOrEmpty(value);
#if !NET20
/// <inheritdoc cref="string.IsNullOrWhiteSpace(string)"/>
public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] string? value)
=> string.IsNullOrWhiteSpace(value);
#endif
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/CodeStyle/Core/Analyzers/AbstractFormattingAnalyzer.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 Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal abstract class AbstractFormattingAnalyzer
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
protected AbstractFormattingAnalyzer()
: base(
IDEDiagnosticIds.FormattingDiagnosticId,
EnforceOnBuildValues.Formatting,
option: null,
new LocalizableResourceString(nameof(CodeStyleResources.Fix_formatting), CodeStyleResources.ResourceManager, typeof(CodeStyleResources)),
new LocalizableResourceString(nameof(CodeStyleResources.Fix_formatting), CodeStyleResources.ResourceManager, typeof(CodeStyleResources)))
{
}
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected abstract ISyntaxFormattingService SyntaxFormattingService { get; }
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree);
private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
var analyzerConfigOptions = context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Tree);
FormattingAnalyzerHelper.AnalyzeSyntaxTree(context, SyntaxFormattingService, Descriptor, analyzerConfigOptions);
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal abstract class AbstractFormattingAnalyzer
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
protected AbstractFormattingAnalyzer()
: base(
IDEDiagnosticIds.FormattingDiagnosticId,
EnforceOnBuildValues.Formatting,
option: null,
new LocalizableResourceString(nameof(CodeStyleResources.Fix_formatting), CodeStyleResources.ResourceManager, typeof(CodeStyleResources)),
new LocalizableResourceString(nameof(CodeStyleResources.Fix_formatting), CodeStyleResources.ResourceManager, typeof(CodeStyleResources)))
{
}
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected abstract ISyntaxFormattingService SyntaxFormattingService { get; }
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree);
private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
var analyzerConfigOptions = context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Tree);
FormattingAnalyzerHelper.AnalyzeSyntaxTree(context, SyntaxFormattingService, Descriptor, analyzerConfigOptions);
}
}
}
| -1 |
dotnet/roslyn | 55,364 | Fix crash with convert namespace | Oopsie. | CyrusNajmabadi | 2021-08-03T02:29:24Z | 2021-08-03T12:57:53Z | a80a5868188242800f4615dc51ab30ed5e9eaf76 | 3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf | Fix crash with convert namespace. Oopsie. | ./src/Workspaces/Core/Portable/Shared/Extensions/SemanticEquivalence.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 Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SemanticEquivalence
{
public static bool AreEquivalent(SemanticModel semanticModel, SyntaxNode node1, SyntaxNode node2)
=> AreEquivalent(semanticModel, semanticModel, node1, node2);
public static bool AreEquivalent(
SemanticModel semanticModel1,
SemanticModel semanticModel2,
SyntaxNode node1,
SyntaxNode node2,
Func<SyntaxNode, bool> predicate = null)
{
// First check for syntactic equivalency. If two nodes aren't structurally equivalent,
// then they're not semantically equivalent.
if (node1 == null && node2 == null)
{
return true;
}
if (node1 == null || node2 == null)
{
return false;
}
if (!node1.IsEquivalentTo(node2, topLevel: false))
{
return false;
}
// From this point on we can assume the tree structure is the same. So no need to check
// kinds, child counts or token contents.
return AreSemanticallyEquivalentWorker(
semanticModel1, semanticModel2, node1, node2, predicate);
}
private static bool AreSemanticallyEquivalentWorker(
SemanticModel semanticModel1,
SemanticModel semanticModel2,
SyntaxNode node1,
SyntaxNode node2,
Func<SyntaxNode, bool> predicate)
{
if (node1 == node2)
{
return true;
}
if (predicate == null || predicate(node1))
{
var info1 = semanticModel1.GetSymbolInfo(node1);
var info2 = semanticModel2.GetSymbolInfo(node2);
if (!AreEquals(semanticModel1, semanticModel2, info1, info2))
{
return false;
}
}
// Original expression and current node being semantically equivalent isn't enough when the original expression
// is a member access via instance reference (either implicit or explicit), the check only ensures that the expression
// and current node are both backed by the same member symbol. So in this case, in addition to SemanticEquivalence check,
// we also check if expression and current node are both instance member access.
//
// For example, even though the first `c` binds to a field and we are introducing a local for it,
// we don't want other references to that field to be replaced as well (i.e. the second `c` in the expression).
//
// class C
// {
// C c;
// void Test()
// {
// var x = [|c|].c;
// }
// }
var originalOperation = semanticModel1.GetOperation(node1);
if (originalOperation != null && IsInstanceMemberReference(originalOperation))
{
var currentOperation = semanticModel2.GetOperation(node2);
if (currentOperation is null || !IsInstanceMemberReference(currentOperation))
{
return false;
}
}
var e1 = node1.ChildNodesAndTokens().GetEnumerator();
var e2 = node2.ChildNodesAndTokens().GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
Contract.ThrowIfTrue(b1 != b2);
if (b1 == false)
{
return true;
}
var c1 = e1.Current;
var c2 = e2.Current;
if (c1.IsNode && c2.IsNode)
{
if (!AreSemanticallyEquivalentWorker(semanticModel1, semanticModel2, c1.AsNode(), c2.AsNode(), predicate))
{
return false;
}
}
}
}
private static bool IsInstanceMemberReference(IOperation operation)
=> operation is IMemberReferenceOperation { Instance: { Kind: OperationKind.InstanceReference } };
private static bool AreEquals(
SemanticModel semanticModel1,
SemanticModel semanticModel2,
SymbolInfo info1,
SymbolInfo info2)
{
if (semanticModel1 == semanticModel2)
{
return EqualityComparer<ISymbol>.Default.Equals(info1.Symbol, info2.Symbol);
}
else
{
return SymbolEquivalenceComparer.Instance.Equals(info1.Symbol, info2.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 System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SemanticEquivalence
{
public static bool AreEquivalent(SemanticModel semanticModel, SyntaxNode node1, SyntaxNode node2)
=> AreEquivalent(semanticModel, semanticModel, node1, node2);
public static bool AreEquivalent(
SemanticModel semanticModel1,
SemanticModel semanticModel2,
SyntaxNode node1,
SyntaxNode node2,
Func<SyntaxNode, bool> predicate = null)
{
// First check for syntactic equivalency. If two nodes aren't structurally equivalent,
// then they're not semantically equivalent.
if (node1 == null && node2 == null)
{
return true;
}
if (node1 == null || node2 == null)
{
return false;
}
if (!node1.IsEquivalentTo(node2, topLevel: false))
{
return false;
}
// From this point on we can assume the tree structure is the same. So no need to check
// kinds, child counts or token contents.
return AreSemanticallyEquivalentWorker(
semanticModel1, semanticModel2, node1, node2, predicate);
}
private static bool AreSemanticallyEquivalentWorker(
SemanticModel semanticModel1,
SemanticModel semanticModel2,
SyntaxNode node1,
SyntaxNode node2,
Func<SyntaxNode, bool> predicate)
{
if (node1 == node2)
{
return true;
}
if (predicate == null || predicate(node1))
{
var info1 = semanticModel1.GetSymbolInfo(node1);
var info2 = semanticModel2.GetSymbolInfo(node2);
if (!AreEquals(semanticModel1, semanticModel2, info1, info2))
{
return false;
}
}
// Original expression and current node being semantically equivalent isn't enough when the original expression
// is a member access via instance reference (either implicit or explicit), the check only ensures that the expression
// and current node are both backed by the same member symbol. So in this case, in addition to SemanticEquivalence check,
// we also check if expression and current node are both instance member access.
//
// For example, even though the first `c` binds to a field and we are introducing a local for it,
// we don't want other references to that field to be replaced as well (i.e. the second `c` in the expression).
//
// class C
// {
// C c;
// void Test()
// {
// var x = [|c|].c;
// }
// }
var originalOperation = semanticModel1.GetOperation(node1);
if (originalOperation != null && IsInstanceMemberReference(originalOperation))
{
var currentOperation = semanticModel2.GetOperation(node2);
if (currentOperation is null || !IsInstanceMemberReference(currentOperation))
{
return false;
}
}
var e1 = node1.ChildNodesAndTokens().GetEnumerator();
var e2 = node2.ChildNodesAndTokens().GetEnumerator();
while (true)
{
var b1 = e1.MoveNext();
var b2 = e2.MoveNext();
Contract.ThrowIfTrue(b1 != b2);
if (b1 == false)
{
return true;
}
var c1 = e1.Current;
var c2 = e2.Current;
if (c1.IsNode && c2.IsNode)
{
if (!AreSemanticallyEquivalentWorker(semanticModel1, semanticModel2, c1.AsNode(), c2.AsNode(), predicate))
{
return false;
}
}
}
}
private static bool IsInstanceMemberReference(IOperation operation)
=> operation is IMemberReferenceOperation { Instance: { Kind: OperationKind.InstanceReference } };
private static bool AreEquals(
SemanticModel semanticModel1,
SemanticModel semanticModel2,
SymbolInfo info1,
SymbolInfo info2)
{
if (semanticModel1 == semanticModel2)
{
return EqualityComparer<ISymbol>.Default.Equals(info1.Symbol, info2.Symbol);
}
else
{
return SymbolEquivalenceComparer.Instance.Equals(info1.Symbol, info2.Symbol);
}
}
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.