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,179 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | 2021-07-28T12:01:59Z | 2021-07-28T13:07:16Z | badcd003f616de451aa1ce04191f27c0be835c4d | af0313d42f845445623b2ee6865ac13ba1faf522 | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/Core/Implementation/DocumentationComments/AbstractXmlTagCompletionCommandHandler.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 Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments
{
internal abstract class AbstractXmlTagCompletionCommandHandler : IChainedCommandHandler<TypeCharCommandArgs>
{
private readonly ITextUndoHistoryRegistry _undoHistory;
public string DisplayName => EditorFeaturesResources.XML_End_Tag_Completion;
public AbstractXmlTagCompletionCommandHandler(ITextUndoHistoryRegistry undoHistory)
=> _undoHistory = undoHistory;
protected abstract void TryCompleteTag(ITextView textView, ITextBuffer subjectBuffer, Document document, SnapshotPoint position, CancellationToken cancellationToken);
public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler)
=> nextHandler();
public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
// Ensure completion and any other buffer edits happen first.
nextHandler();
var cancellationToken = context.OperationContext.UserCancellationToken;
if (cancellationToken.IsCancellationRequested)
{
return;
}
try
{
ExecuteCommandWorker(args, context);
}
catch (OperationCanceledException)
{
// According to Editor command handler API guidelines, it's best if we return early if cancellation
// is requested instead of throwing. Otherwise, we could end up in an invalid state due to already
// calling nextHandler().
}
}
private void ExecuteCommandWorker(TypeCharCommandArgs args, CommandExecutionContext context)
{
if (args.TypedChar != '>' && args.TypedChar != '/')
{
return;
}
using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Completing_Tag))
{
var buffer = args.SubjectBuffer;
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
// We actually want the caret position after any operations
var position = args.TextView.GetCaretPoint(args.SubjectBuffer);
// No caret position? No edit!
if (!position.HasValue)
{
return;
}
TryCompleteTag(args.TextView, args.SubjectBuffer, document, position.Value, context.OperationContext.UserCancellationToken);
}
}
protected void InsertTextAndMoveCaret(ITextView textView, ITextBuffer subjectBuffer, SnapshotPoint position, string insertionText, int? finalCaretPosition)
{
using var transaction = _undoHistory.GetHistory(textView.TextBuffer).CreateTransaction("XmlTagCompletion");
subjectBuffer.Insert(position, insertionText);
if (finalCaretPosition.HasValue)
{
var point = subjectBuffer.CurrentSnapshot.GetPoint(finalCaretPosition.Value);
textView.TryMoveCaretToAndEnsureVisible(point);
}
transaction.Complete();
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments
{
internal abstract class AbstractXmlTagCompletionCommandHandler : IChainedCommandHandler<TypeCharCommandArgs>
{
private readonly ITextUndoHistoryRegistry _undoHistory;
public string DisplayName => EditorFeaturesResources.XML_End_Tag_Completion;
public AbstractXmlTagCompletionCommandHandler(ITextUndoHistoryRegistry undoHistory)
=> _undoHistory = undoHistory;
protected abstract void TryCompleteTag(ITextView textView, ITextBuffer subjectBuffer, Document document, SnapshotPoint position, CancellationToken cancellationToken);
public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler)
=> nextHandler();
public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context)
{
// Ensure completion and any other buffer edits happen first.
nextHandler();
var cancellationToken = context.OperationContext.UserCancellationToken;
if (cancellationToken.IsCancellationRequested)
{
return;
}
try
{
ExecuteCommandWorker(args, context);
}
catch (OperationCanceledException)
{
// According to Editor command handler API guidelines, it's best if we return early if cancellation
// is requested instead of throwing. Otherwise, we could end up in an invalid state due to already
// calling nextHandler().
}
}
private void ExecuteCommandWorker(TypeCharCommandArgs args, CommandExecutionContext context)
{
if (args.TypedChar != '>' && args.TypedChar != '/')
{
return;
}
using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Completing_Tag))
{
var buffer = args.SubjectBuffer;
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
// We actually want the caret position after any operations
var position = args.TextView.GetCaretPoint(args.SubjectBuffer);
// No caret position? No edit!
if (!position.HasValue)
{
return;
}
TryCompleteTag(args.TextView, args.SubjectBuffer, document, position.Value, context.OperationContext.UserCancellationToken);
}
}
protected void InsertTextAndMoveCaret(ITextView textView, ITextBuffer subjectBuffer, SnapshotPoint position, string insertionText, int? finalCaretPosition)
{
using var transaction = _undoHistory.GetHistory(textView.TextBuffer).CreateTransaction("XmlTagCompletion");
subjectBuffer.Insert(position, insertionText);
if (finalCaretPosition.HasValue)
{
var point = subjectBuffer.CurrentSnapshot.GetPoint(finalCaretPosition.Value);
textView.TryMoveCaretToAndEnsureVisible(point);
}
transaction.Complete();
}
}
}
| -1 |
dotnet/roslyn | 55,179 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | 2021-07-28T12:01:59Z | 2021-07-28T13:07:16Z | badcd003f616de451aa1ce04191f27c0be835c4d | af0313d42f845445623b2ee6865ac13ba1faf522 | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Shared/GlobalAssemblyCacheHelpers/FusionAssemblyIdentity.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.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class FusionAssemblyIdentity
{
[Flags]
internal enum ASM_DISPLAYF
{
VERSION = 0x01,
CULTURE = 0x02,
PUBLIC_KEY_TOKEN = 0x04,
PUBLIC_KEY = 0x08,
CUSTOM = 0x10,
PROCESSORARCHITECTURE = 0x20,
LANGUAGEID = 0x40,
RETARGET = 0x80,
CONFIG_MASK = 0x100,
MVID = 0x200,
CONTENT_TYPE = 0x400,
FULL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE | CONTENT_TYPE
}
internal enum PropertyId
{
PUBLIC_KEY = 0, // 0
PUBLIC_KEY_TOKEN, // 1
HASH_VALUE, // 2
NAME, // 3
MAJOR_VERSION, // 4
MINOR_VERSION, // 5
BUILD_NUMBER, // 6
REVISION_NUMBER, // 7
CULTURE, // 8
PROCESSOR_ID_ARRAY, // 9
OSINFO_ARRAY, // 10
HASH_ALGID, // 11
ALIAS, // 12
CODEBASE_URL, // 13
CODEBASE_LASTMOD, // 14
NULL_PUBLIC_KEY, // 15
NULL_PUBLIC_KEY_TOKEN, // 16
CUSTOM, // 17
NULL_CUSTOM, // 18
MVID, // 19
FILE_MAJOR_VERSION, // 20
FILE_MINOR_VERSION, // 21
FILE_BUILD_NUMBER, // 22
FILE_REVISION_NUMBER, // 23
RETARGET, // 24
SIGNATURE_BLOB, // 25
CONFIG_MASK, // 26
ARCHITECTURE, // 27
CONTENT_TYPE, // 28
MAX_PARAMS // 29
}
private static class CANOF
{
public const uint PARSE_DISPLAY_NAME = 0x1;
public const uint SET_DEFAULT_VALUES = 0x2;
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")]
internal unsafe interface IAssemblyName
{
void SetProperty(PropertyId id, void* data, uint size);
[PreserveSig]
int GetProperty(PropertyId id, void* data, ref uint size);
[PreserveSig]
int Finalize();
[PreserveSig]
int GetDisplayName(byte* buffer, ref uint characterCount, ASM_DISPLAYF dwDisplayFlags);
[PreserveSig]
int __BindToObject(/*...*/);
[PreserveSig]
int __GetName(/*...*/);
[PreserveSig]
int GetVersion(out uint versionHi, out uint versionLow);
[PreserveSig]
int IsEqual(IAssemblyName pName, uint dwCmpFlags);
[PreserveSig]
int Clone(out IAssemblyName pName);
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")]
internal interface IApplicationContext
{
}
// NOTE: The CLR caches assembly identities, but doesn't do so in a threadsafe manner.
// Wrap all calls to this with a lock.
private static readonly object s_assemblyIdentityGate = new object();
private static int CreateAssemblyNameObject(out IAssemblyName ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved)
{
lock (s_assemblyIdentityGate)
{
return RealCreateAssemblyNameObject(out ppEnum, szAssemblyName, dwFlags, pvReserved);
}
}
[DllImport("clr", EntryPoint = "CreateAssemblyNameObject", CharSet = CharSet.Unicode, PreserveSig = true)]
private static extern int RealCreateAssemblyNameObject(out IAssemblyName ppEnum, [MarshalAs(UnmanagedType.LPWStr)] string szAssemblyName, uint dwFlags, IntPtr pvReserved);
private const int ERROR_INSUFFICIENT_BUFFER = unchecked((int)0x8007007A);
private const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047);
internal static unsafe string GetDisplayName(IAssemblyName nameObject, ASM_DISPLAYF displayFlags)
{
int hr;
uint characterCountIncludingTerminator = 0;
hr = nameObject.GetDisplayName(null, ref characterCountIncludingTerminator, displayFlags);
if (hr == 0)
{
return String.Empty;
}
if (hr != ERROR_INSUFFICIENT_BUFFER)
{
throw Marshal.GetExceptionForHR(hr);
}
byte[] data = new byte[(int)characterCountIncludingTerminator * 2];
fixed (byte* p = data)
{
hr = nameObject.GetDisplayName(p, ref characterCountIncludingTerminator, displayFlags);
if (hr != 0)
{
throw Marshal.GetExceptionForHR(hr);
}
return Marshal.PtrToStringUni((IntPtr)p, (int)characterCountIncludingTerminator - 1);
}
}
internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, PropertyId propertyId)
{
int hr;
uint size = 0;
hr = nameObject.GetProperty(propertyId, null, ref size);
if (hr == 0)
{
return null;
}
if (hr != ERROR_INSUFFICIENT_BUFFER)
{
throw Marshal.GetExceptionForHR(hr);
}
byte[] data = new byte[(int)size];
fixed (byte* p = data)
{
hr = nameObject.GetProperty(propertyId, p, ref size);
if (hr != 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
return data;
}
internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId)
{
byte[] data = GetPropertyBytes(nameObject, propertyId);
if (data == null)
{
return null;
}
fixed (byte* p = data)
{
return Marshal.PtrToStringUni((IntPtr)p, (data.Length / 2) - 1);
}
}
internal static unsafe bool IsKeyOrTokenEmpty(IAssemblyName nameObject, PropertyId propertyId)
{
Debug.Assert(propertyId == PropertyId.NULL_PUBLIC_KEY_TOKEN || propertyId == PropertyId.NULL_PUBLIC_KEY);
uint size = 0;
int hr = nameObject.GetProperty(propertyId, null, ref size);
return hr == 0;
}
internal static unsafe Version GetVersion(IAssemblyName nameObject)
{
uint hi, lo;
int hr = nameObject.GetVersion(out hi, out lo);
if (hr != 0)
{
Debug.Assert(hr == FUSION_E_INVALID_NAME);
return null;
}
return new Version((int)(hi >> 16), (int)(hi & 0xffff), (int)(lo >> 16), (int)(lo & 0xffff));
}
internal static Version GetVersion(IAssemblyName name, out AssemblyIdentityParts parts)
{
uint? major = GetPropertyWord(name, PropertyId.MAJOR_VERSION);
uint? minor = GetPropertyWord(name, PropertyId.MINOR_VERSION);
uint? build = GetPropertyWord(name, PropertyId.BUILD_NUMBER);
uint? revision = GetPropertyWord(name, PropertyId.REVISION_NUMBER);
parts = 0;
if (major != null)
{
parts |= AssemblyIdentityParts.VersionMajor;
}
if (minor != null)
{
parts |= AssemblyIdentityParts.VersionMinor;
}
if (build != null)
{
parts |= AssemblyIdentityParts.VersionBuild;
}
if (revision != null)
{
parts |= AssemblyIdentityParts.VersionRevision;
}
return new Version((int)(major ?? 0), (int)(minor ?? 0), (int)(build ?? 0), (int)(revision ?? 0));
}
internal static byte[] GetPublicKeyToken(IAssemblyName nameObject)
{
byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY_TOKEN);
if (result != null)
{
return result;
}
if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY_TOKEN))
{
return Array.Empty<byte>();
}
return null;
}
internal static byte[] GetPublicKey(IAssemblyName nameObject)
{
byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY);
if (result != null)
{
return result;
}
if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY))
{
return Array.Empty<byte>();
}
return null;
}
internal static unsafe uint? GetPropertyWord(IAssemblyName nameObject, PropertyId propertyId)
{
uint result;
uint size = sizeof(uint);
int hr = nameObject.GetProperty(propertyId, &result, ref size);
if (hr != 0)
{
throw Marshal.GetExceptionForHR(hr);
}
if (size == 0)
{
return null;
}
return result;
}
internal static string GetName(IAssemblyName nameObject)
{
return GetPropertyString(nameObject, PropertyId.NAME);
}
internal static string GetCulture(IAssemblyName nameObject)
{
return GetPropertyString(nameObject, PropertyId.CULTURE);
}
internal static AssemblyContentType GetContentType(IAssemblyName nameObject)
{
return (AssemblyContentType)(GetPropertyWord(nameObject, PropertyId.CONTENT_TYPE) ?? 0);
}
internal static ProcessorArchitecture GetProcessorArchitecture(IAssemblyName nameObject)
{
return (ProcessorArchitecture)(GetPropertyWord(nameObject, PropertyId.ARCHITECTURE) ?? 0);
}
internal static unsafe AssemblyNameFlags GetFlags(IAssemblyName nameObject)
{
AssemblyNameFlags result = 0;
uint retarget = GetPropertyWord(nameObject, PropertyId.RETARGET) ?? 0;
if (retarget != 0)
{
result |= AssemblyNameFlags.Retargetable;
}
return result;
}
private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, string data)
{
if (data == null)
{
nameObject.SetProperty(propertyId, null, 0);
}
else
{
Debug.Assert(data.IndexOf('\0') == -1);
fixed (char* p = data)
{
Debug.Assert(p[data.Length] == '\0');
// size is in bytes, include trailing \0 character:
nameObject.SetProperty(propertyId, p, (uint)(data.Length + 1) * 2);
}
}
}
private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, byte[] data)
{
if (data == null)
{
nameObject.SetProperty(propertyId, null, 0);
}
else
{
fixed (byte* p = data)
{
nameObject.SetProperty(propertyId, p, (uint)data.Length);
}
}
}
private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, ushort data)
{
nameObject.SetProperty(propertyId, &data, sizeof(ushort));
}
private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, uint data)
{
nameObject.SetProperty(propertyId, &data, sizeof(uint));
}
private static unsafe void SetPublicKeyToken(IAssemblyName nameObject, byte[] value)
{
// An empty public key token is set via NULL_PUBLIC_KEY_TOKEN property.
if (value != null && value.Length == 0)
{
nameObject.SetProperty(PropertyId.NULL_PUBLIC_KEY_TOKEN, null, 0);
}
else
{
SetProperty(nameObject, PropertyId.PUBLIC_KEY_TOKEN, value);
}
}
/// <summary>
/// Converts <see cref="IAssemblyName"/> to <see cref="AssemblyName"/> with all metadata fields filled.
/// </summary>
/// <returns>
/// Assembly name with Version, Culture and PublicKeyToken components filled in:
/// "SimpleName, Version=#.#.#.#, Culture=XXX, PublicKeyToken=XXXXXXXXXXXXXXXX".
/// In addition Retargetable flag and ContentType are set.
/// </returns>
internal static AssemblyIdentity ToAssemblyIdentity(IAssemblyName nameObject)
{
if (nameObject == null)
{
return null;
}
AssemblyNameFlags flags = GetFlags(nameObject);
byte[] publicKey = GetPublicKey(nameObject);
bool hasPublicKey = publicKey != null && publicKey.Length != 0;
AssemblyIdentityParts versionParts;
return new AssemblyIdentity(
GetName(nameObject),
GetVersion(nameObject, out versionParts),
GetCulture(nameObject) ?? "",
(hasPublicKey ? publicKey : GetPublicKeyToken(nameObject)).AsImmutableOrNull(),
hasPublicKey: hasPublicKey,
isRetargetable: (flags & AssemblyNameFlags.Retargetable) != 0,
contentType: GetContentType(nameObject));
}
/// <summary>
/// Converts <see cref="AssemblyName"/> to an equivalent <see cref="IAssemblyName"/>.
/// </summary>
internal static IAssemblyName ToAssemblyNameObject(AssemblyName name)
{
if (name == null)
{
return null;
}
IAssemblyName result;
Marshal.ThrowExceptionForHR(CreateAssemblyNameObject(out result, null, 0, IntPtr.Zero));
string assemblyName = name.Name;
if (assemblyName != null)
{
if (assemblyName.IndexOf('\0') >= 0)
{
#if SCRIPTING
throw new ArgumentException(Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name));
#elif EDITOR_FEATURES
throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name));
#else
throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name));
#endif
}
SetProperty(result, PropertyId.NAME, assemblyName);
}
if (name.Version != null)
{
SetProperty(result, PropertyId.MAJOR_VERSION, unchecked((ushort)name.Version.Major));
SetProperty(result, PropertyId.MINOR_VERSION, unchecked((ushort)name.Version.Minor));
SetProperty(result, PropertyId.BUILD_NUMBER, unchecked((ushort)name.Version.Build));
SetProperty(result, PropertyId.REVISION_NUMBER, unchecked((ushort)name.Version.Revision));
}
string cultureName = name.CultureName;
if (cultureName != null)
{
if (cultureName.IndexOf('\0') >= 0)
{
#if SCRIPTING
throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name));
#elif EDITOR_FEATURES
throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name));
#else
throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name));
#endif
}
SetProperty(result, PropertyId.CULTURE, cultureName);
}
if (name.Flags == AssemblyNameFlags.Retargetable)
{
SetProperty(result, PropertyId.RETARGET, 1U);
}
if (name.ContentType != AssemblyContentType.Default)
{
SetProperty(result, PropertyId.CONTENT_TYPE, (uint)name.ContentType);
}
byte[] token = name.GetPublicKeyToken();
SetPublicKeyToken(result, token);
return result;
}
/// <summary>
/// Creates <see cref="IAssemblyName"/> object by parsing given display name.
/// </summary>
internal static IAssemblyName ToAssemblyNameObject(string displayName)
{
// CLR doesn't handle \0 in the display name well:
if (displayName.IndexOf('\0') >= 0)
{
return null;
}
Debug.Assert(displayName != null);
IAssemblyName result;
int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero);
if (hr != 0)
{
return null;
}
Debug.Assert(result != null);
return result;
}
/// <summary>
/// Selects the candidate assembly with the largest version number. Uses culture as a tie-breaker if it is provided.
/// All candidates are assumed to have the same name and must include versions and cultures.
/// </summary>
internal static IAssemblyName GetBestMatch(IEnumerable<IAssemblyName> candidates, string preferredCultureOpt)
{
IAssemblyName bestCandidate = null;
Version bestVersion = null;
string bestCulture = null;
foreach (var candidate in candidates)
{
if (bestCandidate != null)
{
Version candidateVersion = GetVersion(candidate);
Debug.Assert(candidateVersion != null);
if (bestVersion == null)
{
bestVersion = GetVersion(bestCandidate);
Debug.Assert(bestVersion != null);
}
int cmp = bestVersion.CompareTo(candidateVersion);
if (cmp == 0)
{
if (preferredCultureOpt != null)
{
string candidateCulture = GetCulture(candidate);
Debug.Assert(candidateCulture != null);
if (bestCulture == null)
{
bestCulture = GetCulture(candidate);
Debug.Assert(bestCulture != null);
}
// we have exactly the preferred culture or
// we have neutral culture and the best candidate's culture isn't the preferred one:
if (StringComparer.OrdinalIgnoreCase.Equals(candidateCulture, preferredCultureOpt) ||
candidateCulture.Length == 0 && !StringComparer.OrdinalIgnoreCase.Equals(bestCulture, preferredCultureOpt))
{
bestCandidate = candidate;
bestVersion = candidateVersion;
bestCulture = candidateCulture;
}
}
}
else if (cmp < 0)
{
bestCandidate = candidate;
bestVersion = candidateVersion;
}
}
else
{
bestCandidate = candidate;
}
}
return bestCandidate;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class FusionAssemblyIdentity
{
[Flags]
internal enum ASM_DISPLAYF
{
VERSION = 0x01,
CULTURE = 0x02,
PUBLIC_KEY_TOKEN = 0x04,
PUBLIC_KEY = 0x08,
CUSTOM = 0x10,
PROCESSORARCHITECTURE = 0x20,
LANGUAGEID = 0x40,
RETARGET = 0x80,
CONFIG_MASK = 0x100,
MVID = 0x200,
CONTENT_TYPE = 0x400,
FULL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE | CONTENT_TYPE
}
internal enum PropertyId
{
PUBLIC_KEY = 0, // 0
PUBLIC_KEY_TOKEN, // 1
HASH_VALUE, // 2
NAME, // 3
MAJOR_VERSION, // 4
MINOR_VERSION, // 5
BUILD_NUMBER, // 6
REVISION_NUMBER, // 7
CULTURE, // 8
PROCESSOR_ID_ARRAY, // 9
OSINFO_ARRAY, // 10
HASH_ALGID, // 11
ALIAS, // 12
CODEBASE_URL, // 13
CODEBASE_LASTMOD, // 14
NULL_PUBLIC_KEY, // 15
NULL_PUBLIC_KEY_TOKEN, // 16
CUSTOM, // 17
NULL_CUSTOM, // 18
MVID, // 19
FILE_MAJOR_VERSION, // 20
FILE_MINOR_VERSION, // 21
FILE_BUILD_NUMBER, // 22
FILE_REVISION_NUMBER, // 23
RETARGET, // 24
SIGNATURE_BLOB, // 25
CONFIG_MASK, // 26
ARCHITECTURE, // 27
CONTENT_TYPE, // 28
MAX_PARAMS // 29
}
private static class CANOF
{
public const uint PARSE_DISPLAY_NAME = 0x1;
public const uint SET_DEFAULT_VALUES = 0x2;
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")]
internal unsafe interface IAssemblyName
{
void SetProperty(PropertyId id, void* data, uint size);
[PreserveSig]
int GetProperty(PropertyId id, void* data, ref uint size);
[PreserveSig]
int Finalize();
[PreserveSig]
int GetDisplayName(byte* buffer, ref uint characterCount, ASM_DISPLAYF dwDisplayFlags);
[PreserveSig]
int __BindToObject(/*...*/);
[PreserveSig]
int __GetName(/*...*/);
[PreserveSig]
int GetVersion(out uint versionHi, out uint versionLow);
[PreserveSig]
int IsEqual(IAssemblyName pName, uint dwCmpFlags);
[PreserveSig]
int Clone(out IAssemblyName pName);
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")]
internal interface IApplicationContext
{
}
// NOTE: The CLR caches assembly identities, but doesn't do so in a threadsafe manner.
// Wrap all calls to this with a lock.
private static readonly object s_assemblyIdentityGate = new object();
private static int CreateAssemblyNameObject(out IAssemblyName ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved)
{
lock (s_assemblyIdentityGate)
{
return RealCreateAssemblyNameObject(out ppEnum, szAssemblyName, dwFlags, pvReserved);
}
}
[DllImport("clr", EntryPoint = "CreateAssemblyNameObject", CharSet = CharSet.Unicode, PreserveSig = true)]
private static extern int RealCreateAssemblyNameObject(out IAssemblyName ppEnum, [MarshalAs(UnmanagedType.LPWStr)] string szAssemblyName, uint dwFlags, IntPtr pvReserved);
private const int ERROR_INSUFFICIENT_BUFFER = unchecked((int)0x8007007A);
private const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047);
internal static unsafe string GetDisplayName(IAssemblyName nameObject, ASM_DISPLAYF displayFlags)
{
int hr;
uint characterCountIncludingTerminator = 0;
hr = nameObject.GetDisplayName(null, ref characterCountIncludingTerminator, displayFlags);
if (hr == 0)
{
return String.Empty;
}
if (hr != ERROR_INSUFFICIENT_BUFFER)
{
throw Marshal.GetExceptionForHR(hr);
}
byte[] data = new byte[(int)characterCountIncludingTerminator * 2];
fixed (byte* p = data)
{
hr = nameObject.GetDisplayName(p, ref characterCountIncludingTerminator, displayFlags);
if (hr != 0)
{
throw Marshal.GetExceptionForHR(hr);
}
return Marshal.PtrToStringUni((IntPtr)p, (int)characterCountIncludingTerminator - 1);
}
}
internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, PropertyId propertyId)
{
int hr;
uint size = 0;
hr = nameObject.GetProperty(propertyId, null, ref size);
if (hr == 0)
{
return null;
}
if (hr != ERROR_INSUFFICIENT_BUFFER)
{
throw Marshal.GetExceptionForHR(hr);
}
byte[] data = new byte[(int)size];
fixed (byte* p = data)
{
hr = nameObject.GetProperty(propertyId, p, ref size);
if (hr != 0)
{
throw Marshal.GetExceptionForHR(hr);
}
}
return data;
}
internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId)
{
byte[] data = GetPropertyBytes(nameObject, propertyId);
if (data == null)
{
return null;
}
fixed (byte* p = data)
{
return Marshal.PtrToStringUni((IntPtr)p, (data.Length / 2) - 1);
}
}
internal static unsafe bool IsKeyOrTokenEmpty(IAssemblyName nameObject, PropertyId propertyId)
{
Debug.Assert(propertyId == PropertyId.NULL_PUBLIC_KEY_TOKEN || propertyId == PropertyId.NULL_PUBLIC_KEY);
uint size = 0;
int hr = nameObject.GetProperty(propertyId, null, ref size);
return hr == 0;
}
internal static unsafe Version GetVersion(IAssemblyName nameObject)
{
uint hi, lo;
int hr = nameObject.GetVersion(out hi, out lo);
if (hr != 0)
{
Debug.Assert(hr == FUSION_E_INVALID_NAME);
return null;
}
return new Version((int)(hi >> 16), (int)(hi & 0xffff), (int)(lo >> 16), (int)(lo & 0xffff));
}
internal static Version GetVersion(IAssemblyName name, out AssemblyIdentityParts parts)
{
uint? major = GetPropertyWord(name, PropertyId.MAJOR_VERSION);
uint? minor = GetPropertyWord(name, PropertyId.MINOR_VERSION);
uint? build = GetPropertyWord(name, PropertyId.BUILD_NUMBER);
uint? revision = GetPropertyWord(name, PropertyId.REVISION_NUMBER);
parts = 0;
if (major != null)
{
parts |= AssemblyIdentityParts.VersionMajor;
}
if (minor != null)
{
parts |= AssemblyIdentityParts.VersionMinor;
}
if (build != null)
{
parts |= AssemblyIdentityParts.VersionBuild;
}
if (revision != null)
{
parts |= AssemblyIdentityParts.VersionRevision;
}
return new Version((int)(major ?? 0), (int)(minor ?? 0), (int)(build ?? 0), (int)(revision ?? 0));
}
internal static byte[] GetPublicKeyToken(IAssemblyName nameObject)
{
byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY_TOKEN);
if (result != null)
{
return result;
}
if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY_TOKEN))
{
return Array.Empty<byte>();
}
return null;
}
internal static byte[] GetPublicKey(IAssemblyName nameObject)
{
byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY);
if (result != null)
{
return result;
}
if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY))
{
return Array.Empty<byte>();
}
return null;
}
internal static unsafe uint? GetPropertyWord(IAssemblyName nameObject, PropertyId propertyId)
{
uint result;
uint size = sizeof(uint);
int hr = nameObject.GetProperty(propertyId, &result, ref size);
if (hr != 0)
{
throw Marshal.GetExceptionForHR(hr);
}
if (size == 0)
{
return null;
}
return result;
}
internal static string GetName(IAssemblyName nameObject)
{
return GetPropertyString(nameObject, PropertyId.NAME);
}
internal static string GetCulture(IAssemblyName nameObject)
{
return GetPropertyString(nameObject, PropertyId.CULTURE);
}
internal static AssemblyContentType GetContentType(IAssemblyName nameObject)
{
return (AssemblyContentType)(GetPropertyWord(nameObject, PropertyId.CONTENT_TYPE) ?? 0);
}
internal static ProcessorArchitecture GetProcessorArchitecture(IAssemblyName nameObject)
{
return (ProcessorArchitecture)(GetPropertyWord(nameObject, PropertyId.ARCHITECTURE) ?? 0);
}
internal static unsafe AssemblyNameFlags GetFlags(IAssemblyName nameObject)
{
AssemblyNameFlags result = 0;
uint retarget = GetPropertyWord(nameObject, PropertyId.RETARGET) ?? 0;
if (retarget != 0)
{
result |= AssemblyNameFlags.Retargetable;
}
return result;
}
private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, string data)
{
if (data == null)
{
nameObject.SetProperty(propertyId, null, 0);
}
else
{
Debug.Assert(data.IndexOf('\0') == -1);
fixed (char* p = data)
{
Debug.Assert(p[data.Length] == '\0');
// size is in bytes, include trailing \0 character:
nameObject.SetProperty(propertyId, p, (uint)(data.Length + 1) * 2);
}
}
}
private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, byte[] data)
{
if (data == null)
{
nameObject.SetProperty(propertyId, null, 0);
}
else
{
fixed (byte* p = data)
{
nameObject.SetProperty(propertyId, p, (uint)data.Length);
}
}
}
private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, ushort data)
{
nameObject.SetProperty(propertyId, &data, sizeof(ushort));
}
private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, uint data)
{
nameObject.SetProperty(propertyId, &data, sizeof(uint));
}
private static unsafe void SetPublicKeyToken(IAssemblyName nameObject, byte[] value)
{
// An empty public key token is set via NULL_PUBLIC_KEY_TOKEN property.
if (value != null && value.Length == 0)
{
nameObject.SetProperty(PropertyId.NULL_PUBLIC_KEY_TOKEN, null, 0);
}
else
{
SetProperty(nameObject, PropertyId.PUBLIC_KEY_TOKEN, value);
}
}
/// <summary>
/// Converts <see cref="IAssemblyName"/> to <see cref="AssemblyName"/> with all metadata fields filled.
/// </summary>
/// <returns>
/// Assembly name with Version, Culture and PublicKeyToken components filled in:
/// "SimpleName, Version=#.#.#.#, Culture=XXX, PublicKeyToken=XXXXXXXXXXXXXXXX".
/// In addition Retargetable flag and ContentType are set.
/// </returns>
internal static AssemblyIdentity ToAssemblyIdentity(IAssemblyName nameObject)
{
if (nameObject == null)
{
return null;
}
AssemblyNameFlags flags = GetFlags(nameObject);
byte[] publicKey = GetPublicKey(nameObject);
bool hasPublicKey = publicKey != null && publicKey.Length != 0;
AssemblyIdentityParts versionParts;
return new AssemblyIdentity(
GetName(nameObject),
GetVersion(nameObject, out versionParts),
GetCulture(nameObject) ?? "",
(hasPublicKey ? publicKey : GetPublicKeyToken(nameObject)).AsImmutableOrNull(),
hasPublicKey: hasPublicKey,
isRetargetable: (flags & AssemblyNameFlags.Retargetable) != 0,
contentType: GetContentType(nameObject));
}
/// <summary>
/// Converts <see cref="AssemblyName"/> to an equivalent <see cref="IAssemblyName"/>.
/// </summary>
internal static IAssemblyName ToAssemblyNameObject(AssemblyName name)
{
if (name == null)
{
return null;
}
IAssemblyName result;
Marshal.ThrowExceptionForHR(CreateAssemblyNameObject(out result, null, 0, IntPtr.Zero));
string assemblyName = name.Name;
if (assemblyName != null)
{
if (assemblyName.IndexOf('\0') >= 0)
{
#if SCRIPTING
throw new ArgumentException(Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name));
#elif EDITOR_FEATURES
throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name));
#else
throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name));
#endif
}
SetProperty(result, PropertyId.NAME, assemblyName);
}
if (name.Version != null)
{
SetProperty(result, PropertyId.MAJOR_VERSION, unchecked((ushort)name.Version.Major));
SetProperty(result, PropertyId.MINOR_VERSION, unchecked((ushort)name.Version.Minor));
SetProperty(result, PropertyId.BUILD_NUMBER, unchecked((ushort)name.Version.Build));
SetProperty(result, PropertyId.REVISION_NUMBER, unchecked((ushort)name.Version.Revision));
}
string cultureName = name.CultureName;
if (cultureName != null)
{
if (cultureName.IndexOf('\0') >= 0)
{
#if SCRIPTING
throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name));
#elif EDITOR_FEATURES
throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name));
#else
throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name));
#endif
}
SetProperty(result, PropertyId.CULTURE, cultureName);
}
if (name.Flags == AssemblyNameFlags.Retargetable)
{
SetProperty(result, PropertyId.RETARGET, 1U);
}
if (name.ContentType != AssemblyContentType.Default)
{
SetProperty(result, PropertyId.CONTENT_TYPE, (uint)name.ContentType);
}
byte[] token = name.GetPublicKeyToken();
SetPublicKeyToken(result, token);
return result;
}
/// <summary>
/// Creates <see cref="IAssemblyName"/> object by parsing given display name.
/// </summary>
internal static IAssemblyName ToAssemblyNameObject(string displayName)
{
// CLR doesn't handle \0 in the display name well:
if (displayName.IndexOf('\0') >= 0)
{
return null;
}
Debug.Assert(displayName != null);
IAssemblyName result;
int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero);
if (hr != 0)
{
return null;
}
Debug.Assert(result != null);
return result;
}
/// <summary>
/// Selects the candidate assembly with the largest version number. Uses culture as a tie-breaker if it is provided.
/// All candidates are assumed to have the same name and must include versions and cultures.
/// </summary>
internal static IAssemblyName GetBestMatch(IEnumerable<IAssemblyName> candidates, string preferredCultureOpt)
{
IAssemblyName bestCandidate = null;
Version bestVersion = null;
string bestCulture = null;
foreach (var candidate in candidates)
{
if (bestCandidate != null)
{
Version candidateVersion = GetVersion(candidate);
Debug.Assert(candidateVersion != null);
if (bestVersion == null)
{
bestVersion = GetVersion(bestCandidate);
Debug.Assert(bestVersion != null);
}
int cmp = bestVersion.CompareTo(candidateVersion);
if (cmp == 0)
{
if (preferredCultureOpt != null)
{
string candidateCulture = GetCulture(candidate);
Debug.Assert(candidateCulture != null);
if (bestCulture == null)
{
bestCulture = GetCulture(candidate);
Debug.Assert(bestCulture != null);
}
// we have exactly the preferred culture or
// we have neutral culture and the best candidate's culture isn't the preferred one:
if (StringComparer.OrdinalIgnoreCase.Equals(candidateCulture, preferredCultureOpt) ||
candidateCulture.Length == 0 && !StringComparer.OrdinalIgnoreCase.Equals(bestCulture, preferredCultureOpt))
{
bestCandidate = candidate;
bestVersion = candidateVersion;
bestCulture = candidateCulture;
}
}
}
else if (cmp < 0)
{
bestCandidate = candidate;
bestVersion = candidateVersion;
}
}
else
{
bestCandidate = candidate;
}
}
return bestCandidate;
}
}
}
| -1 |
dotnet/roslyn | 55,179 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | 2021-07-28T12:01:59Z | 2021-07-28T13:07:16Z | badcd003f616de451aa1ce04191f27c0be835c4d | af0313d42f845445623b2ee6865ac13ba1faf522 | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateEvent/GenerateEventTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateEvent
Public Class GenerateEventTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New GenerateEventCodeFixProvider())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventIntoInterface1() As Task
Await TestInRegularAndScriptAsync(
"Interface MyInterface
End Interface
Class C
Implements MyInterface
Event goo() Implements [|MyInterface.E|]
End Class",
"Interface MyInterface
Event E()
End Interface
Class C
Implements MyInterface
Event goo() Implements MyInterface.E
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestNotIfIdentifierMissing() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface MyInterface
End Interface
Class C
Implements MyInterface
Event goo() Implements [|MyInterface.|]
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestNotIfAlreadyPresent() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface MyInterface
Event E()
End Interface
Class C
Implements MyInterface
Event goo() Implements [|MyInterface.E|]
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventWithParameter() As Task
Await TestInRegularAndScriptAsync(
"Interface MyInterface
End Interface
Class C
Implements MyInterface
Event goo(x As Integer) Implements [|MyInterface.E|]
End Class",
"Interface MyInterface
Event E(x As Integer)
End Interface
Class C
Implements MyInterface
Event goo(x As Integer) Implements MyInterface.E
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestHandlesClause() As Task
Await TestInRegularAndScriptAsync(
"Class D
End Class
Class C
WithEvents a As D
Sub bar(x As Integer, e As Object) Handles [|a.E|]
End Sub
End Class",
"Class D
Public Event E(x As Integer, e As Object)
End Class
Class C
WithEvents a As D
Sub bar(x As Integer, e As Object) Handles a.E
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestHandlesClauseWithExistingEvent() As Task
Await TestMissingInRegularAndScriptAsync(
"Class D
Public Event E(x As Integer, e As Object)
End Class
Class C
WithEvents a As D
Sub bar(x As Integer, e As Object) Handles [|a.E|]
End Sub
End Class")
End Function
<WorkItem(531210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531210")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMyBase() As Task
Await TestInRegularAndScriptAsync(
"Public Class BaseClass
' Place methods and properties here.
End Class
Public Class DerivedClass
Inherits BaseClass
Sub EventHandler(ByVal x As Integer) Handles [|MyBase.BaseEvent|]
' Place code to handle events from BaseClass here.
End Sub
End Class",
"Public Class BaseClass
Public Event BaseEvent(x As Integer)
' Place methods and properties here.
End Class
Public Class DerivedClass
Inherits BaseClass
Sub EventHandler(ByVal x As Integer) Handles MyBase.BaseEvent
' Place code to handle events from BaseClass here.
End Sub
End Class")
End Function
<WorkItem(531210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531210")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMe() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub EventHandler(ByVal x As Integer) Handles [|Me.MyEvent|]
' Place code to handle events from BaseClass here.
End Sub
End Class",
"Public Class C
Public Event MyEvent(x As Integer)
Sub EventHandler(ByVal x As Integer) Handles Me.MyEvent
' Place code to handle events from BaseClass here.
End Sub
End Class")
End Function
<WorkItem(531210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531210")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMyClass() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub EventHandler(ByVal x As Integer) Handles [|MyClass.MyEvent|]
' Place code to handle events from BaseClass here.
End Sub
End Class",
"Public Class C
Public Event MyEvent(x As Integer)
Sub EventHandler(ByVal x As Integer) Handles MyClass.MyEvent
' Place code to handle events from BaseClass here.
End Sub
End Class")
End Function
<WorkItem(531251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531251")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestNotIfEventMemberMissing() As Task
Await TestMissingInRegularAndScriptAsync(
"Public Class A
End Class
Public Class C
Dim WithEvents x As A
Sub Hello(i As Integer) Handles [|x.|]'mark
End Sub
End Class")
End Function
<WorkItem(531267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531267")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMakeParamsNotOptional() As Task
Await TestInRegularAndScriptAsync(
"Public Class B
Dim WithEvents x As B
Private Sub Test(Optional x As String = Nothing) Handles [|x.E1|] 'mark 1
End Sub
Private Sub Test2(ParamArray x As String()) Handles x.E2 'mark 2
End Sub
End Class",
"Public Class B
Dim WithEvents x As B
Public Event E1(x As String)
Private Sub Test(Optional x As String = Nothing) Handles x.E1 'mark 1
End Sub
Private Sub Test2(ParamArray x As String()) Handles x.E2 'mark 2
End Sub
End Class")
End Function
<WorkItem(531267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531267")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMakeParamsNotParamArray() As Task
Await TestInRegularAndScriptAsync(
"Public Class B
Dim WithEvents x As B
Private Sub Test(Optional x As String = Nothing) Handles x.E1 'mark 1
End Sub
Private Sub Test2(ParamArray x As String()) Handles [|x.E2|] 'mark 2
End Sub
End Class",
"Public Class B
Dim WithEvents x As B
Public Event E2(x() As String)
Private Sub Test(Optional x As String = Nothing) Handles x.E1 'mark 1
End Sub
Private Sub Test2(ParamArray x As String()) Handles x.E2 'mark 2
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventStaticClass() As Task
Await TestInRegularAndScriptAsync(
"Class EventClass
Public Event ZEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|EventClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Class EventClass
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler EventClass.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventStaticClass() As Task
Await TestInRegularAndScriptAsync(
"Class EventClass
Public Event ZEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|EventClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Class EventClass
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler EventClass.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventVariable() As Task
Await TestInRegularAndScriptAsync(
"Class EventClass
Public Event ZEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|EClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Class EventClass
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler EClass.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventVariable() As Task
Await TestInRegularAndScriptAsync(
"Class EventClass
Public Event ZEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|EClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Class EventClass
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler EClass.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEvent() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEvent() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMe() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|Me.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler Me.XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMe() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|Me.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler Me.XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyClass() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|MyClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler MyClass.XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyClass() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|MyClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler MyClass.XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyBase() As Task
Await TestInRegularAndScriptAsync(
"Public Class EventClass
End Class
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class EventClass
Public Event XEvent()
End Class
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler MyBase.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyBase() As Task
Await TestInRegularAndScriptAsync(
"Public Class EventClass
End Class
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class EventClass
Public Event XEvent()
End Class
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler MyBase.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventDelegate() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class EventClass
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|EClass.XEvent|], EClass_EventHandler
End Sub
Dim EClass_EventHandler As Action = Sub()
End Sub
End Class",
"Imports System
Public Class EventClass
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler EClass.XEvent, EClass_EventHandler
End Sub
Dim EClass_EventHandler As Action = Sub()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventDelegate() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class EventClass
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|EClass.XEvent|], EClass_EventHandler
End Sub
Dim EClass_EventHandler As Action = Sub()
End Sub
End Class",
"Imports System
Public Class EventClass
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler EClass.XEvent, EClass_EventHandler
End Sub
Dim EClass_EventHandler As Action = Sub()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyBaseIntoCSharp() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler(argument As String)
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(string argument);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyBaseIntoCSharp() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler(argument As String)
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(string argument);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyBaseIntoCSharpGeneric() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler(Of EventArgs)
End Sub
Sub EClass_EventHandler(Of T)(sender As Object, e As T)
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
using System;
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(object sender, EventArgs e);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyBaseIntoCSharpGeneric() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler(Of EventArgs)
End Sub
Sub EClass_EventHandler(Of T)(sender As Object, e As T)
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
using System;
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(object sender, EventArgs e);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMultiLineLambdaIntoCSharp() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|EClass.XEvent|], Sub(a As Object, b As EventArgs)
End Sub
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
using System;
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(object a, EventArgs b);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMultiLineLambdaIntoCSharp() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|EClass.XEvent|], Sub(a As Object, b As EventArgs)
End Sub
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
using System;
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(object a, EventArgs b);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyBaseIntoCSharpGenericExistingDelegate() As Task
Dim initialMarkup =
"<Workspace>
<Project Language=""Visual Basic"" CommonReferences=""true"">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler(Of EventArgs)
End Sub
Sub EClass_EventHandler(Of T)(sender As Object, e As T)
End Sub
End Class
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<Document>
using System;
public class EventClass
{
public event XEventHandler ZEvent;
}
public delegate void XEventHandler(object sender, EventArgs e);
</Document>
</Project>
</Workspace>"
Await TestMissingInRegularAndScriptAsync(initialMarkup)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyBaseIntoCSharpGenericExistingDelegate() As Task
Dim initialMarkup =
"<Workspace>
<Project Language=""Visual Basic"" CommonReferences=""True"">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler(Of EventArgs)
End Sub
Sub EClass_EventHandler(Of T)(sender As Object, e As T)
End Sub
End Class
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""True"">
<Document>
using System;
public class EventClass
{
public event XEventHandler ZEvent;
}
public delegate void XEventHandler(object sender, EventArgs e);
</Document>
</Project>
</Workspace>"
Await TestMissingInRegularAndScriptAsync(initialMarkup)
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.VisualBasic.CodeFixes.GenerateEvent
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateEvent
Public Class GenerateEventTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New GenerateEventCodeFixProvider())
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventIntoInterface1() As Task
Await TestInRegularAndScriptAsync(
"Interface MyInterface
End Interface
Class C
Implements MyInterface
Event goo() Implements [|MyInterface.E|]
End Class",
"Interface MyInterface
Event E()
End Interface
Class C
Implements MyInterface
Event goo() Implements MyInterface.E
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestNotIfIdentifierMissing() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface MyInterface
End Interface
Class C
Implements MyInterface
Event goo() Implements [|MyInterface.|]
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestNotIfAlreadyPresent() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface MyInterface
Event E()
End Interface
Class C
Implements MyInterface
Event goo() Implements [|MyInterface.E|]
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventWithParameter() As Task
Await TestInRegularAndScriptAsync(
"Interface MyInterface
End Interface
Class C
Implements MyInterface
Event goo(x As Integer) Implements [|MyInterface.E|]
End Class",
"Interface MyInterface
Event E(x As Integer)
End Interface
Class C
Implements MyInterface
Event goo(x As Integer) Implements MyInterface.E
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestHandlesClause() As Task
Await TestInRegularAndScriptAsync(
"Class D
End Class
Class C
WithEvents a As D
Sub bar(x As Integer, e As Object) Handles [|a.E|]
End Sub
End Class",
"Class D
Public Event E(x As Integer, e As Object)
End Class
Class C
WithEvents a As D
Sub bar(x As Integer, e As Object) Handles a.E
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestHandlesClauseWithExistingEvent() As Task
Await TestMissingInRegularAndScriptAsync(
"Class D
Public Event E(x As Integer, e As Object)
End Class
Class C
WithEvents a As D
Sub bar(x As Integer, e As Object) Handles [|a.E|]
End Sub
End Class")
End Function
<WorkItem(531210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531210")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMyBase() As Task
Await TestInRegularAndScriptAsync(
"Public Class BaseClass
' Place methods and properties here.
End Class
Public Class DerivedClass
Inherits BaseClass
Sub EventHandler(ByVal x As Integer) Handles [|MyBase.BaseEvent|]
' Place code to handle events from BaseClass here.
End Sub
End Class",
"Public Class BaseClass
Public Event BaseEvent(x As Integer)
' Place methods and properties here.
End Class
Public Class DerivedClass
Inherits BaseClass
Sub EventHandler(ByVal x As Integer) Handles MyBase.BaseEvent
' Place code to handle events from BaseClass here.
End Sub
End Class")
End Function
<WorkItem(531210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531210")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMe() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub EventHandler(ByVal x As Integer) Handles [|Me.MyEvent|]
' Place code to handle events from BaseClass here.
End Sub
End Class",
"Public Class C
Public Event MyEvent(x As Integer)
Sub EventHandler(ByVal x As Integer) Handles Me.MyEvent
' Place code to handle events from BaseClass here.
End Sub
End Class")
End Function
<WorkItem(531210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531210")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMyClass() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub EventHandler(ByVal x As Integer) Handles [|MyClass.MyEvent|]
' Place code to handle events from BaseClass here.
End Sub
End Class",
"Public Class C
Public Event MyEvent(x As Integer)
Sub EventHandler(ByVal x As Integer) Handles MyClass.MyEvent
' Place code to handle events from BaseClass here.
End Sub
End Class")
End Function
<WorkItem(531251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531251")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestNotIfEventMemberMissing() As Task
Await TestMissingInRegularAndScriptAsync(
"Public Class A
End Class
Public Class C
Dim WithEvents x As A
Sub Hello(i As Integer) Handles [|x.|]'mark
End Sub
End Class")
End Function
<WorkItem(531267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531267")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMakeParamsNotOptional() As Task
Await TestInRegularAndScriptAsync(
"Public Class B
Dim WithEvents x As B
Private Sub Test(Optional x As String = Nothing) Handles [|x.E1|] 'mark 1
End Sub
Private Sub Test2(ParamArray x As String()) Handles x.E2 'mark 2
End Sub
End Class",
"Public Class B
Dim WithEvents x As B
Public Event E1(x As String)
Private Sub Test(Optional x As String = Nothing) Handles x.E1 'mark 1
End Sub
Private Sub Test2(ParamArray x As String()) Handles x.E2 'mark 2
End Sub
End Class")
End Function
<WorkItem(531267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531267")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestMakeParamsNotParamArray() As Task
Await TestInRegularAndScriptAsync(
"Public Class B
Dim WithEvents x As B
Private Sub Test(Optional x As String = Nothing) Handles x.E1 'mark 1
End Sub
Private Sub Test2(ParamArray x As String()) Handles [|x.E2|] 'mark 2
End Sub
End Class",
"Public Class B
Dim WithEvents x As B
Public Event E2(x() As String)
Private Sub Test(Optional x As String = Nothing) Handles x.E1 'mark 1
End Sub
Private Sub Test2(ParamArray x As String()) Handles x.E2 'mark 2
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventStaticClass() As Task
Await TestInRegularAndScriptAsync(
"Class EventClass
Public Event ZEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|EventClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Class EventClass
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler EventClass.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventStaticClass() As Task
Await TestInRegularAndScriptAsync(
"Class EventClass
Public Event ZEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|EventClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Class EventClass
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler EventClass.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventVariable() As Task
Await TestInRegularAndScriptAsync(
"Class EventClass
Public Event ZEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|EClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Class EventClass
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler EClass.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventVariable() As Task
Await TestInRegularAndScriptAsync(
"Class EventClass
Public Event ZEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|EClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Class EventClass
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler EClass.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEvent() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEvent() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMe() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|Me.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler Me.XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMe() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|Me.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler Me.XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyClass() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|MyClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler MyClass.XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyClass() As Task
Await TestInRegularAndScriptAsync(
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|MyClass.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler MyClass.XEvent, AddressOf EClass_EventHandler
End Sub
Public Event XEvent()
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyBase() As Task
Await TestInRegularAndScriptAsync(
"Public Class EventClass
End Class
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class EventClass
Public Event XEvent()
End Class
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler MyBase.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyBase() As Task
Await TestInRegularAndScriptAsync(
"Public Class EventClass
End Class
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class",
"Public Class EventClass
Public Event XEvent()
End Class
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler MyBase.XEvent, AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventDelegate() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class EventClass
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|EClass.XEvent|], EClass_EventHandler
End Sub
Dim EClass_EventHandler As Action = Sub()
End Sub
End Class",
"Imports System
Public Class EventClass
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler EClass.XEvent, EClass_EventHandler
End Sub
Dim EClass_EventHandler As Action = Sub()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventDelegate() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class EventClass
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|EClass.XEvent|], EClass_EventHandler
End Sub
Dim EClass_EventHandler As Action = Sub()
End Sub
End Class",
"Imports System
Public Class EventClass
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler EClass.XEvent, EClass_EventHandler
End Sub
Dim EClass_EventHandler As Action = Sub()
End Sub
End Class")
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyBaseIntoCSharp() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler(argument As String)
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(string argument);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyBaseIntoCSharp() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler
End Sub
Sub EClass_EventHandler(argument As String)
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(string argument);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyBaseIntoCSharpGeneric() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler(Of EventArgs)
End Sub
Sub EClass_EventHandler(Of T)(sender As Object, e As T)
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
using System;
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(object sender, EventArgs e);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyBaseIntoCSharpGeneric() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler(Of EventArgs)
End Sub
Sub EClass_EventHandler(Of T)(sender As Object, e As T)
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
using System;
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(object sender, EventArgs e);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMultiLineLambdaIntoCSharp() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
AddHandler [|EClass.XEvent|], Sub(a As Object, b As EventArgs)
End Sub
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
using System;
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(object a, EventArgs b);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMultiLineLambdaIntoCSharp() As Task
Dim initialMarkup =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
WithEvents EClass As New EventClass
Public Sub New()
RemoveHandler [|EClass.XEvent|], Sub(a As Object, b As EventArgs)
End Sub
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document>
public class EventClass
{
}
</Document>
</Project>
</Workspace>.ToString()
Dim expected =
<Text>
using System;
public class EventClass
{
public event XEventHandler XEvent;
}
public delegate void XEventHandler(object a, EventArgs b);
</Text>.NormalizedValue
Await TestInRegularAndScriptAsync(initialMarkup, expected)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForAddEventMyBaseIntoCSharpGenericExistingDelegate() As Task
Dim initialMarkup =
"<Workspace>
<Project Language=""Visual Basic"" CommonReferences=""true"">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
Inherits EventClass
Public Sub New()
AddHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler(Of EventArgs)
End Sub
Sub EClass_EventHandler(Of T)(sender As Object, e As T)
End Sub
End Class
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true"">
<Document>
using System;
public class EventClass
{
public event XEventHandler ZEvent;
}
public delegate void XEventHandler(object sender, EventArgs e);
</Document>
</Project>
</Workspace>"
Await TestMissingInRegularAndScriptAsync(initialMarkup)
End Function
<WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventForRemoveEventMyBaseIntoCSharpGenericExistingDelegate() As Task
Dim initialMarkup =
"<Workspace>
<Project Language=""Visual Basic"" CommonReferences=""True"">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Imports System
Public Class Test
Inherits EventClass
Public Sub New()
RemoveHandler [|MyBase.XEvent|], AddressOf EClass_EventHandler(Of EventArgs)
End Sub
Sub EClass_EventHandler(Of T)(sender As Object, e As T)
End Sub
End Class
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""True"">
<Document>
using System;
public class EventClass
{
public event XEventHandler ZEvent;
}
public delegate void XEventHandler(object sender, EventArgs e);
</Document>
</Project>
</Workspace>"
Await TestMissingInRegularAndScriptAsync(initialMarkup)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,179 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | 2021-07-28T12:01:59Z | 2021-07-28T13:07:16Z | badcd003f616de451aa1ce04191f27c0be835c4d | af0313d42f845445623b2ee6865ac13ba1faf522 | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodGroup.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
// pooled class used for input to overload resolution
internal sealed class MethodGroup
{
internal BoundExpression Receiver { get; private set; }
internal ArrayBuilder<MethodSymbol> Methods { get; }
internal ArrayBuilder<TypeWithAnnotations> TypeArguments { get; }
internal bool IsExtensionMethodGroup { get; private set; }
internal DiagnosticInfo Error { get; private set; }
internal LookupResultKind ResultKind { get; private set; }
private MethodGroup()
{
this.Methods = new ArrayBuilder<MethodSymbol>();
this.TypeArguments = new ArrayBuilder<TypeWithAnnotations>();
}
internal void PopulateWithSingleMethod(
BoundExpression receiverOpt,
MethodSymbol method,
LookupResultKind resultKind = LookupResultKind.Viable,
DiagnosticInfo error = null)
{
this.PopulateHelper(receiverOpt, resultKind, error);
this.Methods.Add(method);
}
internal void PopulateWithExtensionMethods(
BoundExpression receiverOpt,
ArrayBuilder<Symbol> members,
ImmutableArray<TypeWithAnnotations> typeArguments,
LookupResultKind resultKind = LookupResultKind.Viable,
DiagnosticInfo error = null)
{
this.PopulateHelper(receiverOpt, resultKind, error);
this.IsExtensionMethodGroup = true;
foreach (var member in members)
{
this.Methods.Add((MethodSymbol)member);
}
if (!typeArguments.IsDefault)
{
this.TypeArguments.AddRange(typeArguments);
}
}
internal void PopulateWithNonExtensionMethods(
BoundExpression receiverOpt,
ImmutableArray<MethodSymbol> methods,
ImmutableArray<TypeWithAnnotations> typeArguments,
LookupResultKind resultKind = LookupResultKind.Viable,
DiagnosticInfo error = null)
{
this.PopulateHelper(receiverOpt, resultKind, error);
this.Methods.AddRange(methods);
if (!typeArguments.IsDefault)
{
this.TypeArguments.AddRange(typeArguments);
}
}
private void PopulateHelper(BoundExpression receiverOpt, LookupResultKind resultKind, DiagnosticInfo error)
{
VerifyClear();
this.Receiver = receiverOpt;
this.Error = error;
this.ResultKind = resultKind;
}
public void Clear()
{
this.Receiver = null;
this.Methods.Clear();
this.TypeArguments.Clear();
this.IsExtensionMethodGroup = false;
this.Error = null;
this.ResultKind = LookupResultKind.Empty;
VerifyClear();
}
public string Name
{
get
{
return this.Methods.Count > 0 ? this.Methods[0].Name : null;
}
}
public BoundExpression InstanceOpt
{
get
{
if (this.Receiver == null)
{
return null;
}
if (this.Receiver.Kind == BoundKind.TypeExpression)
{
return null;
}
return this.Receiver;
}
}
[Conditional("DEBUG")]
private void VerifyClear()
{
Debug.Assert(this.Receiver == null);
Debug.Assert(this.Methods.Count == 0);
Debug.Assert(this.TypeArguments.Count == 0);
Debug.Assert(!this.IsExtensionMethodGroup);
Debug.Assert(this.Error == null);
Debug.Assert(this.ResultKind == LookupResultKind.Empty);
}
#region "Poolable"
public static MethodGroup GetInstance()
{
return Pool.Allocate();
}
public void Free()
{
this.Clear();
Pool.Free(this);
}
//2) Expose the pool or the way to create a pool or the way to get an instance.
// for now we will expose both and figure which way works better
public static readonly ObjectPool<MethodGroup> Pool = CreatePool();
private static ObjectPool<MethodGroup> CreatePool()
{
ObjectPool<MethodGroup> pool = null;
pool = new ObjectPool<MethodGroup>(() => new MethodGroup(), 10);
return pool;
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
// pooled class used for input to overload resolution
internal sealed class MethodGroup
{
internal BoundExpression Receiver { get; private set; }
internal ArrayBuilder<MethodSymbol> Methods { get; }
internal ArrayBuilder<TypeWithAnnotations> TypeArguments { get; }
internal bool IsExtensionMethodGroup { get; private set; }
internal DiagnosticInfo Error { get; private set; }
internal LookupResultKind ResultKind { get; private set; }
private MethodGroup()
{
this.Methods = new ArrayBuilder<MethodSymbol>();
this.TypeArguments = new ArrayBuilder<TypeWithAnnotations>();
}
internal void PopulateWithSingleMethod(
BoundExpression receiverOpt,
MethodSymbol method,
LookupResultKind resultKind = LookupResultKind.Viable,
DiagnosticInfo error = null)
{
this.PopulateHelper(receiverOpt, resultKind, error);
this.Methods.Add(method);
}
internal void PopulateWithExtensionMethods(
BoundExpression receiverOpt,
ArrayBuilder<Symbol> members,
ImmutableArray<TypeWithAnnotations> typeArguments,
LookupResultKind resultKind = LookupResultKind.Viable,
DiagnosticInfo error = null)
{
this.PopulateHelper(receiverOpt, resultKind, error);
this.IsExtensionMethodGroup = true;
foreach (var member in members)
{
this.Methods.Add((MethodSymbol)member);
}
if (!typeArguments.IsDefault)
{
this.TypeArguments.AddRange(typeArguments);
}
}
internal void PopulateWithNonExtensionMethods(
BoundExpression receiverOpt,
ImmutableArray<MethodSymbol> methods,
ImmutableArray<TypeWithAnnotations> typeArguments,
LookupResultKind resultKind = LookupResultKind.Viable,
DiagnosticInfo error = null)
{
this.PopulateHelper(receiverOpt, resultKind, error);
this.Methods.AddRange(methods);
if (!typeArguments.IsDefault)
{
this.TypeArguments.AddRange(typeArguments);
}
}
private void PopulateHelper(BoundExpression receiverOpt, LookupResultKind resultKind, DiagnosticInfo error)
{
VerifyClear();
this.Receiver = receiverOpt;
this.Error = error;
this.ResultKind = resultKind;
}
public void Clear()
{
this.Receiver = null;
this.Methods.Clear();
this.TypeArguments.Clear();
this.IsExtensionMethodGroup = false;
this.Error = null;
this.ResultKind = LookupResultKind.Empty;
VerifyClear();
}
public string Name
{
get
{
return this.Methods.Count > 0 ? this.Methods[0].Name : null;
}
}
public BoundExpression InstanceOpt
{
get
{
if (this.Receiver == null)
{
return null;
}
if (this.Receiver.Kind == BoundKind.TypeExpression)
{
return null;
}
return this.Receiver;
}
}
[Conditional("DEBUG")]
private void VerifyClear()
{
Debug.Assert(this.Receiver == null);
Debug.Assert(this.Methods.Count == 0);
Debug.Assert(this.TypeArguments.Count == 0);
Debug.Assert(!this.IsExtensionMethodGroup);
Debug.Assert(this.Error == null);
Debug.Assert(this.ResultKind == LookupResultKind.Empty);
}
#region "Poolable"
public static MethodGroup GetInstance()
{
return Pool.Allocate();
}
public void Free()
{
this.Clear();
Pool.Free(this);
}
//2) Expose the pool or the way to create a pool or the way to get an instance.
// for now we will expose both and figure which way works better
public static readonly ObjectPool<MethodGroup> Pool = CreatePool();
private static ObjectPool<MethodGroup> CreatePool()
{
ObjectPool<MethodGroup> pool = null;
pool = new ObjectPool<MethodGroup>(() => new MethodGroup(), 10);
return pool;
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,179 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | 2021-07-28T12:01:59Z | 2021-07-28T13:07:16Z | badcd003f616de451aa1ce04191f27c0be835c4d | af0313d42f845445623b2ee6865ac13ba1faf522 | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Test/Semantic/Semantics/BindingAsyncTasklikeMoreTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingAsyncTasklikeMoreTests : CompilingTestBase
{
[Fact]
public void AsyncMethod()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M()
{
await F();
return await G(3);
}
static void Main()
{
var i = M().Result;
Console.WriteLine(i);
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask
{
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
struct MyTask<T>
{
internal T _result;
public T Result => _result;
internal Awaiter GetAwaiter() => new Awaiter(this);
internal class Awaiter : INotifyCompletion
{
private readonly MyTask<T> _task;
internal Awaiter(MyTask<T> task) { _task = task; }
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => _task.Result;
}
}
struct MyTaskMethodBuilder
{
private MyTask _task;
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(new MyTask());
internal MyTaskMethodBuilder(MyTask task)
{
_task = task;
}
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => _task;
}
struct MyTaskMethodBuilder<T>
{
private MyTask<T> _task;
public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(new MyTask<T>());
internal MyTaskMethodBuilder(MyTask<T> task)
{
_task = task;
}
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult(T t) { _task._result = t; }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => _task;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(compilation, expectedOutput: "3");
verifier.VerifyDiagnostics();
var testData = verifier.TestData;
var method = (MethodSymbol)testData.GetMethodData("C.F()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningTask(compilation));
method = (MethodSymbol)testData.GetMethodData("C.G<T>(T)").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningGenericTask(compilation));
verifier.VerifyIL("C.F()",
@"{
// Code size 49 (0x31)
.maxstack 2
.locals init (C.<F>d__0 V_0)
IL_0000: newobj ""C.<F>d__0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call ""MyTaskMethodBuilder MyTaskMethodBuilder.Create()""
IL_000c: stfld ""MyTaskMethodBuilder C.<F>d__0.<>t__builder""
IL_0011: ldloc.0
IL_0012: ldc.i4.m1
IL_0013: stfld ""int C.<F>d__0.<>1__state""
IL_0018: ldloc.0
IL_0019: ldflda ""MyTaskMethodBuilder C.<F>d__0.<>t__builder""
IL_001e: ldloca.s V_0
IL_0020: call ""void MyTaskMethodBuilder.Start<C.<F>d__0>(ref C.<F>d__0)""
IL_0025: ldloc.0
IL_0026: ldflda ""MyTaskMethodBuilder C.<F>d__0.<>t__builder""
IL_002b: call ""MyTask MyTaskMethodBuilder.Task.get""
IL_0030: ret
}");
verifier.VerifyIL("C.G<T>(T)",
@"{
// Code size 56 (0x38)
.maxstack 2
.locals init (C.<G>d__1<T> V_0)
IL_0000: newobj ""C.<G>d__1<T>..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call ""MyTaskMethodBuilder<T> MyTaskMethodBuilder<T>.Create()""
IL_000c: stfld ""MyTaskMethodBuilder<T> C.<G>d__1<T>.<>t__builder""
IL_0011: ldloc.0
IL_0012: ldarg.0
IL_0013: stfld ""T C.<G>d__1<T>.t""
IL_0018: ldloc.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<G>d__1<T>.<>1__state""
IL_001f: ldloc.0
IL_0020: ldflda ""MyTaskMethodBuilder<T> C.<G>d__1<T>.<>t__builder""
IL_0025: ldloca.s V_0
IL_0027: call ""void MyTaskMethodBuilder<T>.Start<C.<G>d__1<T>>(ref C.<G>d__1<T>)""
IL_002c: ldloc.0
IL_002d: ldflda ""MyTaskMethodBuilder<T> C.<G>d__1<T>.<>t__builder""
IL_0032: call ""MyTask<T> MyTaskMethodBuilder<T>.Task.get""
IL_0037: ret
}");
}
[Fact]
public void AsyncMethod_CreateHasRefReturn()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M() { await F(); return await G(3); }
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask
{
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
struct MyTask<T>
{
internal T _result;
public T Result => _result;
internal Awaiter GetAwaiter() => new Awaiter(this);
internal class Awaiter : INotifyCompletion
{
private readonly MyTask<T> _task;
internal Awaiter(MyTask<T> task) { _task = task; }
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => _task.Result;
}
}
struct MyTaskMethodBuilder
{
private MyTask _task;
public static ref MyTaskMethodBuilder Create() => throw null;
internal MyTaskMethodBuilder(MyTask task) { _task = task; }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => _task;
}
struct MyTaskMethodBuilder<T>
{
private MyTask<T> _task;
public static ref MyTaskMethodBuilder<T> Create() => throw null;
internal MyTaskMethodBuilder(MyTask<T> task) { _task = task; }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); }
public void SetException(Exception e) { }
public void SetResult(T t) { _task._result = t; }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => _task;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (6,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilder.Create'
// static async MyTask F() { await Task.Delay(0); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("MyTaskMethodBuilder", "Create").WithLocation(6, 29),
// (7,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<T>.Create'
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); return t; }").WithArguments("MyTaskMethodBuilder<T>", "Create").WithLocation(7, 38),
// (8,34): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<int>.Create'
// static async MyTask<int> M() { await F(); return await G(3); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await F(); return await G(3); }").WithArguments("MyTaskMethodBuilder<int>", "Create").WithLocation(8, 34)
);
}
[Fact]
public void AsyncMethod_BuilderFactoryDisallowed()
{
// Only method-level builder overrides allow having Create() return a different builder
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M() { await F(); return await G(3); }
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilderFactory))]
struct MyTask
{
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilderFactory<>))]
struct MyTask<T>
{
internal T _result;
public T Result => _result;
internal Awaiter GetAwaiter() => new Awaiter(this);
internal class Awaiter : INotifyCompletion
{
private readonly MyTask<T> _task;
internal Awaiter(MyTask<T> task) { _task = task; }
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => _task.Result;
}
}
struct MyTaskMethodBuilderFactory
{
public static MyTaskMethodBuilder Create() => throw null;
}
struct MyTaskMethodBuilder
{
private MyTask _task;
internal MyTaskMethodBuilder(MyTask task) { _task = task; }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => _task;
}
struct MyTaskMethodBuilderFactory<T>
{
public static MyTaskMethodBuilder<T> Create() => throw null;
}
struct MyTaskMethodBuilder<T>
{
private MyTask<T> _task;
internal MyTaskMethodBuilder(MyTask<T> task) { _task = task; }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); }
public void SetException(Exception e) { }
public void SetResult(T t) { _task._result = t; }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => _task;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (6,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory.Task'
// static async MyTask F() { await Task.Delay(0); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("MyTaskMethodBuilderFactory", "Task").WithLocation(6, 29),
// (6,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory.Create'
// static async MyTask F() { await Task.Delay(0); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("MyTaskMethodBuilderFactory", "Create").WithLocation(6, 29),
// (7,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory<T>.Task'
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); return t; }").WithArguments("MyTaskMethodBuilderFactory<T>", "Task").WithLocation(7, 38),
// (7,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory<T>.Create'
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); return t; }").WithArguments("MyTaskMethodBuilderFactory<T>", "Create").WithLocation(7, 38),
// (8,34): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory<int>.Task'
// static async MyTask<int> M() { await F(); return await G(3); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await F(); return await G(3); }").WithArguments("MyTaskMethodBuilderFactory<int>", "Task").WithLocation(8, 34),
// (8,34): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory<int>.Create'
// static async MyTask<int> M() { await F(); return await G(3); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await F(); return await G(3); }").WithArguments("MyTaskMethodBuilderFactory<int>", "Create").WithLocation(8, 34)
);
}
[Fact]
public void AsyncMethodBuilder_MissingMethods()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
static async MyTask F() { await (Task)null; }
static async MyTask<T> G<T>(T t) { await (Task)null; return t; }
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask { }
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
struct MyTask<T> { }
struct MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
}
struct MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>();
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task { get { return default(MyTask<T>); } }
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (6,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilder.Task'
// static async MyTask F() { await (Task)null; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await (Task)null; }").WithArguments("MyTaskMethodBuilder", "Task").WithLocation(6, 29),
// (7,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<T>.SetException'
// static async MyTask<T> G<T>(T t) { await (Task)null; return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await (Task)null; return t; }").WithArguments("MyTaskMethodBuilder<T>", "SetException").WithLocation(7, 38));
}
[Fact]
public void Private()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
#pragma warning disable CS1998
static async MyTask F() { }
static async MyTask<int> G() { return 3; }
#pragma warning restore CS1998
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
private class MyTask { }
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
private class MyTask<T> { }
private class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task { get { return null; } }
}
private class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task { get { return null; } }
}
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
var verifier = CompileAndVerify(compilation);
verifier.VerifyDiagnostics();
var testData = verifier.TestData;
var method = (MethodSymbol)testData.GetMethodData("C.F()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningTask(compilation));
Assert.Equal("C.MyTask", method.ReturnTypeWithAnnotations.ToDisplayString());
method = (MethodSymbol)testData.GetMethodData("C.G()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningGenericTask(compilation));
Assert.Equal("C.MyTask<int>", method.ReturnTypeWithAnnotations.ToDisplayString());
}
[Fact]
public void AsyncLambda_InferReturnType()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static void F(Func<MyTask> f) { }
static void F<T>(Func<MyTask<T>> f) { }
static void F(Func<MyTask<string>> f) { }
static void M()
{
#pragma warning disable CS1998
F(async () => { });
F(async () => { return 3; });
F(async () => { return string.Empty; });
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
class MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
var verifier = CompileAndVerify(compilation);
verifier.VerifyDiagnostics();
var testData = verifier.TestData;
var method = (MethodSymbol)testData.GetMethodData("C.<>c.<M>b__3_0()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningTask(compilation));
Assert.Equal("MyTask", method.ReturnTypeWithAnnotations.ToDisplayString());
method = (MethodSymbol)testData.GetMethodData("C.<>c.<M>b__3_1()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningGenericTask(compilation));
Assert.Equal("MyTask<int>", method.ReturnTypeWithAnnotations.ToDisplayString());
}
[Fact]
public void AsyncLocalFunction()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static async void M()
{
#pragma warning disable CS1998
async MyTask F() { }
async MyTask<T> G<T>(T t) => t;
await F();
await G(3);
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
struct MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
var verifier = CompileAndVerify(compilation);
verifier.VerifyDiagnostics();
var testData = verifier.TestData;
var method = (MethodSymbol)testData.GetMethodData("C.<M>g__F|0_0()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningTask(compilation));
Assert.Equal("MyTask", method.ReturnTypeWithAnnotations.ToDisplayString());
method = (MethodSymbol)testData.GetMethodData("C.<M>g__G|0_1<T>(T)").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningGenericTask(compilation));
Assert.Equal("MyTask<T>", method.ReturnTypeWithAnnotations.ToDisplayString());
}
[Fact]
public void Dynamic()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static void F<T>(Func<MyTask<T>> f) { }
static void G(Func<MyTask<dynamic>> f) { }
static void M(object o)
{
#pragma warning disable CS1998
F(async () => (dynamic)o);
F(async () => new[] { (dynamic)o });
G(async () => o);
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source, references: new MetadataReference[] { CSharpRef, SystemCoreRef });
var verifier = CompileAndVerify(
compilation,
expectedSignatures: new[]
{
Signature(
"C+<>c__DisplayClass2_0",
"<M>b__0",
".method [System.Runtime.CompilerServices.AsyncStateMachineAttribute(C+<>c__DisplayClass2_0+<<M>b__0>d)] assembly hidebysig instance [System.Runtime.CompilerServices.DynamicAttribute(System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] MyTask`1[System.Object] <M>b__0() cil managed"),
Signature(
"C+<>c__DisplayClass2_0",
"<M>b__1",
".method [System.Runtime.CompilerServices.AsyncStateMachineAttribute(C+<>c__DisplayClass2_0+<<M>b__1>d)] assembly hidebysig instance [System.Runtime.CompilerServices.DynamicAttribute(System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] MyTask`1[System.Object[]] <M>b__1() cil managed"),
Signature(
"C+<>c__DisplayClass2_0",
"<M>b__2",
".method [System.Runtime.CompilerServices.AsyncStateMachineAttribute(C+<>c__DisplayClass2_0+<<M>b__2>d)] assembly hidebysig instance [System.Runtime.CompilerServices.DynamicAttribute(System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] MyTask`1[System.Object] <M>b__2() cil managed"),
});
verifier.VerifyDiagnostics();
}
[Fact]
public void NonTaskBuilder()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static async void M()
{
#pragma warning disable CS1998
async MyTask F() { };
await F();
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(string))]
public struct MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (8,26): error CS0656: Missing compiler required member 'string.Task'
// async MyTask F() { };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ }").WithArguments("string", "Task").WithLocation(8, 26),
// (8,26): error CS0656: Missing compiler required member 'string.Create'
// async MyTask F() { };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ }").WithArguments("string", "Create").WithLocation(8, 26));
}
[Fact]
public void NonTaskBuilderOfT()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static async void M()
{
#pragma warning disable CS1998
async MyTask<T> F<T>(T t) => t;
await F(3);
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(IEquatable<>))]
public struct MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (8,35): error CS0656: Missing compiler required member 'IEquatable<T>.Task'
// async MyTask<T> F<T>(T t) => t;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> t").WithArguments("System.IEquatable<T>", "Task").WithLocation(8, 35),
// (8,35): error CS0656: Missing compiler required member 'IEquatable<T>.Create'
// async MyTask<T> F<T>(T t) => t;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> t").WithArguments("System.IEquatable<T>", "Create").WithLocation(8, 35));
}
[Fact]
public void NonTaskBuilder_Array()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static async void M()
{
#pragma warning disable CS1998
async MyTask F() { };
await F();
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(object[]))]
struct MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (8,22): error CS1983: The return type of an async method must be void, Task or Task<T>
// async MyTask F() { };
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "{ }").WithLocation(8, 26));
}
[Fact]
public static void AsyncMethodBuilderAttributeMultipleParameters()
{
var source = @"
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
[AsyncMethodBuilder(typeof(B1),1)] class T1 { }
class B1 { }
[AsyncMethodBuilder(typeof(B2))] class T2 { }
class B2 { }
class Program {
static void Main() { }
async T1 f1() => await Task.Delay(1);
async T2 f2() => await Task.Delay(1);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t, int i) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (8,2): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'AsyncMethodBuilderAttribute.AsyncMethodBuilderAttribute(Type, int)'
// [AsyncMethodBuilder(typeof(B2))] class T2 { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AsyncMethodBuilder(typeof(B2))").WithArguments("i", "System.Runtime.CompilerServices.AsyncMethodBuilderAttribute.AsyncMethodBuilderAttribute(System.Type, int)").WithLocation(8, 2),
// (13,14): error CS1983: The return type of an async method must be void, Task or Task<T>
// async T1 f1() => await Task.Delay(1);
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f1").WithLocation(13, 14),
// (14,14): error CS1983: The return type of an async method must be void, Task or Task<T>
// async T2 f2() => await Task.Delay(1);
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f2").WithLocation(14, 14)
);
}
[Fact]
public static void AsyncMethodBuilderAttributeSingleParameterWrong()
{
var source = @"
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
[AsyncMethodBuilder(1)] class T { }
class Program {
static void Main() { }
async T f() => await Task.Delay(1);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(int i) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (9,13): error CS1983: The return type of an async method must be void, Task or Task<T>
// async T f() => await Task.Delay(1);
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f").WithLocation(9, 13)
);
}
[Fact]
public void AsyncMethodBuilder_IncorrectMethodArity()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : System.Attribute
{
public AsyncMethodBuilderAttribute(System.Type t) { }
}
}
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M()
{
await F();
return await G(3);
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
class MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
internal MyTaskMethodBuilder(MyTask task) { }
public void SetStateMachine<T>(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
internal MyTaskMethodBuilder(MyTask<T> task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TAwaiter, TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
compilation.VerifyEmitDiagnostics(
// (13,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilder.SetStateMachine'
// static async MyTask F() { await Task.Delay(0); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("MyTaskMethodBuilder", "SetStateMachine").WithLocation(13, 29),
// (14,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<T>.Start'
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); return t; }").WithArguments("MyTaskMethodBuilder<T>", "Start").WithLocation(14, 38),
// (16,5): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<int>.Start'
// {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"{
await F();
return await G(3);
}").WithArguments("MyTaskMethodBuilder<int>", "Start").WithLocation(16, 5));
}
[WorkItem(12616, "https://github.com/dotnet/roslyn/issues/12616")]
[Fact]
public void AsyncMethodBuilder_MissingConstraints()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : System.Attribute
{
public AsyncMethodBuilderAttribute(System.Type t) { }
}
}
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M()
{
await F();
return await G(3);
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
class MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
internal MyTaskMethodBuilder(MyTask task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
// Missing constraint: where TStateMachine : IAsyncStateMachine
public void Start<TStateMachine>(ref TStateMachine stateMachine) { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
internal MyTaskMethodBuilder(MyTask<T> task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
// Incorrect constraint: where TAwaiter : IAsyncStateMachine
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : IAsyncStateMachine where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
compilation.VerifyEmitDiagnostics(
// (17,9): error CS0311: The type 'MyTask.Awaiter' cannot be used as type parameter 'TAwaiter' in the generic type or method 'MyTaskMethodBuilder<int>.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'. There is no implicit reference conversion from 'MyTask.Awaiter' to 'System.Runtime.CompilerServices.IAsyncStateMachine'.
// await F();
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "await F();").WithArguments("MyTaskMethodBuilder<int>.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "System.Runtime.CompilerServices.IAsyncStateMachine", "TAwaiter", "MyTask.Awaiter").WithLocation(17, 9),
// (18,16): error CS0311: The type 'MyTask<int>.Awaiter' cannot be used as type parameter 'TAwaiter' in the generic type or method 'MyTaskMethodBuilder<int>.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'. There is no implicit reference conversion from 'MyTask<int>.Awaiter' to 'System.Runtime.CompilerServices.IAsyncStateMachine'.
// return await G(3);
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "await G(3)").WithArguments("MyTaskMethodBuilder<int>.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "System.Runtime.CompilerServices.IAsyncStateMachine", "TAwaiter", "MyTask<int>.Awaiter").WithLocation(18, 16)
);
}
[WorkItem(12616, "https://github.com/dotnet/roslyn/issues/12616")]
[Fact]
public void AsyncMethodBuilder_AdditionalConstraints()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : System.Attribute
{
public AsyncMethodBuilderAttribute(System.Type t) { }
}
}
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M()
{
await F();
return await G(3);
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
class MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
internal MyTaskMethodBuilder(MyTask task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
// Additional constraint: class
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : class, IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
internal MyTaskMethodBuilder(MyTask<T> task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
// Additional constraint: ICriticalNotifyCompletion
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine, ICriticalNotifyCompletion { }
public MyTask<T> Task => default(MyTask<T>);
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
compilation.VerifyEmitDiagnostics(
// (14,40): error CS0311: The type 'C.<G>d__1<T>' cannot be used as type parameter 'TStateMachine' in the generic type or method 'MyTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'. There is no implicit reference conversion from 'C.<G>d__1<T>' to 'System.Runtime.CompilerServices.ICriticalNotifyCompletion'.
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "await Task.Delay(0);").WithArguments("MyTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "System.Runtime.CompilerServices.ICriticalNotifyCompletion", "TStateMachine", "C.<G>d__1<T>").WithLocation(14, 40));
}
[WorkItem(15955, "https://github.com/dotnet/roslyn/issues/15955")]
[Fact]
public void OverloadWithVoidPointer()
{
var source =
@"class A
{
unsafe public static void F(void* p) { }
unsafe public static void F(int* p) { }
}
class B
{
static void Main()
{
unsafe
{
A.F(null);
}
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugExe);
compilation.VerifyEmitDiagnostics();
}
[Fact]
public void AwaiterMissingINotifyCompletion()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : Attribute
{
public AsyncMethodBuilderAttribute(Type t) { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
public sealed class MyTask
{
public Awaiter GetAwaiter() => null;
public class Awaiter
{
public void OnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
public sealed class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public MyTask Task => new MyTask();
}";
var compilation0 = CreateCompilationWithMscorlib45(source0);
var ref0 = compilation0.EmitToImageReference();
var source =
@"class Program
{
static async MyTask F()
{
await new MyTask();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ref0 });
compilation.VerifyEmitDiagnostics(
// (5,9): error CS4027: 'MyTask.Awaiter' does not implement 'INotifyCompletion'
// await new MyTask();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new MyTask()").WithArguments("MyTask.Awaiter", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(5, 9));
}
/// <summary>
/// Avoid checking constraints in generic methods in actual AsyncTaskMethodBuilder
/// to avoid breaking change.
/// </summary>
[WorkItem(21500, "https://github.com/dotnet/roslyn/issues/21500")]
[Fact]
public void AdditionalConstraintMissingFromStateMachine_AsyncTaskMethodBuilder()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System
{
public delegate void Action();
}
namespace System.Runtime.CompilerServices
{
public interface INotifyCompletion
{
void OnCompleted(Action a);
}
public interface ICriticalNotifyCompletion : INotifyCompletion
{
void UnsafeOnCompleted(Action a);
}
public interface IAsyncStateMachine
{
void MoveNext();
void SetStateMachine(IAsyncStateMachine stateMachine);
}
public interface IMyStateMachine
{
}
public struct AsyncTaskMethodBuilder
{
public static AsyncTaskMethodBuilder Create() => new AsyncTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IMyStateMachine, IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IMyStateMachine, IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IMyStateMachine, IAsyncStateMachine
{
}
public Task Task => new Task();
}
}
namespace System.Threading.Tasks
{
public class Task
{
public Awaiter GetAwaiter() => new Awaiter();
public class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
}";
var compilation0 = CreateEmptyCompilation(source0, references: new[] { MscorlibRef_v20 });
var ref0 = compilation0.EmitToImageReference();
var source =
@"using System.Threading.Tasks;
class Program
{
static async Task F()
{
await new Task();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateEmptyCompilation(source, references: new[] { MscorlibRef_v20, ref0 });
compilation.VerifyEmitDiagnostics();
}
/// <summary>
/// Verify constraints at the call-site for generic methods of async method build.
/// </summary>
[WorkItem(21500, "https://github.com/dotnet/roslyn/issues/21500")]
[Fact]
public void Start_AdditionalConstraintMissingFromStateMachine()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : Attribute
{
public AsyncMethodBuilderAttribute(Type t) { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
public sealed class MyTask
{
public Awaiter GetAwaiter() => new Awaiter();
public class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
public interface IMyStateMachine { }
public sealed class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IMyStateMachine, IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public MyTask Task => new MyTask();
}";
var compilation0 = CreateCompilationWithMscorlib45(source0);
var ref0 = compilation0.EmitToImageReference();
var source =
@"class Program
{
static async MyTask F()
{
await new MyTask();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ref0 });
compilation.VerifyEmitDiagnostics(
// (4,5): error CS0315: The type 'Program.<F>d__0' cannot be used as type parameter 'TStateMachine' in the generic type or method 'MyTaskMethodBuilder.Start<TStateMachine>(ref TStateMachine)'. There is no boxing conversion from 'Program.<F>d__0' to 'IMyStateMachine'.
// {
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, @"{
await new MyTask();
}").WithArguments("MyTaskMethodBuilder.Start<TStateMachine>(ref TStateMachine)", "IMyStateMachine", "TStateMachine", "Program.<F>d__0").WithLocation(4, 5));
}
/// <summary>
/// Verify constraints at the call-site for generic methods of async method build.
/// </summary>
[WorkItem(21500, "https://github.com/dotnet/roslyn/issues/21500")]
[Fact]
public void AwaitOnCompleted_AdditionalConstraintMissingFromAwaiter()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : Attribute
{
public AsyncMethodBuilderAttribute(Type t) { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
public sealed class MyTask
{
public Awaiter GetAwaiter() => null;
public abstract class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
public sealed class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion, new()
where TStateMachine : IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public MyTask Task => new MyTask();
}";
var compilation0 = CreateCompilationWithMscorlib45(source0);
var ref0 = compilation0.EmitToImageReference();
var source =
@"class Program
{
static async MyTask F()
{
await new MyTask();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ref0 });
compilation.VerifyEmitDiagnostics(
// (5,9): error CS0310: 'MyTask.Awaiter' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TAwaiter' in the generic type or method 'MyTaskMethodBuilder.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'
// await new MyTask();
Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "await new MyTask();").WithArguments("MyTaskMethodBuilder.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "TAwaiter", "MyTask.Awaiter").WithLocation(5, 9));
}
/// <summary>
/// Verify constraints at the call-site for generic methods of async method build.
/// </summary>
[WorkItem(21500, "https://github.com/dotnet/roslyn/issues/21500")]
[Fact]
public void AwaitUnsafeOnCompleted_AdditionalConstraintMissingFromAwaiter()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : Attribute
{
public AsyncMethodBuilderAttribute(Type t) { }
}
}
public interface IMyAwaiter { }
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
public sealed class MyTask
{
public Awaiter GetAwaiter() => new Awaiter();
public class Awaiter : ICriticalNotifyCompletion
{
public void OnCompleted(Action a) { }
public void UnsafeOnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
public sealed class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : IMyAwaiter, ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public MyTask Task => new MyTask();
}";
var compilation0 = CreateCompilationWithMscorlib45(source0);
var ref0 = compilation0.EmitToImageReference();
var source =
@"class Program
{
static async MyTask F()
{
await new MyTask();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ref0 });
compilation.VerifyEmitDiagnostics(
// (5,9): error CS0311: The type 'MyTask.Awaiter' cannot be used as type parameter 'TAwaiter' in the generic type or method 'MyTaskMethodBuilder.AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'. There is no implicit reference conversion from 'MyTask.Awaiter' to 'IMyAwaiter'.
// await new MyTask();
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "await new MyTask();").WithArguments("MyTaskMethodBuilder.AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "IMyAwaiter", "TAwaiter", "MyTask.Awaiter").WithLocation(5, 9));
}
[Fact, WorkItem(33388, "https://github.com/dotnet/roslyn/pull/33388")]
public void AttributeArgument_TaskLikeOverloadResolution()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class A : Attribute
{
public A(int i) { }
}
class B
{
public static int F(Func<MyTask<C>> t) => 1;
public static int F(Func<Task<object>> t) => 2;
}
[A(B.F(async () => null))]
class C
{
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (15,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(B.F(async () => null))]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B.F(async () => null)").WithLocation(15, 4));
}
[Fact, WorkItem(37712, "https://github.com/dotnet/roslyn/issues/37712")]
public void TaskLikeWithRefStructValue()
{
var source = @"
using System;
using System.Threading.Tasks;
ref struct MyAwaitable
{
public MyAwaiter GetAwaiter() => new MyAwaiter();
}
struct MyAwaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public bool IsCompleted => true;
public MyResult GetResult() => new MyResult();
public void OnCompleted(Action continuation) { }
}
ref struct MyResult
{
}
class Program
{
public static async Task Main()
{
M(await new MyAwaitable());
}
public static void M(MyResult r)
{
Console.WriteLine(3);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "3");
compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "3");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingAsyncTasklikeMoreTests : CompilingTestBase
{
[Fact]
public void AsyncMethod()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M()
{
await F();
return await G(3);
}
static void Main()
{
var i = M().Result;
Console.WriteLine(i);
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask
{
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
struct MyTask<T>
{
internal T _result;
public T Result => _result;
internal Awaiter GetAwaiter() => new Awaiter(this);
internal class Awaiter : INotifyCompletion
{
private readonly MyTask<T> _task;
internal Awaiter(MyTask<T> task) { _task = task; }
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => _task.Result;
}
}
struct MyTaskMethodBuilder
{
private MyTask _task;
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(new MyTask());
internal MyTaskMethodBuilder(MyTask task)
{
_task = task;
}
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => _task;
}
struct MyTaskMethodBuilder<T>
{
private MyTask<T> _task;
public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(new MyTask<T>());
internal MyTaskMethodBuilder(MyTask<T> task)
{
_task = task;
}
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult(T t) { _task._result = t; }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => _task;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(compilation, expectedOutput: "3");
verifier.VerifyDiagnostics();
var testData = verifier.TestData;
var method = (MethodSymbol)testData.GetMethodData("C.F()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningTask(compilation));
method = (MethodSymbol)testData.GetMethodData("C.G<T>(T)").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningGenericTask(compilation));
verifier.VerifyIL("C.F()",
@"{
// Code size 49 (0x31)
.maxstack 2
.locals init (C.<F>d__0 V_0)
IL_0000: newobj ""C.<F>d__0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call ""MyTaskMethodBuilder MyTaskMethodBuilder.Create()""
IL_000c: stfld ""MyTaskMethodBuilder C.<F>d__0.<>t__builder""
IL_0011: ldloc.0
IL_0012: ldc.i4.m1
IL_0013: stfld ""int C.<F>d__0.<>1__state""
IL_0018: ldloc.0
IL_0019: ldflda ""MyTaskMethodBuilder C.<F>d__0.<>t__builder""
IL_001e: ldloca.s V_0
IL_0020: call ""void MyTaskMethodBuilder.Start<C.<F>d__0>(ref C.<F>d__0)""
IL_0025: ldloc.0
IL_0026: ldflda ""MyTaskMethodBuilder C.<F>d__0.<>t__builder""
IL_002b: call ""MyTask MyTaskMethodBuilder.Task.get""
IL_0030: ret
}");
verifier.VerifyIL("C.G<T>(T)",
@"{
// Code size 56 (0x38)
.maxstack 2
.locals init (C.<G>d__1<T> V_0)
IL_0000: newobj ""C.<G>d__1<T>..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call ""MyTaskMethodBuilder<T> MyTaskMethodBuilder<T>.Create()""
IL_000c: stfld ""MyTaskMethodBuilder<T> C.<G>d__1<T>.<>t__builder""
IL_0011: ldloc.0
IL_0012: ldarg.0
IL_0013: stfld ""T C.<G>d__1<T>.t""
IL_0018: ldloc.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<G>d__1<T>.<>1__state""
IL_001f: ldloc.0
IL_0020: ldflda ""MyTaskMethodBuilder<T> C.<G>d__1<T>.<>t__builder""
IL_0025: ldloca.s V_0
IL_0027: call ""void MyTaskMethodBuilder<T>.Start<C.<G>d__1<T>>(ref C.<G>d__1<T>)""
IL_002c: ldloc.0
IL_002d: ldflda ""MyTaskMethodBuilder<T> C.<G>d__1<T>.<>t__builder""
IL_0032: call ""MyTask<T> MyTaskMethodBuilder<T>.Task.get""
IL_0037: ret
}");
}
[Fact]
public void AsyncMethod_CreateHasRefReturn()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M() { await F(); return await G(3); }
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask
{
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
struct MyTask<T>
{
internal T _result;
public T Result => _result;
internal Awaiter GetAwaiter() => new Awaiter(this);
internal class Awaiter : INotifyCompletion
{
private readonly MyTask<T> _task;
internal Awaiter(MyTask<T> task) { _task = task; }
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => _task.Result;
}
}
struct MyTaskMethodBuilder
{
private MyTask _task;
public static ref MyTaskMethodBuilder Create() => throw null;
internal MyTaskMethodBuilder(MyTask task) { _task = task; }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => _task;
}
struct MyTaskMethodBuilder<T>
{
private MyTask<T> _task;
public static ref MyTaskMethodBuilder<T> Create() => throw null;
internal MyTaskMethodBuilder(MyTask<T> task) { _task = task; }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); }
public void SetException(Exception e) { }
public void SetResult(T t) { _task._result = t; }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => _task;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (6,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilder.Create'
// static async MyTask F() { await Task.Delay(0); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("MyTaskMethodBuilder", "Create").WithLocation(6, 29),
// (7,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<T>.Create'
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); return t; }").WithArguments("MyTaskMethodBuilder<T>", "Create").WithLocation(7, 38),
// (8,34): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<int>.Create'
// static async MyTask<int> M() { await F(); return await G(3); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await F(); return await G(3); }").WithArguments("MyTaskMethodBuilder<int>", "Create").WithLocation(8, 34)
);
}
[Fact]
public void AsyncMethod_BuilderFactoryDisallowed()
{
// Only method-level builder overrides allow having Create() return a different builder
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M() { await F(); return await G(3); }
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilderFactory))]
struct MyTask
{
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilderFactory<>))]
struct MyTask<T>
{
internal T _result;
public T Result => _result;
internal Awaiter GetAwaiter() => new Awaiter(this);
internal class Awaiter : INotifyCompletion
{
private readonly MyTask<T> _task;
internal Awaiter(MyTask<T> task) { _task = task; }
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => _task.Result;
}
}
struct MyTaskMethodBuilderFactory
{
public static MyTaskMethodBuilder Create() => throw null;
}
struct MyTaskMethodBuilder
{
private MyTask _task;
internal MyTaskMethodBuilder(MyTask task) { _task = task; }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => _task;
}
struct MyTaskMethodBuilderFactory<T>
{
public static MyTaskMethodBuilder<T> Create() => throw null;
}
struct MyTaskMethodBuilder<T>
{
private MyTask<T> _task;
internal MyTaskMethodBuilder(MyTask<T> task) { _task = task; }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); }
public void SetException(Exception e) { }
public void SetResult(T t) { _task._result = t; }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => _task;
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (6,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory.Task'
// static async MyTask F() { await Task.Delay(0); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("MyTaskMethodBuilderFactory", "Task").WithLocation(6, 29),
// (6,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory.Create'
// static async MyTask F() { await Task.Delay(0); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("MyTaskMethodBuilderFactory", "Create").WithLocation(6, 29),
// (7,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory<T>.Task'
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); return t; }").WithArguments("MyTaskMethodBuilderFactory<T>", "Task").WithLocation(7, 38),
// (7,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory<T>.Create'
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); return t; }").WithArguments("MyTaskMethodBuilderFactory<T>", "Create").WithLocation(7, 38),
// (8,34): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory<int>.Task'
// static async MyTask<int> M() { await F(); return await G(3); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await F(); return await G(3); }").WithArguments("MyTaskMethodBuilderFactory<int>", "Task").WithLocation(8, 34),
// (8,34): error CS0656: Missing compiler required member 'MyTaskMethodBuilderFactory<int>.Create'
// static async MyTask<int> M() { await F(); return await G(3); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await F(); return await G(3); }").WithArguments("MyTaskMethodBuilderFactory<int>", "Create").WithLocation(8, 34)
);
}
[Fact]
public void AsyncMethodBuilder_MissingMethods()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
static async MyTask F() { await (Task)null; }
static async MyTask<T> G<T>(T t) { await (Task)null; return t; }
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask { }
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
struct MyTask<T> { }
struct MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
}
struct MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>();
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task { get { return default(MyTask<T>); } }
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (6,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilder.Task'
// static async MyTask F() { await (Task)null; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await (Task)null; }").WithArguments("MyTaskMethodBuilder", "Task").WithLocation(6, 29),
// (7,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<T>.SetException'
// static async MyTask<T> G<T>(T t) { await (Task)null; return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await (Task)null; return t; }").WithArguments("MyTaskMethodBuilder<T>", "SetException").WithLocation(7, 38));
}
[Fact]
public void Private()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
#pragma warning disable CS1998
static async MyTask F() { }
static async MyTask<int> G() { return 3; }
#pragma warning restore CS1998
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
private class MyTask { }
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
private class MyTask<T> { }
private class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task { get { return null; } }
}
private class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task { get { return null; } }
}
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
var verifier = CompileAndVerify(compilation);
verifier.VerifyDiagnostics();
var testData = verifier.TestData;
var method = (MethodSymbol)testData.GetMethodData("C.F()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningTask(compilation));
Assert.Equal("C.MyTask", method.ReturnTypeWithAnnotations.ToDisplayString());
method = (MethodSymbol)testData.GetMethodData("C.G()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningGenericTask(compilation));
Assert.Equal("C.MyTask<int>", method.ReturnTypeWithAnnotations.ToDisplayString());
}
[Fact]
public void AsyncLambda_InferReturnType()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static void F(Func<MyTask> f) { }
static void F<T>(Func<MyTask<T>> f) { }
static void F(Func<MyTask<string>> f) { }
static void M()
{
#pragma warning disable CS1998
F(async () => { });
F(async () => { return 3; });
F(async () => { return string.Empty; });
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
class MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
var verifier = CompileAndVerify(compilation);
verifier.VerifyDiagnostics();
var testData = verifier.TestData;
var method = (MethodSymbol)testData.GetMethodData("C.<>c.<M>b__3_0()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningTask(compilation));
Assert.Equal("MyTask", method.ReturnTypeWithAnnotations.ToDisplayString());
method = (MethodSymbol)testData.GetMethodData("C.<>c.<M>b__3_1()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningGenericTask(compilation));
Assert.Equal("MyTask<int>", method.ReturnTypeWithAnnotations.ToDisplayString());
}
[Fact]
public void AsyncLocalFunction()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static async void M()
{
#pragma warning disable CS1998
async MyTask F() { }
async MyTask<T> G<T>(T t) => t;
await F();
await G(3);
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
struct MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
var verifier = CompileAndVerify(compilation);
verifier.VerifyDiagnostics();
var testData = verifier.TestData;
var method = (MethodSymbol)testData.GetMethodData("C.<M>g__F|0_0()").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningTask(compilation));
Assert.Equal("MyTask", method.ReturnTypeWithAnnotations.ToDisplayString());
method = (MethodSymbol)testData.GetMethodData("C.<M>g__G|0_1<T>(T)").Method;
Assert.True(method.IsAsync);
Assert.True(method.IsAsyncEffectivelyReturningGenericTask(compilation));
Assert.Equal("MyTask<T>", method.ReturnTypeWithAnnotations.ToDisplayString());
}
[Fact]
public void Dynamic()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static void F<T>(Func<MyTask<T>> f) { }
static void G(Func<MyTask<dynamic>> f) { }
static void M(object o)
{
#pragma warning disable CS1998
F(async () => (dynamic)o);
F(async () => new[] { (dynamic)o });
G(async () => o);
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source, references: new MetadataReference[] { CSharpRef, SystemCoreRef });
var verifier = CompileAndVerify(
compilation,
expectedSignatures: new[]
{
Signature(
"C+<>c__DisplayClass2_0",
"<M>b__0",
".method [System.Runtime.CompilerServices.AsyncStateMachineAttribute(C+<>c__DisplayClass2_0+<<M>b__0>d)] assembly hidebysig instance [System.Runtime.CompilerServices.DynamicAttribute(System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] MyTask`1[System.Object] <M>b__0() cil managed"),
Signature(
"C+<>c__DisplayClass2_0",
"<M>b__1",
".method [System.Runtime.CompilerServices.AsyncStateMachineAttribute(C+<>c__DisplayClass2_0+<<M>b__1>d)] assembly hidebysig instance [System.Runtime.CompilerServices.DynamicAttribute(System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] MyTask`1[System.Object[]] <M>b__1() cil managed"),
Signature(
"C+<>c__DisplayClass2_0",
"<M>b__2",
".method [System.Runtime.CompilerServices.AsyncStateMachineAttribute(C+<>c__DisplayClass2_0+<<M>b__2>d)] assembly hidebysig instance [System.Runtime.CompilerServices.DynamicAttribute(System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] MyTask`1[System.Object] <M>b__2() cil managed"),
});
verifier.VerifyDiagnostics();
}
[Fact]
public void NonTaskBuilder()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static async void M()
{
#pragma warning disable CS1998
async MyTask F() { };
await F();
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(string))]
public struct MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (8,26): error CS0656: Missing compiler required member 'string.Task'
// async MyTask F() { };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ }").WithArguments("string", "Task").WithLocation(8, 26),
// (8,26): error CS0656: Missing compiler required member 'string.Create'
// async MyTask F() { };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ }").WithArguments("string", "Create").WithLocation(8, 26));
}
[Fact]
public void NonTaskBuilderOfT()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static async void M()
{
#pragma warning disable CS1998
async MyTask<T> F<T>(T t) => t;
await F(3);
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(IEquatable<>))]
public struct MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (8,35): error CS0656: Missing compiler required member 'IEquatable<T>.Task'
// async MyTask<T> F<T>(T t) => t;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> t").WithArguments("System.IEquatable<T>", "Task").WithLocation(8, 35),
// (8,35): error CS0656: Missing compiler required member 'IEquatable<T>.Create'
// async MyTask<T> F<T>(T t) => t;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> t").WithArguments("System.IEquatable<T>", "Create").WithLocation(8, 35));
}
[Fact]
public void NonTaskBuilder_Array()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class C
{
static async void M()
{
#pragma warning disable CS1998
async MyTask F() { };
await F();
#pragma warning restore CS1998
}
}
[AsyncMethodBuilder(typeof(object[]))]
struct MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (8,22): error CS1983: The return type of an async method must be void, Task or Task<T>
// async MyTask F() { };
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "{ }").WithLocation(8, 26));
}
[Fact]
public static void AsyncMethodBuilderAttributeMultipleParameters()
{
var source = @"
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
[AsyncMethodBuilder(typeof(B1),1)] class T1 { }
class B1 { }
[AsyncMethodBuilder(typeof(B2))] class T2 { }
class B2 { }
class Program {
static void Main() { }
async T1 f1() => await Task.Delay(1);
async T2 f2() => await Task.Delay(1);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t, int i) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (8,2): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'AsyncMethodBuilderAttribute.AsyncMethodBuilderAttribute(Type, int)'
// [AsyncMethodBuilder(typeof(B2))] class T2 { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AsyncMethodBuilder(typeof(B2))").WithArguments("i", "System.Runtime.CompilerServices.AsyncMethodBuilderAttribute.AsyncMethodBuilderAttribute(System.Type, int)").WithLocation(8, 2),
// (13,14): error CS1983: The return type of an async method must be void, Task or Task<T>
// async T1 f1() => await Task.Delay(1);
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f1").WithLocation(13, 14),
// (14,14): error CS1983: The return type of an async method must be void, Task or Task<T>
// async T2 f2() => await Task.Delay(1);
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f2").WithLocation(14, 14)
);
}
[Fact]
public static void AsyncMethodBuilderAttributeSingleParameterWrong()
{
var source = @"
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
[AsyncMethodBuilder(1)] class T { }
class Program {
static void Main() { }
async T f() => await Task.Delay(1);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(int i) { } } }
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.VerifyEmitDiagnostics(
// (9,13): error CS1983: The return type of an async method must be void, Task or Task<T>
// async T f() => await Task.Delay(1);
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f").WithLocation(9, 13)
);
}
[Fact]
public void AsyncMethodBuilder_IncorrectMethodArity()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : System.Attribute
{
public AsyncMethodBuilderAttribute(System.Type t) { }
}
}
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M()
{
await F();
return await G(3);
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
class MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
internal MyTaskMethodBuilder(MyTask task) { }
public void SetStateMachine<T>(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
internal MyTaskMethodBuilder(MyTask<T> task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TAwaiter, TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
compilation.VerifyEmitDiagnostics(
// (13,29): error CS0656: Missing compiler required member 'MyTaskMethodBuilder.SetStateMachine'
// static async MyTask F() { await Task.Delay(0); }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("MyTaskMethodBuilder", "SetStateMachine").WithLocation(13, 29),
// (14,38): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<T>.Start'
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); return t; }").WithArguments("MyTaskMethodBuilder<T>", "Start").WithLocation(14, 38),
// (16,5): error CS0656: Missing compiler required member 'MyTaskMethodBuilder<int>.Start'
// {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"{
await F();
return await G(3);
}").WithArguments("MyTaskMethodBuilder<int>", "Start").WithLocation(16, 5));
}
[WorkItem(12616, "https://github.com/dotnet/roslyn/issues/12616")]
[Fact]
public void AsyncMethodBuilder_MissingConstraints()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : System.Attribute
{
public AsyncMethodBuilderAttribute(System.Type t) { }
}
}
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M()
{
await F();
return await G(3);
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
class MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
internal MyTaskMethodBuilder(MyTask task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
// Missing constraint: where TStateMachine : IAsyncStateMachine
public void Start<TStateMachine>(ref TStateMachine stateMachine) { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
internal MyTaskMethodBuilder(MyTask<T> task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
// Incorrect constraint: where TAwaiter : IAsyncStateMachine
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : IAsyncStateMachine where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
compilation.VerifyEmitDiagnostics(
// (17,9): error CS0311: The type 'MyTask.Awaiter' cannot be used as type parameter 'TAwaiter' in the generic type or method 'MyTaskMethodBuilder<int>.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'. There is no implicit reference conversion from 'MyTask.Awaiter' to 'System.Runtime.CompilerServices.IAsyncStateMachine'.
// await F();
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "await F();").WithArguments("MyTaskMethodBuilder<int>.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "System.Runtime.CompilerServices.IAsyncStateMachine", "TAwaiter", "MyTask.Awaiter").WithLocation(17, 9),
// (18,16): error CS0311: The type 'MyTask<int>.Awaiter' cannot be used as type parameter 'TAwaiter' in the generic type or method 'MyTaskMethodBuilder<int>.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'. There is no implicit reference conversion from 'MyTask<int>.Awaiter' to 'System.Runtime.CompilerServices.IAsyncStateMachine'.
// return await G(3);
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "await G(3)").WithArguments("MyTaskMethodBuilder<int>.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "System.Runtime.CompilerServices.IAsyncStateMachine", "TAwaiter", "MyTask<int>.Awaiter").WithLocation(18, 16)
);
}
[WorkItem(12616, "https://github.com/dotnet/roslyn/issues/12616")]
[Fact]
public void AsyncMethodBuilder_AdditionalConstraints()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : System.Attribute
{
public AsyncMethodBuilderAttribute(System.Type t) { }
}
}
class C
{
static async MyTask F() { await Task.Delay(0); }
static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
static async MyTask<int> M()
{
await F();
return await G(3);
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
class MyTask
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => null;
internal MyTaskMethodBuilder(MyTask task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
// Additional constraint: class
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : class, IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => default(MyTask);
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
internal MyTaskMethodBuilder(MyTask<T> task) { }
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
// Additional constraint: ICriticalNotifyCompletion
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine, ICriticalNotifyCompletion { }
public MyTask<T> Task => default(MyTask<T>);
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
compilation.VerifyEmitDiagnostics(
// (14,40): error CS0311: The type 'C.<G>d__1<T>' cannot be used as type parameter 'TStateMachine' in the generic type or method 'MyTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'. There is no implicit reference conversion from 'C.<G>d__1<T>' to 'System.Runtime.CompilerServices.ICriticalNotifyCompletion'.
// static async MyTask<T> G<T>(T t) { await Task.Delay(0); return t; }
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "await Task.Delay(0);").WithArguments("MyTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "System.Runtime.CompilerServices.ICriticalNotifyCompletion", "TStateMachine", "C.<G>d__1<T>").WithLocation(14, 40));
}
[WorkItem(15955, "https://github.com/dotnet/roslyn/issues/15955")]
[Fact]
public void OverloadWithVoidPointer()
{
var source =
@"class A
{
unsafe public static void F(void* p) { }
unsafe public static void F(int* p) { }
}
class B
{
static void Main()
{
unsafe
{
A.F(null);
}
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugExe);
compilation.VerifyEmitDiagnostics();
}
[Fact]
public void AwaiterMissingINotifyCompletion()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : Attribute
{
public AsyncMethodBuilderAttribute(Type t) { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
public sealed class MyTask
{
public Awaiter GetAwaiter() => null;
public class Awaiter
{
public void OnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
public sealed class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public MyTask Task => new MyTask();
}";
var compilation0 = CreateCompilationWithMscorlib45(source0);
var ref0 = compilation0.EmitToImageReference();
var source =
@"class Program
{
static async MyTask F()
{
await new MyTask();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ref0 });
compilation.VerifyEmitDiagnostics(
// (5,9): error CS4027: 'MyTask.Awaiter' does not implement 'INotifyCompletion'
// await new MyTask();
Diagnostic(ErrorCode.ERR_DoesntImplementAwaitInterface, "await new MyTask()").WithArguments("MyTask.Awaiter", "System.Runtime.CompilerServices.INotifyCompletion").WithLocation(5, 9));
}
/// <summary>
/// Avoid checking constraints in generic methods in actual AsyncTaskMethodBuilder
/// to avoid breaking change.
/// </summary>
[WorkItem(21500, "https://github.com/dotnet/roslyn/issues/21500")]
[Fact]
public void AdditionalConstraintMissingFromStateMachine_AsyncTaskMethodBuilder()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System
{
public delegate void Action();
}
namespace System.Runtime.CompilerServices
{
public interface INotifyCompletion
{
void OnCompleted(Action a);
}
public interface ICriticalNotifyCompletion : INotifyCompletion
{
void UnsafeOnCompleted(Action a);
}
public interface IAsyncStateMachine
{
void MoveNext();
void SetStateMachine(IAsyncStateMachine stateMachine);
}
public interface IMyStateMachine
{
}
public struct AsyncTaskMethodBuilder
{
public static AsyncTaskMethodBuilder Create() => new AsyncTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IMyStateMachine, IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IMyStateMachine, IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IMyStateMachine, IAsyncStateMachine
{
}
public Task Task => new Task();
}
}
namespace System.Threading.Tasks
{
public class Task
{
public Awaiter GetAwaiter() => new Awaiter();
public class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
}";
var compilation0 = CreateEmptyCompilation(source0, references: new[] { MscorlibRef_v20 });
var ref0 = compilation0.EmitToImageReference();
var source =
@"using System.Threading.Tasks;
class Program
{
static async Task F()
{
await new Task();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateEmptyCompilation(source, references: new[] { MscorlibRef_v20, ref0 });
compilation.VerifyEmitDiagnostics();
}
/// <summary>
/// Verify constraints at the call-site for generic methods of async method build.
/// </summary>
[WorkItem(21500, "https://github.com/dotnet/roslyn/issues/21500")]
[Fact]
public void Start_AdditionalConstraintMissingFromStateMachine()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : Attribute
{
public AsyncMethodBuilderAttribute(Type t) { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
public sealed class MyTask
{
public Awaiter GetAwaiter() => new Awaiter();
public class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
public interface IMyStateMachine { }
public sealed class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IMyStateMachine, IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public MyTask Task => new MyTask();
}";
var compilation0 = CreateCompilationWithMscorlib45(source0);
var ref0 = compilation0.EmitToImageReference();
var source =
@"class Program
{
static async MyTask F()
{
await new MyTask();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ref0 });
compilation.VerifyEmitDiagnostics(
// (4,5): error CS0315: The type 'Program.<F>d__0' cannot be used as type parameter 'TStateMachine' in the generic type or method 'MyTaskMethodBuilder.Start<TStateMachine>(ref TStateMachine)'. There is no boxing conversion from 'Program.<F>d__0' to 'IMyStateMachine'.
// {
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, @"{
await new MyTask();
}").WithArguments("MyTaskMethodBuilder.Start<TStateMachine>(ref TStateMachine)", "IMyStateMachine", "TStateMachine", "Program.<F>d__0").WithLocation(4, 5));
}
/// <summary>
/// Verify constraints at the call-site for generic methods of async method build.
/// </summary>
[WorkItem(21500, "https://github.com/dotnet/roslyn/issues/21500")]
[Fact]
public void AwaitOnCompleted_AdditionalConstraintMissingFromAwaiter()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : Attribute
{
public AsyncMethodBuilderAttribute(Type t) { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
public sealed class MyTask
{
public Awaiter GetAwaiter() => null;
public abstract class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
public sealed class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion, new()
where TStateMachine : IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public MyTask Task => new MyTask();
}";
var compilation0 = CreateCompilationWithMscorlib45(source0);
var ref0 = compilation0.EmitToImageReference();
var source =
@"class Program
{
static async MyTask F()
{
await new MyTask();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ref0 });
compilation.VerifyEmitDiagnostics(
// (5,9): error CS0310: 'MyTask.Awaiter' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TAwaiter' in the generic type or method 'MyTaskMethodBuilder.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'
// await new MyTask();
Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "await new MyTask();").WithArguments("MyTaskMethodBuilder.AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "TAwaiter", "MyTask.Awaiter").WithLocation(5, 9));
}
/// <summary>
/// Verify constraints at the call-site for generic methods of async method build.
/// </summary>
[WorkItem(21500, "https://github.com/dotnet/roslyn/issues/21500")]
[Fact]
public void AwaitUnsafeOnCompleted_AdditionalConstraintMissingFromAwaiter()
{
var source0 =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : Attribute
{
public AsyncMethodBuilderAttribute(Type t) { }
}
}
public interface IMyAwaiter { }
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
public sealed class MyTask
{
public Awaiter GetAwaiter() => new Awaiter();
public class Awaiter : ICriticalNotifyCompletion
{
public void OnCompleted(Action a) { }
public void UnsafeOnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
public sealed class MyTaskMethodBuilder
{
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder();
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
{
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : IMyAwaiter, ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
}
public MyTask Task => new MyTask();
}";
var compilation0 = CreateCompilationWithMscorlib45(source0);
var ref0 = compilation0.EmitToImageReference();
var source =
@"class Program
{
static async MyTask F()
{
await new MyTask();
}
static void Main()
{
var t = F();
t.GetAwaiter().GetResult();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ref0 });
compilation.VerifyEmitDiagnostics(
// (5,9): error CS0311: The type 'MyTask.Awaiter' cannot be used as type parameter 'TAwaiter' in the generic type or method 'MyTaskMethodBuilder.AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)'. There is no implicit reference conversion from 'MyTask.Awaiter' to 'IMyAwaiter'.
// await new MyTask();
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "await new MyTask();").WithArguments("MyTaskMethodBuilder.AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter, ref TStateMachine)", "IMyAwaiter", "TAwaiter", "MyTask.Awaiter").WithLocation(5, 9));
}
[Fact, WorkItem(33388, "https://github.com/dotnet/roslyn/pull/33388")]
public void AttributeArgument_TaskLikeOverloadResolution()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class A : Attribute
{
public A(int i) { }
}
class B
{
public static int F(Func<MyTask<C>> t) => 1;
public static int F(Func<Task<object>> t) => 2;
}
[A(B.F(async () => null))]
class C
{
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))]
class MyTask<T>
{
internal Awaiter GetAwaiter() => null;
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal T GetResult() => default(T);
}
}
class MyTaskMethodBuilder<T>
{
public static MyTaskMethodBuilder<T> Create() => null;
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { }
public void SetException(Exception e) { }
public void SetResult(T t) { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask<T> Task => default(MyTask<T>);
}
namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } }
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (15,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(B.F(async () => null))]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "B.F(async () => null)").WithLocation(15, 4));
}
[Fact, WorkItem(37712, "https://github.com/dotnet/roslyn/issues/37712")]
public void TaskLikeWithRefStructValue()
{
var source = @"
using System;
using System.Threading.Tasks;
ref struct MyAwaitable
{
public MyAwaiter GetAwaiter() => new MyAwaiter();
}
struct MyAwaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public bool IsCompleted => true;
public MyResult GetResult() => new MyResult();
public void OnCompleted(Action continuation) { }
}
ref struct MyResult
{
}
class Program
{
public static async Task Main()
{
M(await new MyAwaitable());
}
public static void M(MyResult r)
{
Console.WriteLine(3);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "3");
compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "3");
}
}
}
| -1 |
dotnet/roslyn | 55,179 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | 2021-07-28T12:01:59Z | 2021-07-28T13:07:16Z | badcd003f616de451aa1ce04191f27c0be835c4d | af0313d42f845445623b2ee6865ac13ba1faf522 | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Tools/ExternalAccess/Razor/RazorDynamicFileInfo.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.Host;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
/// <summary>
/// provides info on the given file
///
/// this will be used to provide dynamic content such as generated content from cshtml to workspace
/// we acquire this from <see cref="IDynamicFileInfoProvider"/> exposed from external components such as razor for cshtml
/// </summary>
internal sealed class RazorDynamicFileInfo
{
public RazorDynamicFileInfo(string filePath, SourceCodeKind sourceCodeKind, TextLoader textLoader, IRazorDocumentServiceProvider documentServiceProvider)
{
FilePath = filePath;
SourceCodeKind = sourceCodeKind;
TextLoader = textLoader;
DocumentServiceProvider = documentServiceProvider;
}
/// <summary>
/// for now, return null. in future, we will use this to get right options from editorconfig
/// </summary>
public string FilePath { get; }
/// <summary>
/// return <see cref="SourceCodeKind"/> for this file
/// </summary>
public SourceCodeKind SourceCodeKind { get; }
/// <summary>
/// return <see cref="RazorDynamicFileInfo.TextLoader"/> to load content for the dynamic file
/// </summary>
public TextLoader TextLoader { get; }
/// <summary>
/// return <see cref="IRazorDocumentServiceProvider"/> for the contents it provides
/// </summary>
public IRazorDocumentServiceProvider DocumentServiceProvider { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
/// <summary>
/// provides info on the given file
///
/// this will be used to provide dynamic content such as generated content from cshtml to workspace
/// we acquire this from <see cref="IDynamicFileInfoProvider"/> exposed from external components such as razor for cshtml
/// </summary>
internal sealed class RazorDynamicFileInfo
{
public RazorDynamicFileInfo(string filePath, SourceCodeKind sourceCodeKind, TextLoader textLoader, IRazorDocumentServiceProvider documentServiceProvider)
{
FilePath = filePath;
SourceCodeKind = sourceCodeKind;
TextLoader = textLoader;
DocumentServiceProvider = documentServiceProvider;
}
/// <summary>
/// for now, return null. in future, we will use this to get right options from editorconfig
/// </summary>
public string FilePath { get; }
/// <summary>
/// return <see cref="SourceCodeKind"/> for this file
/// </summary>
public SourceCodeKind SourceCodeKind { get; }
/// <summary>
/// return <see cref="RazorDynamicFileInfo.TextLoader"/> to load content for the dynamic file
/// </summary>
public TextLoader TextLoader { get; }
/// <summary>
/// return <see cref="IRazorDocumentServiceProvider"/> for the contents it provides
/// </summary>
public IRazorDocumentServiceProvider DocumentServiceProvider { get; }
}
}
| -1 |
dotnet/roslyn | 55,179 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | 2021-07-28T12:01:59Z | 2021-07-28T13:07:16Z | badcd003f616de451aa1ce04191f27c0be835c4d | af0313d42f845445623b2ee6865ac13ba1faf522 | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/Core/Portable/Workspace/Host/TextFactory/TextFactoryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Host
{
[ExportWorkspaceService(typeof(ITextFactoryService), ServiceLayer.Default), Shared]
internal class TextFactoryService : ITextFactoryService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TextFactoryService()
{
}
public SourceText CreateText(Stream stream, Encoding? defaultEncoding, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return EncodedStringText.Create(stream, defaultEncoding);
}
public SourceText CreateText(TextReader reader, Encoding? encoding, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var textReaderWithLength = reader as TextReaderWithLength;
if (textReaderWithLength != null)
{
return SourceText.From(textReaderWithLength, textReaderWithLength.Length, encoding);
}
return SourceText.From(reader.ReadToEnd(), encoding);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Host
{
[ExportWorkspaceService(typeof(ITextFactoryService), ServiceLayer.Default), Shared]
internal class TextFactoryService : ITextFactoryService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TextFactoryService()
{
}
public SourceText CreateText(Stream stream, Encoding? defaultEncoding, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return EncodedStringText.Create(stream, defaultEncoding);
}
public SourceText CreateText(TextReader reader, Encoding? encoding, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var textReaderWithLength = reader as TextReaderWithLength;
if (textReaderWithLength != null)
{
return SourceText.From(textReaderWithLength, textReaderWithLength.Length, encoding);
}
return SourceText.From(reader.ReadToEnd(), encoding);
}
}
}
| -1 |
dotnet/roslyn | 55,179 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | 2021-07-28T12:01:59Z | 2021-07-28T13:07:16Z | badcd003f616de451aa1ce04191f27c0be835c4d | af0313d42f845445623b2ee6865ac13ba1faf522 | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Impl/Options/AbstractRadioButtonViewModel.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.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
internal abstract class AbstractRadioButtonViewModel : AbstractNotifyPropertyChanged
{
private readonly AbstractOptionPreviewViewModel _info;
internal readonly string Preview;
private bool _isChecked;
public string Description { get; }
public string GroupName { get; }
public bool IsChecked
{
get
{
return _isChecked;
}
set
{
SetProperty(ref _isChecked, value);
if (_isChecked)
{
SetOptionAndUpdatePreview(_info, Preview);
}
}
}
public AbstractRadioButtonViewModel(string description, string preview, AbstractOptionPreviewViewModel info, bool isChecked, string group)
{
Description = description;
this.Preview = preview;
_info = info;
this.GroupName = group;
SetProperty(ref _isChecked, isChecked);
}
internal abstract void SetOptionAndUpdatePreview(AbstractOptionPreviewViewModel info, string preview);
}
}
| // Licensed to the .NET Foundation under one or more 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.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
internal abstract class AbstractRadioButtonViewModel : AbstractNotifyPropertyChanged
{
private readonly AbstractOptionPreviewViewModel _info;
internal readonly string Preview;
private bool _isChecked;
public string Description { get; }
public string GroupName { get; }
public bool IsChecked
{
get
{
return _isChecked;
}
set
{
SetProperty(ref _isChecked, value);
if (_isChecked)
{
SetOptionAndUpdatePreview(_info, Preview);
}
}
}
public AbstractRadioButtonViewModel(string description, string preview, AbstractOptionPreviewViewModel info, bool isChecked, string group)
{
Description = description;
this.Preview = preview;
_info = info;
this.GroupName = group;
SetProperty(ref _isChecked, isChecked);
}
internal abstract void SetOptionAndUpdatePreview(AbstractOptionPreviewViewModel info, string preview);
}
}
| -1 |
dotnet/roslyn | 55,179 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | 2021-07-28T12:01:59Z | 2021-07-28T13:07:16Z | badcd003f616de451aa1ce04191f27c0be835c4d | af0313d42f845445623b2ee6865ac13ba1faf522 | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordDeconstruct.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SynthesizedRecordDeconstruct : SynthesizedRecordOrdinaryMethod
{
private readonly SynthesizedRecordConstructor _ctor;
private readonly ImmutableArray<Symbol> _positionalMembers;
public SynthesizedRecordDeconstruct(
SourceMemberContainerTypeSymbol containingType,
SynthesizedRecordConstructor ctor,
ImmutableArray<Symbol> positionalMembers,
int memberOffset,
BindingDiagnosticBag diagnostics)
: base(containingType, WellKnownMemberNames.DeconstructMethodName, hasBody: true, memberOffset, diagnostics)
{
Debug.Assert(positionalMembers.All(p => p is PropertySymbol { GetMethod: not null } or FieldSymbol));
_ctor = ctor;
_positionalMembers = positionalMembers;
}
protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics)
{
const DeclarationModifiers result = DeclarationModifiers.Public;
Debug.Assert((result & ~allowedModifiers) == 0);
return result;
}
protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics)
{
var compilation = DeclaringCompilation;
var location = ReturnTypeLocation;
return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Void, location, diagnostics)),
Parameters: _ctor.Parameters.SelectAsArray<ParameterSymbol, ImmutableArray<Location>, ParameterSymbol>(
(param, locations) =>
new SourceSimpleParameterSymbol(owner: this,
param.TypeWithAnnotations,
param.Ordinal,
RefKind.Out,
param.Name,
locations),
arg: Locations),
IsVararg: false,
DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty);
}
protected override int GetParameterCountFromSyntax() => _ctor.ParameterCount;
internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics);
if (ParameterCount != _positionalMembers.Length)
{
// There is a mismatch, an error was reported elsewhere
F.CloseMethod(F.ThrowNull());
return;
}
var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance(_positionalMembers.Length + 1);
for (int i = 0; i < _positionalMembers.Length; i++)
{
var parameter = Parameters[i];
var positionalMember = _positionalMembers[i];
var type = positionalMember switch
{
PropertySymbol property => property.Type,
FieldSymbol field => field.Type,
_ => throw ExceptionUtilities.Unreachable
};
if (!parameter.Type.Equals(type, TypeCompareKind.AllIgnoreOptions))
{
// There is a mismatch, an error was reported elsewhere
statementsBuilder.Free();
F.CloseMethod(F.ThrowNull());
return;
}
switch (positionalMember)
{
case PropertySymbol property:
// parameter_i = property_i;
statementsBuilder.Add(F.Assignment(F.Parameter(parameter), F.Property(F.This(), property)));
break;
case FieldSymbol field:
// parameter_i = field_i;
statementsBuilder.Add(F.Assignment(F.Parameter(parameter), F.Field(F.This(), field)));
break;
}
}
statementsBuilder.Add(F.Return());
F.CloseMethod(F.Block(statementsBuilder.ToImmutableAndFree()));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SynthesizedRecordDeconstruct : SynthesizedRecordOrdinaryMethod
{
private readonly SynthesizedRecordConstructor _ctor;
private readonly ImmutableArray<Symbol> _positionalMembers;
public SynthesizedRecordDeconstruct(
SourceMemberContainerTypeSymbol containingType,
SynthesizedRecordConstructor ctor,
ImmutableArray<Symbol> positionalMembers,
int memberOffset,
BindingDiagnosticBag diagnostics)
: base(containingType, WellKnownMemberNames.DeconstructMethodName, hasBody: true, memberOffset, diagnostics)
{
Debug.Assert(positionalMembers.All(p => p is PropertySymbol { GetMethod: not null } or FieldSymbol));
_ctor = ctor;
_positionalMembers = positionalMembers;
}
protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics)
{
const DeclarationModifiers result = DeclarationModifiers.Public;
Debug.Assert((result & ~allowedModifiers) == 0);
return result;
}
protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics)
{
var compilation = DeclaringCompilation;
var location = ReturnTypeLocation;
return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Void, location, diagnostics)),
Parameters: _ctor.Parameters.SelectAsArray<ParameterSymbol, ImmutableArray<Location>, ParameterSymbol>(
(param, locations) =>
new SourceSimpleParameterSymbol(owner: this,
param.TypeWithAnnotations,
param.Ordinal,
RefKind.Out,
param.Name,
locations),
arg: Locations),
IsVararg: false,
DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty);
}
protected override int GetParameterCountFromSyntax() => _ctor.ParameterCount;
internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics);
if (ParameterCount != _positionalMembers.Length)
{
// There is a mismatch, an error was reported elsewhere
F.CloseMethod(F.ThrowNull());
return;
}
var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance(_positionalMembers.Length + 1);
for (int i = 0; i < _positionalMembers.Length; i++)
{
var parameter = Parameters[i];
var positionalMember = _positionalMembers[i];
var type = positionalMember switch
{
PropertySymbol property => property.Type,
FieldSymbol field => field.Type,
_ => throw ExceptionUtilities.Unreachable
};
if (!parameter.Type.Equals(type, TypeCompareKind.AllIgnoreOptions))
{
// There is a mismatch, an error was reported elsewhere
statementsBuilder.Free();
F.CloseMethod(F.ThrowNull());
return;
}
switch (positionalMember)
{
case PropertySymbol property:
// parameter_i = property_i;
statementsBuilder.Add(F.Assignment(F.Parameter(parameter), F.Property(F.This(), property)));
break;
case FieldSymbol field:
// parameter_i = field_i;
statementsBuilder.Add(F.Assignment(F.Parameter(parameter), F.Field(F.This(), field)));
break;
}
}
statementsBuilder.Add(F.Return());
F.CloseMethod(F.Block(statementsBuilder.ToImmutableAndFree()));
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/EditorFeatures/Core/Implementation/AddImports/AbstractAddImportsPasteCommandHandler.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 Microsoft.CodeAnalysis.AddMissingImports;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.Implementation.AddImports
{
internal abstract class AbstractAddImportsPasteCommandHandler : IChainedCommandHandler<PasteCommandArgs>
{
/// <summary>
/// The command handler display name
/// </summary>
public abstract string DisplayName { get; }
/// <summary>
/// The thread await dialog text shown to the user if the operation takes a long time
/// </summary>
protected abstract string DialogText { get; }
private readonly IThreadingContext _threadingContext;
public AbstractAddImportsPasteCommandHandler(IThreadingContext threadingContext)
=> _threadingContext = threadingContext;
public CommandState GetCommandState(PasteCommandArgs args, Func<CommandState> nextCommandHandler)
=> nextCommandHandler();
public void ExecuteCommand(PasteCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext)
{
// Check that the feature is enabled before doing any work
var optionValue = args.SubjectBuffer.GetOptionalFeatureOnOffOption(FeatureOnOffOptions.AddImportsOnPaste);
// If the feature is explicitly disabled we can exit early
if (optionValue.HasValue && !optionValue.Value)
{
nextCommandHandler();
return;
}
// Capture the pre-paste caret position
var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer);
if (!caretPosition.HasValue)
{
nextCommandHandler();
return;
}
// Create a tracking span from the pre-paste caret position that will grow as text is inserted.
var trackingSpan = caretPosition.Value.Snapshot.CreateTrackingSpan(caretPosition.Value.Position, 0, SpanTrackingMode.EdgeInclusive);
// Perform the paste command before adding imports
nextCommandHandler();
if (executionContext.OperationContext.UserCancellationToken.IsCancellationRequested)
{
return;
}
try
{
ExecuteCommandWorker(args, executionContext, optionValue, trackingSpan);
}
catch (OperationCanceledException)
{
// According to Editor command handler API guidelines, it's best if we return early if cancellation
// is requested instead of throwing. Otherwise, we could end up in an invalid state due to already
// calling nextCommandHandler().
}
}
private void ExecuteCommandWorker(
PasteCommandArgs args,
CommandExecutionContext executionContext,
bool? optionValue,
ITrackingSpan trackingSpan)
{
if (!args.SubjectBuffer.CanApplyChangeDocumentToWorkspace())
{
return;
}
// Don't perform work if we're inside the interactive window
if (args.TextView.IsNotSurfaceBufferOfTextView(args.SubjectBuffer))
{
return;
}
// Applying the post-paste snapshot to the tracking span gives us the span of pasted text.
var snapshotSpan = trackingSpan.GetSpan(args.SubjectBuffer.CurrentSnapshot);
var textSpan = snapshotSpan.Span.ToTextSpan();
var sourceTextContainer = args.SubjectBuffer.AsTextContainer();
if (!Workspace.TryGetWorkspace(sourceTextContainer, out var workspace))
{
return;
}
var document = sourceTextContainer.GetOpenDocumentInCurrentContext();
if (document is null)
{
return;
}
var experimentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IExperimentationService>();
var enabled = optionValue.HasValue && optionValue.Value
|| experimentationService.IsExperimentEnabled(WellKnownExperimentNames.ImportsOnPasteDefaultEnabled);
if (!enabled)
{
return;
}
using var _ = executionContext.OperationContext.AddScope(allowCancellation: true, DialogText);
var cancellationToken = executionContext.OperationContext.UserCancellationToken;
// We're going to log the same thing on success or failure since this blocks the UI thread. This measurement is
// intended to tell us how long we're blocking the user from typing with this action.
using var blockLogger = Logger.LogBlock(FunctionId.CommandHandler_Paste_ImportsOnPaste, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken);
var addMissingImportsService = document.GetRequiredLanguageService<IAddMissingImportsFeatureService>();
#pragma warning disable VSTHRD102 // Implement internal logic asynchronously
var updatedDocument = _threadingContext.JoinableTaskFactory.Run(() => addMissingImportsService.AddMissingImportsAsync(document, textSpan, cancellationToken));
#pragma warning restore VSTHRD102 // Implement internal logic asynchronously
if (updatedDocument is null)
{
return;
}
workspace.TryApplyChanges(updatedDocument.Project.Solution);
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.AddMissingImports;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.Implementation.AddImports
{
internal abstract class AbstractAddImportsPasteCommandHandler : IChainedCommandHandler<PasteCommandArgs>
{
/// <summary>
/// The command handler display name
/// </summary>
public abstract string DisplayName { get; }
/// <summary>
/// The thread await dialog text shown to the user if the operation takes a long time
/// </summary>
protected abstract string DialogText { get; }
private readonly IThreadingContext _threadingContext;
public AbstractAddImportsPasteCommandHandler(IThreadingContext threadingContext)
=> _threadingContext = threadingContext;
public CommandState GetCommandState(PasteCommandArgs args, Func<CommandState> nextCommandHandler)
=> nextCommandHandler();
public void ExecuteCommand(PasteCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext)
{
// Check that the feature is enabled before doing any work
var optionValue = args.SubjectBuffer.GetOptionalFeatureOnOffOption(FeatureOnOffOptions.AddImportsOnPaste);
// If the feature is explicitly disabled we can exit early
if (optionValue.HasValue && !optionValue.Value)
{
nextCommandHandler();
return;
}
// Capture the pre-paste caret position
var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer);
if (!caretPosition.HasValue)
{
nextCommandHandler();
return;
}
// Create a tracking span from the pre-paste caret position that will grow as text is inserted.
var trackingSpan = caretPosition.Value.Snapshot.CreateTrackingSpan(caretPosition.Value.Position, 0, SpanTrackingMode.EdgeInclusive);
// Perform the paste command before adding imports
nextCommandHandler();
if (executionContext.OperationContext.UserCancellationToken.IsCancellationRequested)
{
return;
}
try
{
ExecuteCommandWorker(args, executionContext, optionValue, trackingSpan);
}
catch (OperationCanceledException)
{
// According to Editor command handler API guidelines, it's best if we return early if cancellation
// is requested instead of throwing. Otherwise, we could end up in an invalid state due to already
// calling nextCommandHandler().
}
}
private void ExecuteCommandWorker(
PasteCommandArgs args,
CommandExecutionContext executionContext,
bool? optionValue,
ITrackingSpan trackingSpan)
{
if (!args.SubjectBuffer.CanApplyChangeDocumentToWorkspace())
{
return;
}
// Don't perform work if we're inside the interactive window
if (args.TextView.IsNotSurfaceBufferOfTextView(args.SubjectBuffer))
{
return;
}
// Applying the post-paste snapshot to the tracking span gives us the span of pasted text.
var snapshotSpan = trackingSpan.GetSpan(args.SubjectBuffer.CurrentSnapshot);
var textSpan = snapshotSpan.Span.ToTextSpan();
var sourceTextContainer = args.SubjectBuffer.AsTextContainer();
if (!Workspace.TryGetWorkspace(sourceTextContainer, out var workspace))
{
return;
}
var document = sourceTextContainer.GetOpenDocumentInCurrentContext();
if (document is null)
{
return;
}
// Enable by default unless the user has explicitly disabled in the settings
var disabled = optionValue.HasValue && !optionValue.Value;
if (disabled)
{
return;
}
using var _ = executionContext.OperationContext.AddScope(allowCancellation: true, DialogText);
var cancellationToken = executionContext.OperationContext.UserCancellationToken;
// We're going to log the same thing on success or failure since this blocks the UI thread. This measurement is
// intended to tell us how long we're blocking the user from typing with this action.
using var blockLogger = Logger.LogBlock(FunctionId.CommandHandler_Paste_ImportsOnPaste, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken);
var addMissingImportsService = document.GetRequiredLanguageService<IAddMissingImportsFeatureService>();
#pragma warning disable VSTHRD102 // Implement internal logic asynchronously
var updatedDocument = _threadingContext.JoinableTaskFactory.Run(() => addMissingImportsService.AddMissingImportsAsync(document, textSpan, cancellationToken));
#pragma warning restore VSTHRD102 // Implement internal logic asynchronously
if (updatedDocument is null)
{
return;
}
workspace.TryApplyChanges(updatedDocument.Project.Solution);
}
}
}
| 1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml.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.Windows;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral;
using Microsoft.CodeAnalysis.Editor.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Fading;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.InlineHints;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.ValidateFormatString;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.ColorSchemes;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
internal partial class AdvancedOptionPageControl : AbstractOptionPageControl
{
private readonly ColorSchemeApplier _colorSchemeApplier;
public AdvancedOptionPageControl(OptionStore optionStore, IComponentModel componentModel, IExperimentationService experimentationService) : base(optionStore)
{
_colorSchemeApplier = componentModel.GetService<ColorSchemeApplier>();
InitializeComponent();
BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.CSharp);
BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.CSharp);
BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.CSharp);
BindToOption(Enable_navigation_to_decompiled_sources, FeatureOnOffOptions.NavigateToDecompiledSources);
BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit);
BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics);
BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds);
BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, () =>
{
// If the option has not been set by the user, check if the option to remove unused references
// is enabled from experimentation. If so, default to that. Otherwise default to disabled
return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) ?? false;
});
BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp);
BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp);
BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp);
BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp);
BindToOption(AddUsingsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.CSharp, () =>
{
// If the option has not been set by the user, check if the option to enable imports on paste
// is enabled from experimentation. If so, default to that. Otherwise default to disabled
return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.ImportsOnPasteDefaultEnabled) ?? false;
});
BindToOption(Split_string_literals_on_enter, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp);
BindToOption(EnterOutliningMode, FeatureOnOffOptions.Outlining, LanguageNames.CSharp);
BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.CSharp);
BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.CSharp);
BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.CSharp);
BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp);
BindToOption(Fade_out_unused_usings, FadingOptions.FadeOutUnusedImports, LanguageNames.CSharp);
BindToOption(Fade_out_unreachable_code, FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp);
BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp);
BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp);
BindToOption(GenerateXmlDocCommentsForTripleSlash, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.CSharp);
BindToOption(InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp);
BindToOption(InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments, FeatureOnOffOptions.AutoInsertBlockCommentStartString, LanguageNames.CSharp);
BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.CSharp);
BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.CSharp);
BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.CSharp);
BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.CSharp);
BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.CSharp);
BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.CSharp);
BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, () =>
{
// If the option has not been set by the user, check if the option is enabled from experimentation.
// If so, default to that. Otherwise default to disabled
return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace) ?? false;
});
BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.CSharp);
BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.CSharp);
BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.CSharp);
BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.CSharp);
BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.CSharp);
BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp);
BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.CSharp);
BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp);
BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.CSharp);
BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.CSharp);
BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme);
BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1);
BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.CSharp);
BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp);
BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.CSharp);
BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.CSharp);
BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.CSharp);
BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.CSharp);
BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.CSharp);
BindToOption(DisplayInlineTypeHints, InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp);
BindToOption(ShowHintsForVariablesWithInferredTypes, InlineHintsOptions.ForImplicitVariableTypes, LanguageNames.CSharp);
BindToOption(ShowHintsForLambdaParameterTypes, InlineHintsOptions.ForLambdaParameterTypes, LanguageNames.CSharp);
BindToOption(ShowHintsForImplicitObjectCreation, InlineHintsOptions.ForImplicitObjectCreation, LanguageNames.CSharp);
// If the option has not been set by the user, check if the option is enabled from experimentation.
// If so, default to that. Otherwise default to disabled
BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.CSharp, () =>
experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.InheritanceMargin) ?? false);
}
// Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started,
// we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered.
internal override void OnLoad()
{
var isSupportedTheme = _colorSchemeApplier.IsSupportedTheme();
var isThemeCustomized = _colorSchemeApplier.IsThemeCustomized();
Editor_color_scheme.Visibility = isSupportedTheme ? Visibility.Visible : Visibility.Collapsed;
Customized_Theme_Warning.Visibility = isSupportedTheme && isThemeCustomized ? Visibility.Visible : Visibility.Collapsed;
Custom_VS_Theme_Warning.Visibility = isSupportedTheme ? Visibility.Collapsed : Visibility.Visible;
UpdatePullDiagnosticsOptions();
UpdateInlineHintsOptions();
base.OnLoad();
}
private void UpdatePullDiagnosticsOptions()
{
var normalPullDiagnosticsOption = OptionStore.GetOption(InternalDiagnosticsOptions.NormalDiagnosticMode);
Enable_pull_diagnostics_experimental_requires_restart.IsChecked = GetDiagnosticModeCheckboxValue(normalPullDiagnosticsOption);
Enable_Razor_pull_diagnostics_experimental_requires_restart.IsChecked = OptionStore.GetOption(InternalDiagnosticsOptions.RazorDiagnosticMode) == DiagnosticMode.Pull;
static bool? GetDiagnosticModeCheckboxValue(DiagnosticMode mode)
{
return mode switch
{
DiagnosticMode.Push => false,
DiagnosticMode.Pull => true,
DiagnosticMode.Default => null,
_ => throw new System.ArgumentException("unknown diagnostic mode"),
};
}
}
private void Enable_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull);
UpdatePullDiagnosticsOptions();
}
private void Enable_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Push);
UpdatePullDiagnosticsOptions();
}
private void Enable_pull_diagnostics_experimental_requires_restart_Indeterminate(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Default);
UpdatePullDiagnosticsOptions();
}
private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Pull);
UpdatePullDiagnosticsOptions();
}
private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Push);
UpdatePullDiagnosticsOptions();
}
private void UpdateInlineHintsOptions()
{
var enabledForParameters = this.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp);
ShowHintsForLiterals.IsEnabled = enabledForParameters;
ShowHintsForNewExpressions.IsEnabled = enabledForParameters;
ShowHintsForEverythingElse.IsEnabled = enabledForParameters;
SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters;
SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters;
var enabledForTypes = this.OptionStore.GetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp);
ShowHintsForVariablesWithInferredTypes.IsEnabled = enabledForTypes;
ShowHintsForLambdaParameterTypes.IsEnabled = enabledForTypes;
ShowHintsForImplicitObjectCreation.IsEnabled = enabledForTypes;
}
private void DisplayInlineParameterNameHints_Checked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, true);
UpdateInlineHintsOptions();
}
private void DisplayInlineParameterNameHints_Unchecked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, false);
UpdateInlineHintsOptions();
}
private void DisplayInlineTypeHints_Checked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, true);
UpdateInlineHintsOptions();
}
private void DisplayInlineTypeHints_Unchecked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, false);
UpdateInlineHintsOptions();
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Windows;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral;
using Microsoft.CodeAnalysis.Editor.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Fading;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.InlineHints;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.ValidateFormatString;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.ColorSchemes;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
internal partial class AdvancedOptionPageControl : AbstractOptionPageControl
{
private readonly ColorSchemeApplier _colorSchemeApplier;
public AdvancedOptionPageControl(OptionStore optionStore, IComponentModel componentModel, IExperimentationService experimentationService) : base(optionStore)
{
_colorSchemeApplier = componentModel.GetService<ColorSchemeApplier>();
InitializeComponent();
BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.CSharp);
BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.CSharp);
BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.CSharp);
BindToOption(Enable_navigation_to_decompiled_sources, FeatureOnOffOptions.NavigateToDecompiledSources);
BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit);
BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics);
BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds);
BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, () =>
{
// If the option has not been set by the user, check if the option to remove unused references
// is enabled from experimentation. If so, default to that. Otherwise default to disabled
return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) ?? false;
});
BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp);
BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp);
BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp);
BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp);
BindToOption(AddUsingsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.CSharp, () =>
{
// This option used to be backed by an experimentation flag but is now enabled by default.
// Having the option still a bool? keeps us from running into storage related issues,
// but if the option was stored as null we want it to be enabled by default
return true;
});
BindToOption(Split_string_literals_on_enter, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp);
BindToOption(EnterOutliningMode, FeatureOnOffOptions.Outlining, LanguageNames.CSharp);
BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.CSharp);
BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.CSharp);
BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.CSharp);
BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp);
BindToOption(Fade_out_unused_usings, FadingOptions.FadeOutUnusedImports, LanguageNames.CSharp);
BindToOption(Fade_out_unreachable_code, FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp);
BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp);
BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp);
BindToOption(GenerateXmlDocCommentsForTripleSlash, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.CSharp);
BindToOption(InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp);
BindToOption(InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments, FeatureOnOffOptions.AutoInsertBlockCommentStartString, LanguageNames.CSharp);
BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.CSharp);
BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.CSharp);
BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.CSharp);
BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.CSharp);
BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.CSharp);
BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.CSharp);
BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, () =>
{
// If the option has not been set by the user, check if the option is enabled from experimentation.
// If so, default to that. Otherwise default to disabled
return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace) ?? false;
});
BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.CSharp);
BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.CSharp);
BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.CSharp);
BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.CSharp);
BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.CSharp);
BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp);
BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.CSharp);
BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp);
BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.CSharp);
BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.CSharp);
BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme);
BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1);
BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.CSharp);
BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp);
BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.CSharp);
BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.CSharp);
BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.CSharp);
BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.CSharp);
BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.CSharp);
BindToOption(DisplayInlineTypeHints, InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp);
BindToOption(ShowHintsForVariablesWithInferredTypes, InlineHintsOptions.ForImplicitVariableTypes, LanguageNames.CSharp);
BindToOption(ShowHintsForLambdaParameterTypes, InlineHintsOptions.ForLambdaParameterTypes, LanguageNames.CSharp);
BindToOption(ShowHintsForImplicitObjectCreation, InlineHintsOptions.ForImplicitObjectCreation, LanguageNames.CSharp);
// If the option has not been set by the user, check if the option is enabled from experimentation.
// If so, default to that. Otherwise default to disabled
BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.CSharp, () =>
experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.InheritanceMargin) ?? false);
}
// Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started,
// we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered.
internal override void OnLoad()
{
var isSupportedTheme = _colorSchemeApplier.IsSupportedTheme();
var isThemeCustomized = _colorSchemeApplier.IsThemeCustomized();
Editor_color_scheme.Visibility = isSupportedTheme ? Visibility.Visible : Visibility.Collapsed;
Customized_Theme_Warning.Visibility = isSupportedTheme && isThemeCustomized ? Visibility.Visible : Visibility.Collapsed;
Custom_VS_Theme_Warning.Visibility = isSupportedTheme ? Visibility.Collapsed : Visibility.Visible;
UpdatePullDiagnosticsOptions();
UpdateInlineHintsOptions();
base.OnLoad();
}
private void UpdatePullDiagnosticsOptions()
{
var normalPullDiagnosticsOption = OptionStore.GetOption(InternalDiagnosticsOptions.NormalDiagnosticMode);
Enable_pull_diagnostics_experimental_requires_restart.IsChecked = GetDiagnosticModeCheckboxValue(normalPullDiagnosticsOption);
Enable_Razor_pull_diagnostics_experimental_requires_restart.IsChecked = OptionStore.GetOption(InternalDiagnosticsOptions.RazorDiagnosticMode) == DiagnosticMode.Pull;
static bool? GetDiagnosticModeCheckboxValue(DiagnosticMode mode)
{
return mode switch
{
DiagnosticMode.Push => false,
DiagnosticMode.Pull => true,
DiagnosticMode.Default => null,
_ => throw new System.ArgumentException("unknown diagnostic mode"),
};
}
}
private void Enable_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull);
UpdatePullDiagnosticsOptions();
}
private void Enable_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Push);
UpdatePullDiagnosticsOptions();
}
private void Enable_pull_diagnostics_experimental_requires_restart_Indeterminate(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Default);
UpdatePullDiagnosticsOptions();
}
private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Pull);
UpdatePullDiagnosticsOptions();
}
private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Push);
UpdatePullDiagnosticsOptions();
}
private void UpdateInlineHintsOptions()
{
var enabledForParameters = this.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp);
ShowHintsForLiterals.IsEnabled = enabledForParameters;
ShowHintsForNewExpressions.IsEnabled = enabledForParameters;
ShowHintsForEverythingElse.IsEnabled = enabledForParameters;
SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters;
SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters;
var enabledForTypes = this.OptionStore.GetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp);
ShowHintsForVariablesWithInferredTypes.IsEnabled = enabledForTypes;
ShowHintsForLambdaParameterTypes.IsEnabled = enabledForTypes;
ShowHintsForImplicitObjectCreation.IsEnabled = enabledForTypes;
}
private void DisplayInlineParameterNameHints_Checked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, true);
UpdateInlineHintsOptions();
}
private void DisplayInlineParameterNameHints_Unchecked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, false);
UpdateInlineHintsOptions();
}
private void DisplayInlineTypeHints_Checked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, true);
UpdateInlineHintsOptions();
}
private void DisplayInlineTypeHints_Unchecked(object sender, RoutedEventArgs e)
{
this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, false);
UpdateInlineHintsOptions();
}
}
}
| 1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAddMissingUsingsOnPaste.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;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpAddMissingUsingsOnPaste : AbstractEditorTest
{
public CSharpAddMissingUsingsOnPaste(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpAddMissingUsingsOnPaste))
{
}
protected override string LanguageName => LanguageNames.CSharp;
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyDisabled()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "False");
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyDisabledWithNull()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, valueString: null);
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyAddImportsOnPaste()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
using var telemetry = VisualStudio.EnableTestTelemetryChannel();
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "True");
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
telemetry.VerifyFired("vs/ide/vbcs/commandhandler/paste/importsonpaste");
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpAddMissingUsingsOnPaste : AbstractEditorTest
{
public CSharpAddMissingUsingsOnPaste(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpAddMissingUsingsOnPaste))
{
}
protected override string LanguageName => LanguageNames.CSharp;
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyDisabled()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "False");
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyEnabledWithNull()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, valueString: null);
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)]
public void VerifyAddImportsOnPaste()
{
var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @"
public class Example
{
}
");
SetUpEditor(@"
using System;
class Program
{
static void Main(string[] args)
{
}
$$
}");
using var telemetry = VisualStudio.EnableTestTelemetryChannel();
VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "True");
VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;");
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
}
Task DoThingAsync() => Task.CompletedTask;
}");
telemetry.VerifyFired("vs/ide/vbcs/commandhandler/paste/importsonpaste");
}
}
}
| 1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Windows
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.DocumentationComments
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment
Imports Microsoft.CodeAnalysis.Editor.Options
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
Imports Microsoft.CodeAnalysis.Experiments
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.Fading
Imports Microsoft.CodeAnalysis.ImplementType
Imports Microsoft.CodeAnalysis.InlineHints
Imports Microsoft.CodeAnalysis.QuickInfo
Imports Microsoft.CodeAnalysis.Remote
Imports Microsoft.CodeAnalysis.SolutionCrawler
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.SymbolSearch
Imports Microsoft.CodeAnalysis.ValidateFormatString
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.ColorSchemes
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Friend Class AdvancedOptionPageControl
Private ReadOnly _colorSchemeApplier As ColorSchemeApplier
Public Sub New(optionStore As OptionStore, componentModel As IComponentModel, experimentationService As IExperimentationService)
MyBase.New(optionStore)
_colorSchemeApplier = componentModel.GetService(Of ColorSchemeApplier)()
InitializeComponent()
' Keep this code in sync with the actual order options appear in Tools | Options
' Analysis
BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.VisualBasic)
BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.VisualBasic)
BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.VisualBasic)
BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit)
BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics)
BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds)
BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences,
Function()
' If the option has Not been set by the user, check if the option to remove unused references
' Is enabled from experimentation. If so, default to that. Otherwise default to disabled
If experimentationService Is Nothing Then
Return False
End If
Return experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences)
End Function)
' Import directives
BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic)
BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic)
BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic)
BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic)
BindToOption(AddMissingImportsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.VisualBasic,
Function()
' If the option has Not been set by the user, check if the option to enable imports on paste
' Is enabled from experimentation. If so, default to that. Otherwise default to disabled
If experimentationService Is Nothing Then
Return False
End If
Return experimentationService.IsExperimentEnabled(WellKnownExperimentNames.ImportsOnPasteDefaultEnabled)
End Function)
' Highlighting
BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.VisualBasic)
BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.VisualBasic)
' Outlining
BindToOption(EnableOutlining, FeatureOnOffOptions.Outlining, LanguageNames.VisualBasic)
BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.VisualBasic)
BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.VisualBasic)
BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.VisualBasic)
BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.VisualBasic)
BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic)
' Fading
BindToOption(Fade_out_unused_imports, FadingOptions.FadeOutUnusedImports, LanguageNames.VisualBasic)
' Block structure guides
BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic)
BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic)
' Comments
BindToOption(GenerateXmlDocCommentsForTripleApostrophes, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.VisualBasic)
BindToOption(InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments, SplitCommentOptions.Enabled, LanguageNames.VisualBasic)
' Editor help
BindToOption(EnableEndConstruct, FeatureOnOffOptions.EndConstruct, LanguageNames.VisualBasic)
BindToOption(EnableLineCommit, FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic)
BindToOption(AutomaticInsertionOfInterfaceAndMustOverrideMembers, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic)
BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.VisualBasic)
BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.VisualBasic)
BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic)
BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.VisualBasic)
' Go To Definition
BindToOption(NavigateToObjectBrowser, VisualStudioNavigationOptions.NavigateToObjectBrowser, LanguageNames.VisualBasic)
BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace,
Function()
' If the option has not been set by the user, check if the option Is enabled from experimentation.
' If so, default to that. Otherwise default to disabled
Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace), False)
End Function)
' Regular expressions
BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.VisualBasic)
BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic)
BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.VisualBasic)
BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.VisualBasic)
' Editor color scheme
BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme)
' Extract method
BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.VisualBasic)
' Implement Interface or Abstract Class
BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.VisualBasic)
BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.VisualBasic)
BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.VisualBasic)
BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.VisualBasic)
' Inline hints
BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1)
BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.VisualBasic)
BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic)
BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.VisualBasic)
BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.VisualBasic)
BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.VisualBasic)
BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.VisualBasic)
BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.VisualBasic)
BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.VisualBasic,
Function()
' If the option has not been set by the user, check if the option Is enabled from experimentation.
' If so, default to that. Otherwise default to disabled
Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.InheritanceMargin), False)
End Function)
End Sub
' Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started,
' we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered.
Friend Overrides Sub OnLoad()
Dim isSupportedTheme = _colorSchemeApplier.IsSupportedTheme()
Dim isCustomized = _colorSchemeApplier.IsThemeCustomized()
Editor_color_scheme.Visibility = If(isSupportedTheme, Visibility.Visible, Visibility.Collapsed)
Customized_Theme_Warning.Visibility = If(isSupportedTheme AndAlso isCustomized, Visibility.Visible, Visibility.Collapsed)
Custom_VS_Theme_Warning.Visibility = If(isSupportedTheme, Visibility.Collapsed, Visibility.Visible)
UpdateInlineHintsOptions()
MyBase.OnLoad()
End Sub
Private Sub UpdateInlineHintsOptions()
Dim enabledForParameters = Me.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) <> False
ShowHintsForLiterals.IsEnabled = enabledForParameters
ShowHintsForNewExpressions.IsEnabled = enabledForParameters
ShowHintsForEverythingElse.IsEnabled = enabledForParameters
SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters
SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters
End Sub
Private Sub DisplayInlineParameterNameHints_Checked()
Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, True)
UpdateInlineHintsOptions()
End Sub
Private Sub DisplayInlineParameterNameHints_Unchecked()
Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, False)
UpdateInlineHintsOptions()
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Windows
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.DocumentationComments
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment
Imports Microsoft.CodeAnalysis.Editor.Options
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
Imports Microsoft.CodeAnalysis.Experiments
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.Fading
Imports Microsoft.CodeAnalysis.ImplementType
Imports Microsoft.CodeAnalysis.InlineHints
Imports Microsoft.CodeAnalysis.QuickInfo
Imports Microsoft.CodeAnalysis.Remote
Imports Microsoft.CodeAnalysis.SolutionCrawler
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.SymbolSearch
Imports Microsoft.CodeAnalysis.ValidateFormatString
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.ColorSchemes
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Friend Class AdvancedOptionPageControl
Private ReadOnly _colorSchemeApplier As ColorSchemeApplier
Public Sub New(optionStore As OptionStore, componentModel As IComponentModel, experimentationService As IExperimentationService)
MyBase.New(optionStore)
_colorSchemeApplier = componentModel.GetService(Of ColorSchemeApplier)()
InitializeComponent()
' Keep this code in sync with the actual order options appear in Tools | Options
' Analysis
BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.VisualBasic)
BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.VisualBasic)
BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.VisualBasic)
BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit)
BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics)
BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds)
BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences,
Function()
' If the option has Not been set by the user, check if the option to remove unused references
' Is enabled from experimentation. If so, default to that. Otherwise default to disabled
If experimentationService Is Nothing Then
Return False
End If
Return experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences)
End Function)
' Import directives
BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic)
BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic)
BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic)
BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic)
BindToOption(AddMissingImportsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.VisualBasic,
Function()
' This option used to be backed by an experimentation flag but Is now enabled by default.
' Having the option still a bool? keeps us from running into storage related issues,
' but if the option was stored as null we want it to be enabled by default
Return True
End Function)
' Highlighting
BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.VisualBasic)
BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.VisualBasic)
' Outlining
BindToOption(EnableOutlining, FeatureOnOffOptions.Outlining, LanguageNames.VisualBasic)
BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.VisualBasic)
BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.VisualBasic)
BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.VisualBasic)
BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.VisualBasic)
BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic)
' Fading
BindToOption(Fade_out_unused_imports, FadingOptions.FadeOutUnusedImports, LanguageNames.VisualBasic)
' Block structure guides
BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic)
BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic)
' Comments
BindToOption(GenerateXmlDocCommentsForTripleApostrophes, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.VisualBasic)
BindToOption(InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments, SplitCommentOptions.Enabled, LanguageNames.VisualBasic)
' Editor help
BindToOption(EnableEndConstruct, FeatureOnOffOptions.EndConstruct, LanguageNames.VisualBasic)
BindToOption(EnableLineCommit, FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic)
BindToOption(AutomaticInsertionOfInterfaceAndMustOverrideMembers, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic)
BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.VisualBasic)
BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.VisualBasic)
BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic)
BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.VisualBasic)
' Go To Definition
BindToOption(NavigateToObjectBrowser, VisualStudioNavigationOptions.NavigateToObjectBrowser, LanguageNames.VisualBasic)
BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace,
Function()
' If the option has not been set by the user, check if the option Is enabled from experimentation.
' If so, default to that. Otherwise default to disabled
Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace), False)
End Function)
' Regular expressions
BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.VisualBasic)
BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic)
BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.VisualBasic)
BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.VisualBasic)
' Editor color scheme
BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme)
' Extract method
BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.VisualBasic)
' Implement Interface or Abstract Class
BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.VisualBasic)
BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.VisualBasic)
BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.VisualBasic)
BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.VisualBasic)
' Inline hints
BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1)
BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.VisualBasic)
BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic)
BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.VisualBasic)
BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.VisualBasic)
BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.VisualBasic)
BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.VisualBasic)
BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.VisualBasic)
BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.VisualBasic,
Function()
' If the option has not been set by the user, check if the option Is enabled from experimentation.
' If so, default to that. Otherwise default to disabled
Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.InheritanceMargin), False)
End Function)
End Sub
' Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started,
' we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered.
Friend Overrides Sub OnLoad()
Dim isSupportedTheme = _colorSchemeApplier.IsSupportedTheme()
Dim isCustomized = _colorSchemeApplier.IsThemeCustomized()
Editor_color_scheme.Visibility = If(isSupportedTheme, Visibility.Visible, Visibility.Collapsed)
Customized_Theme_Warning.Visibility = If(isSupportedTheme AndAlso isCustomized, Visibility.Visible, Visibility.Collapsed)
Custom_VS_Theme_Warning.Visibility = If(isSupportedTheme, Visibility.Collapsed, Visibility.Visible)
UpdateInlineHintsOptions()
MyBase.OnLoad()
End Sub
Private Sub UpdateInlineHintsOptions()
Dim enabledForParameters = Me.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) <> False
ShowHintsForLiterals.IsEnabled = enabledForParameters
ShowHintsForNewExpressions.IsEnabled = enabledForParameters
ShowHintsForEverythingElse.IsEnabled = enabledForParameters
SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters
SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters
End Sub
Private Sub DisplayInlineParameterNameHints_Checked()
Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, True)
UpdateInlineHintsOptions()
End Sub
Private Sub DisplayInlineParameterNameHints_Unchecked()
Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, False)
UpdateInlineHintsOptions()
End Sub
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Workspaces/Core/Portable/Experiments/IExperimentationService.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.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => false;
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string OOPServerGC = "Roslyn.OOPServerGC";
public const string ImportsOnPasteDefaultEnabled = "Roslyn.ImportsOnPasteDefaultEnabled";
public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled";
public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace";
public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences";
public const string LSPCompletion = "Roslyn.LSP.Completion";
public const string CloudCache = "Roslyn.CloudCache";
public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled";
public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor";
public const string InheritanceMargin = "Roslyn.InheritanceMargin";
public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics";
public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch";
}
}
| // Licensed to the .NET Foundation under one or more 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.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => false;
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string OOPServerGC = "Roslyn.OOPServerGC";
public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled";
public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace";
public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences";
public const string LSPCompletion = "Roslyn.LSP.Completion";
public const string CloudCache = "Roslyn.CloudCache";
public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled";
public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor";
public const string InheritanceMargin = "Roslyn.InheritanceMargin";
public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics";
public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch";
}
}
| 1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService+CompatAbstractMetadataFormattingRule.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.CodeAnalysis.Formatting.Rules;
namespace Microsoft.CodeAnalysis.MetadataAsSource
{
internal partial class AbstractMetadataAsSourceService
{
protected abstract class CompatAbstractMetadataFormattingRule : AbstractMetadataFormattingRule
{
#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation)
{
var nextOperationCopy = nextOperation;
AddSuppressOperationsSlow(list, node, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, in NextAnchorIndentationOperationAction nextOperation)
{
var nextOperationCopy = nextOperation;
AddAnchorIndentationOperationsSlow(list, node, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation)
{
var nextOperationCopy = nextOperation;
AddIndentBlockOperationsSlow(list, node, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override void AddAlignTokensOperations(List<AlignTokensOperation> list, SyntaxNode node, in NextAlignTokensOperationAction nextOperation)
{
var nextOperationCopy = nextOperation;
AddAlignTokensOperationsSlow(list, node, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
var previousTokenCopy = previousToken;
var currentTokenCopy = currentToken;
var nextOperationCopy = nextOperation;
return GetAdjustNewLinesOperationSlow(ref previousTokenCopy, ref currentTokenCopy, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation)
{
var previousTokenCopy = previousToken;
var currentTokenCopy = currentToken;
var nextOperationCopy = nextOperation;
return GetAdjustSpacesOperationSlow(ref previousTokenCopy, ref currentTokenCopy, ref nextOperationCopy);
}
#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member
/// <summary>
/// Returns SuppressWrappingIfOnSingleLineOperations under a node either by itself or by
/// filtering/replacing operations returned by NextOperation
/// </summary>
public virtual void AddSuppressOperationsSlow(List<SuppressOperation> list, SyntaxNode node, ref NextSuppressOperationAction nextOperation)
=> base.AddSuppressOperations(list, node, in nextOperation);
/// <summary>
/// returns AnchorIndentationOperations under a node either by itself or by filtering/replacing operations returned by NextOperation
/// </summary>
public virtual void AddAnchorIndentationOperationsSlow(List<AnchorIndentationOperation> list, SyntaxNode node, ref NextAnchorIndentationOperationAction nextOperation)
=> base.AddAnchorIndentationOperations(list, node, in nextOperation);
/// <summary>
/// returns IndentBlockOperations under a node either by itself or by filtering/replacing operations returned by NextOperation
/// </summary>
public virtual void AddIndentBlockOperationsSlow(List<IndentBlockOperation> list, SyntaxNode node, ref NextIndentBlockOperationAction nextOperation)
=> base.AddIndentBlockOperations(list, node, in nextOperation);
/// <summary>
/// returns AlignTokensOperations under a node either by itself or by filtering/replacing operations returned by NextOperation
/// </summary>
public virtual void AddAlignTokensOperationsSlow(List<AlignTokensOperation> list, SyntaxNode node, ref NextAlignTokensOperationAction nextOperation)
=> base.AddAlignTokensOperations(list, node, in nextOperation);
/// <summary>
/// returns AdjustNewLinesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation
/// </summary>
public virtual AdjustNewLinesOperation GetAdjustNewLinesOperationSlow(ref SyntaxToken previousToken, ref SyntaxToken currentToken, ref NextGetAdjustNewLinesOperation nextOperation)
=> base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation);
/// <summary>
/// returns AdjustSpacesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation
/// </summary>
public virtual AdjustSpacesOperation GetAdjustSpacesOperationSlow(ref SyntaxToken previousToken, ref SyntaxToken currentToken, ref NextGetAdjustSpacesOperation nextOperation)
=> base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.CodeAnalysis.Formatting.Rules;
namespace Microsoft.CodeAnalysis.MetadataAsSource
{
internal partial class AbstractMetadataAsSourceService
{
protected abstract class CompatAbstractMetadataFormattingRule : AbstractMetadataFormattingRule
{
#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation)
{
var nextOperationCopy = nextOperation;
AddSuppressOperationsSlow(list, node, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, in NextAnchorIndentationOperationAction nextOperation)
{
var nextOperationCopy = nextOperation;
AddAnchorIndentationOperationsSlow(list, node, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation)
{
var nextOperationCopy = nextOperation;
AddIndentBlockOperationsSlow(list, node, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override void AddAlignTokensOperations(List<AlignTokensOperation> list, SyntaxNode node, in NextAlignTokensOperationAction nextOperation)
{
var nextOperationCopy = nextOperation;
AddAlignTokensOperationsSlow(list, node, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
var previousTokenCopy = previousToken;
var currentTokenCopy = currentToken;
var nextOperationCopy = nextOperation;
return GetAdjustNewLinesOperationSlow(ref previousTokenCopy, ref currentTokenCopy, ref nextOperationCopy);
}
[Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation)
{
var previousTokenCopy = previousToken;
var currentTokenCopy = currentToken;
var nextOperationCopy = nextOperation;
return GetAdjustSpacesOperationSlow(ref previousTokenCopy, ref currentTokenCopy, ref nextOperationCopy);
}
#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member
/// <summary>
/// Returns SuppressWrappingIfOnSingleLineOperations under a node either by itself or by
/// filtering/replacing operations returned by NextOperation
/// </summary>
public virtual void AddSuppressOperationsSlow(List<SuppressOperation> list, SyntaxNode node, ref NextSuppressOperationAction nextOperation)
=> base.AddSuppressOperations(list, node, in nextOperation);
/// <summary>
/// returns AnchorIndentationOperations under a node either by itself or by filtering/replacing operations returned by NextOperation
/// </summary>
public virtual void AddAnchorIndentationOperationsSlow(List<AnchorIndentationOperation> list, SyntaxNode node, ref NextAnchorIndentationOperationAction nextOperation)
=> base.AddAnchorIndentationOperations(list, node, in nextOperation);
/// <summary>
/// returns IndentBlockOperations under a node either by itself or by filtering/replacing operations returned by NextOperation
/// </summary>
public virtual void AddIndentBlockOperationsSlow(List<IndentBlockOperation> list, SyntaxNode node, ref NextIndentBlockOperationAction nextOperation)
=> base.AddIndentBlockOperations(list, node, in nextOperation);
/// <summary>
/// returns AlignTokensOperations under a node either by itself or by filtering/replacing operations returned by NextOperation
/// </summary>
public virtual void AddAlignTokensOperationsSlow(List<AlignTokensOperation> list, SyntaxNode node, ref NextAlignTokensOperationAction nextOperation)
=> base.AddAlignTokensOperations(list, node, in nextOperation);
/// <summary>
/// returns AdjustNewLinesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation
/// </summary>
public virtual AdjustNewLinesOperation GetAdjustNewLinesOperationSlow(ref SyntaxToken previousToken, ref SyntaxToken currentToken, ref NextGetAdjustNewLinesOperation nextOperation)
=> base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation);
/// <summary>
/// returns AdjustSpacesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation
/// </summary>
public virtual AdjustSpacesOperation GetAdjustSpacesOperationSlow(ref SyntaxToken previousToken, ref SyntaxToken currentToken, ref NextGetAdjustSpacesOperation nextOperation)
=> base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation);
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncMainTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
[CompilerTrait(CompilerFeature.AsyncMain)]
public class CodeGenAsyncMainTests : EmitMetadataTestBase
{
[Fact]
public void MultipleMainsOneOfWhichHasBadTaskType_CSharp71_WithMainType()
{
var source = @"
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
static void Main(string[] args) { }
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe.WithMainTypeName("Program"), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (11,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(11, 12));
}
[Fact]
public void MultipleMainsOneOfWhichHasBadTaskType_CSharp7()
{
var source = @"
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
static void Main(string[] args) { }
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
sourceCompilation.VerifyEmitDiagnostics(
// (11,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(11, 12),
// (11,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(11, 22));
}
[Fact]
public void MultipleMainsOneOfWhichHasBadTaskType_CSharp7_WithExplicitMain()
{
var source = @"
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
static void Main(string[] args) { }
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe.WithMainTypeName("Program"), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
sourceCompilation.VerifyEmitDiagnostics(
// (11,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(11, 12));
}
[Fact]
public void MultipleMainsOneOfWhichHasBadTaskType_CSharp71()
{
var source = @"
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
static void Main(string[] args) { }
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (11,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(11, 12),
// (11,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(11, 22));
}
[Fact]
public void GetResultReturnsSomethingElse_CSharp7()
{
var source = @"
using System.Threading.Tasks;
using System;
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public double GetResult() { return 0.0; }
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
}
public class Task<T> {
public Awaiter GetAwaiter() {
return new Awaiter();
}
}
}
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
sourceCompilation.VerifyEmitDiagnostics(
// (25,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(25, 12),
// (25,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(25, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void GetResultReturnsSomethingElse_CSharp71()
{
var source = @"
using System.Threading.Tasks;
using System;
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public double GetResult() { return 0.0; }
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
}
public class Task<T> {
public Awaiter GetAwaiter() {
return new Awaiter();
}
}
}
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (25,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(25, 12),
// (25,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(25, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskOfTGetAwaiterReturnsVoid_CSharp7()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
sourceCompilation.VerifyDiagnostics(
// (12,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(12, 12),
// (12,12): error CS1986: 'await' requires that the type Task<int> have a suitable GetAwaiter method
// static Task<int> Main() {
Diagnostic(ErrorCode.ERR_BadAwaitArg, "Task<int>").WithArguments("System.Threading.Tasks.Task<int>").WithLocation(12, 12),
// (12,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(12, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (2,1): hidden CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(2, 1));
}
[Fact]
public void TaskOfTGetAwaiterReturnsVoid_CSharp71()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyDiagnostics(
// (12,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(12, 12),
// (12,12): error CS1986: 'await' requires that the type Task<int> have a suitable GetAwaiter method
// static Task<int> Main() {
Diagnostic(ErrorCode.ERR_BadAwaitArg, "Task<int>").WithArguments("System.Threading.Tasks.Task<int>").WithLocation(12, 12),
// (12,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(12, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (2,1): hidden CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(2, 1));
}
[Fact]
public void TaskGetAwaiterReturnsVoid()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task {
public void GetAwaiter() {}
}
}
static class Program {
static Task Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (12,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(12, 12),
// (12,12): error CS1986: 'await' requires that the type Task have a suitable GetAwaiter method
// static Task Main() {
Diagnostic(ErrorCode.ERR_BadAwaitArg, "Task").WithArguments("System.Threading.Tasks.Task").WithLocation(12, 12),
// (12,17): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(12, 17),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MissingMethodsOnTask()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task {}
}
static class Program {
static Task Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (10,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(10, 12),
// (10,12): error CS1061: 'Task' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly reference?)
// static Task Main() {
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Task").WithArguments("System.Threading.Tasks.Task", "GetAwaiter").WithLocation(10, 12),
// (10,17): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(10, 17),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void EmitTaskOfIntReturningMainWithoutInt()
{
var corAssembly = @"
namespace System {
public class Object {}
public class Void {}
public abstract class ValueType{}
public struct Int32{}
}";
var corCompilation = CreateEmptyCompilation(corAssembly, options: TestOptions.DebugDll);
corCompilation.VerifyDiagnostics();
var taskAssembly = @"
namespace System.Threading.Tasks {
public class Task<T>{}
}";
var taskCompilation = CreateCompilationWithMscorlib45(taskAssembly, options: TestOptions.DebugDll);
taskCompilation.VerifyDiagnostics();
var source = @"
using System;
using System.Threading.Tasks;
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateEmptyCompilation(source, new[] { corCompilation.ToMetadataReference(), taskCompilation.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.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),
// (6,17): error CS0518: Predefined type 'System.Int32' is not defined or imported
// static Task<int> Main() {
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Task<int>").WithArguments("System.Threading.Tasks.Task<int>", "GetAwaiter").WithLocation(6, 12),
// (6,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(6, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void EmitTaskReturningMainWithoutVoid()
{
var corAssembly = @"
namespace System {
public class Object {}
}";
var corCompilation = CreateEmptyCompilation(corAssembly, options: TestOptions.DebugDll);
corCompilation.VerifyDiagnostics();
var taskAssembly = @"
namespace System.Threading.Tasks {
public class Task{}
}";
var taskCompilation = CreateCompilationWithMscorlib45(taskAssembly, options: TestOptions.DebugDll);
taskCompilation.VerifyDiagnostics();
var source = @"
using System;
using System.Threading.Tasks;
static class Program {
static Task Main() {
return null;
}
}";
var sourceCompilation = CreateEmptyCompilation(source, new[] { corCompilation.ToMetadataReference(), taskCompilation.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.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),
// (6,12): error CS1061: 'Task' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly reference?)
// static Task Main() {
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Task").WithArguments("System.Threading.Tasks.Task", "GetAwaiter").WithLocation(6, 12),
// (6,17): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(6, 17),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void AsyncEmitMainTest()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task Main() {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(""async main"");
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 0);
}
[Fact]
public void AsyncMainTestCodegenWithErrors()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main() {
Console.WriteLine(""hello"");
await Task.Factory.StartNew(() => 5);
Console.WriteLine(""async main"");
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
c.VerifyEmitDiagnostics(
// (6,28): error CS0161: 'Program.Main()': not all code paths return a value
// static async Task<int> Main() {
Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Program.Main()").WithLocation(6, 28));
}
[Fact]
public void AsyncEmitMainOfIntTest_StringArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main(string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(""async main"");
return 10;
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 10);
}
[Fact]
public void AsyncEmitMainOfIntTest_ParamsStringArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main(params string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(""async main"");
return 10;
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 10);
}
[Fact]
public void AsyncEmitMainTest_StringArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task Main(string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(""async main"");
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 0);
}
[Fact]
public void AsyncEmitMainTestCodegenWithErrors_StringArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main(string[] args) {
Console.WriteLine(""hello"");
await Task.Factory.StartNew(() => 5);
Console.WriteLine(""async main"");
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
c.VerifyEmitDiagnostics(
// (6,28): error CS0161: 'Program.Main()': not all code paths return a value
// static async Task<int> Main() {
Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Program.Main(string[])").WithLocation(6, 28));
}
[Fact]
public void AsyncEmitMainOfIntTest_StringArgs_WithArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main(string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(args[0]);
return 10;
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 10, args: new string[] { "async main" });
}
[Fact]
public void AsyncEmitMainTest_StringArgs_WithArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task Main(string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(args[0]);
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 0, args: new string[] { "async main" });
}
[Fact]
public void MainCanBeAsyncWithArgs()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task A.Main(System.String[] args)", entry.ToTestDisplayString());
CompileAndVerify(compilation, expectedReturnCode: 0);
}
[Fact]
public void MainCanReturnTaskWithArgs_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task Main(string[] args)
{
return Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task A.Main(System.String[] args)", entry.ToTestDisplayString());
CompileAndVerify(compilation, expectedReturnCode: 0);
}
[Fact]
public void MainCantBeAsyncWithRefTask()
{
var source = @"
using System.Threading.Tasks;
class A
{
static ref Task Main(string[] args)
{
throw new System.Exception();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics(
// (6,21): warning CS0028: 'A.Main(string[])' has the wrong signature to be an entry point
// static ref Task Main(string[] args)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(string[])").WithLocation(6, 21),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncWithArgs_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7.0. Please use language version 7.1 or greater.
// async static Task Main(string[] args)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task").WithArguments("async main", "7.1").WithLocation(6, 18),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1)
);
}
[Fact]
public void MainCantBeAsyncWithArgs_CSharp7_NoAwait()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task Main(string[] args)
{
return Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task Main(string[] args)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task").WithArguments("async main", "7.1").WithLocation(6, 12),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCanReturnTask()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task Main()
{
await Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task A.Main()", entry.ToTestDisplayString());
var image = compilation.EmitToArray();
using var reader = new PEReader(image);
var metadataReader = reader.GetMetadataReader();
var main = metadataReader.MethodDefinitions.Where(mh => getMethodName(mh) == "<Main>").Single();
Assert.Equal(new[] { "MemberReference:Void System.Diagnostics.DebuggerStepThroughAttribute..ctor()" }, getMethodAttributes(main));
string getMethodName(MethodDefinitionHandle handle)
=> metadataReader.GetString(metadataReader.GetMethodDefinition(handle).Name);
IEnumerable<string> getMethodAttributes(MethodDefinitionHandle handle)
=> metadataReader.GetMethodDefinition(handle).GetCustomAttributes()
.Select(a => metadataReader.Dump(metadataReader.GetCustomAttribute(a).Constructor));
if (ExecutionConditionUtil.IsWindows)
{
_ = ConditionalSkipReason.NativePdbRequiresDesktop;
// Verify asyncInfo.catchHandler
compilation.VerifyPdb("A+<Main>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""A"" methodName=""<Main>"" />
<methods>
<method containingType=""A+<Main>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""A+<>c"" methodName=""<Main>b__0_0"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""48"" document=""1"" />
<entry offset=""0x3e"" hidden=""true"" document=""1"" />
<entry offset=""0x91"" hidden=""true"" document=""1"" />
<entry offset=""0xa9"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0xb1"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x91"" />
<kickoffMethod declaringType=""A"" methodName=""Main"" />
<await yield=""0x50"" resume=""0x6b"" declaringType=""A+<Main>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>", options: PdbValidationOptions.SkipConversionValidation);
}
// The PDB conversion from portable to windows drops the entryPoint node
// Tracked by https://github.com/dotnet/roslyn/issues/34561
}
[Fact]
public void MainCanReturnTask_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task Main()
{
return Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task A.Main()", entry.ToTestDisplayString());
}
[Fact]
public void MainCantBeAsyncVoid_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main()
{
await Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,23): error CS8413: Async Main methods must return Task or Task<int>
// async static void Main()
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main()").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncInt()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static int Main()
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics(
// (6,22): error CS1983: The return type of an async method must be void, Task or Task<T>
// async static int Main()
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "Main").WithLocation(6, 22),
// (6,22): error CS4009: A void or int returning entry point cannot be async
// async static int Main()
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main()").WithLocation(6, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.Null(entry);
}
[Fact]
public void MainCantBeAsyncInt_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static int Main()
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,22): error CS1983: The return type of an async method must be void, Task or Task<T>
// async static int Main()
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "Main").WithLocation(6, 22),
// (6,22): error CS8413: Async Main methods must return Task or Task<int>
// async static int Main()
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main()").WithLocation(6, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCanReturnTaskAndGenericOnInt_WithArgs()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main(string[] args)
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task<System.Int32> A.Main(System.String[] args)", entry.ToTestDisplayString());
}
[Fact]
public void MainCanReturnTaskAndGenericOnInt_WithArgs_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main(string[] args)
{
return Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task<System.Int32> A.Main(System.String[] args)", entry.ToTestDisplayString());
}
[Fact]
public void MainCantBeAsyncAndGenericOnInt_WithArgs_Csharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main(string[] args)
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main(string[] args)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 18),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncAndGenericOnInt_WithArgs_Csharp7_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main(string[] args)
{
return Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main(string[] args)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 12),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCanReturnTaskAndGenericOnInt()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main()
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task<System.Int32> A.Main()", entry.ToTestDisplayString());
}
[Fact]
public void MainCanReturnTaskAndGenericOnInt_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main()
{
return Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task<System.Int32> A.Main()", entry.ToTestDisplayString());
}
[Fact]
public void MainCantBeAsyncAndGenericOnInt_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main()
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 18),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncAndGenericOnInt_CSharp7_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main()
{
return Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 12),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncAndGenericOverFloats()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<float> Main()
{
await Task.Factory.StartNew(() => { });
return 0;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics(
// (6,30): warning CS0028: 'A.Main()' has the wrong signature to be an entry point
// async static Task<float> Main()
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main()").WithLocation(6, 30),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsync_AndGeneric()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main<T>()
{
await Task.Factory.StartNew(() => { });
}
}";
CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)).VerifyDiagnostics(
// (6,23): warning CS0402: 'A.Main<T>()': an entry point cannot be generic or in a generic type
// async static void Main<T>()
Diagnostic(ErrorCode.WRN_MainCantBeGeneric, "Main").WithArguments("A.Main<T>()").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsync_AndBadSig()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main(bool truth)
{
await Task.Factory.StartNew(() => { });
}
}";
CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(
// (6,23): warning CS0028: 'A.Main(bool)' has the wrong signature to be an entry point
// async static void Main(bool truth)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(bool)").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsync_AndGeneric_AndBadSig()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main<T>(bool truth)
{
await Task.Factory.StartNew(() => { });
}
}";
CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(
// (6,23): warning CS0028: 'A.Main<T>(bool)' has the wrong signature to be an entry point
// async static void Main<T>(bool truth)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main<T>(bool)").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskMainAndNonTaskMain()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void TaskMainAndNonTaskMain_CSharp71()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)).VerifyDiagnostics(
// (10,23): warning CS8892: Method 'A.Main(string[])' will not be used as an entry point because a synchronous entry point 'A.Main()' was found.
// async static Task Main(string[] args)
Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("A.Main(string[])", "A.Main()").WithLocation(10, 23)
);
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void AsyncVoidMain_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Async Void Main"");
}
async static int Main()
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Async Void Main"");
return 1;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(
// (11,22): error CS1983: The return type of an async method must be void, Task or Task<T>
// async static int Main()
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "Main").WithLocation(11, 22),
// (11,22): error CS4009: A void or int returning entry point cannot be async
// async static int Main()
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main()").WithLocation(11, 22),
// (6,23): error CS4009: A void or int returning entry point cannot be async
// async static void Main(string[] args)
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main(string[])").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void AsyncVoidMain_CSharp71()
{
var source = @"
using System.Threading.Tasks;
class A
{
static async void Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Async Void Main"");
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)).VerifyDiagnostics(
// (6,23): error CS4009: A void or int returning entry point cannot be async
// static async void Main(string[] args)
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main(string[])").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskMainAndNonTaskMain_WithExplicitMain()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithMainTypeName("A")).VerifyDiagnostics(
// (10,23): warning CS8892: Method 'A.Main(string[])' will not be used as an entry point because a synchronous entry point 'A.Main()' was found.
// async static Task Main(string[] args)
Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("A.Main(string[])", "A.Main()").WithLocation(10, 23));
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void TaskIntAndTaskFloat_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main()
{
System.Console.WriteLine(""Task<int>"");
return 0;
}
async static Task<float> Main(string[] args)
{
System.Console.WriteLine(""Task<float>"");
return 0.0F;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)).VerifyDiagnostics(
// (6,28): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async static Task<int> Main()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(6, 28),
// (12,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async static Task<float> Main(string[] args)
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(12, 30),
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 18),
// (12,30): warning CS0028: 'A.Main(string[])' has the wrong signature to be an entry point
// async static Task<float> Main(string[] args)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(string[])").WithLocation(12, 30),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskIntAndTaskFloat_CSharp7_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main()
{
System.Console.WriteLine(""Task<int>"");
return Task.FromResult(0);
}
static Task<float> Main(string[] args)
{
System.Console.WriteLine(""Task<float>"");
return Task.FromResult(0.0F);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)).VerifyDiagnostics(
// (6,12): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// static Task<int> Main()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 12),
// (12,24): warning CS0028: 'A.Main(string[])' has the wrong signature to be an entry point
// static Task<float> Main(string[] args)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(string[])").WithLocation(12, 24),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskOfFloatMainAndNonTaskMain()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task<float> Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
return 0.0f;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(
// (10,30): warning CS0028: 'A.Main(string[])' has the wrong signature to be an entry point
// async static Task<float> Main(string[] args)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(string[])").WithLocation(11, 30));
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void TaskOfFloatMainAndNonTaskMain_WithExplicitMain()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task<float> Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
return 0.0f;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithMainTypeName("A")).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void ImplementGetAwaiterGetResultViaExtensionMethods()
{
var source = @"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices {
public class ExtensionAttribute {}
}
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
public void GetResult() {
System.Console.Write(""GetResult called"");
}
}
public class Task {}
}
public static class MyExtensions {
public static Awaiter GetAwaiter(this Task task) {
System.Console.Write(""GetAwaiter called | "");
return new Awaiter();
}
}
static class Program {
static Task Main() {
return new Task();
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = sourceCompilation.VerifyEmitDiagnostics(
// (26,43): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// public static Awaiter GetAwaiter(this Task task) {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(26, 43),
// (33,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(33, 12),
// (34,20): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// return new Task();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(34, 20));
CompileAndVerify(sourceCompilation, expectedOutput: "GetAwaiter called | GetResult called");
}
[Fact]
public void ImplementGetAwaiterGetResultViaExtensionMethods_Obsolete()
{
var source = @"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices {
public class ExtensionAttribute {}
}
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
public void GetResult() {
System.Console.Write(""GetResult called"");
}
}
public class Task {}
}
public static class MyExtensions {
[System.Obsolete(""test"")]
public static Awaiter GetAwaiter(this Task task) {
System.Console.Write(""GetAwaiter called | "");
return new Awaiter();
}
}
static class Program {
static Task Main() {
return new Task();
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = sourceCompilation.VerifyEmitDiagnostics(
// (34,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(34, 12),
// (27,43): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// public static Awaiter GetAwaiter(this Task task) {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(27, 43),
// (35,20): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// return new Task();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(35, 20),
// (34,12): warning CS0618: 'MyExtensions.GetAwaiter(Task)' is obsolete: 'test'
// static Task Main() {
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "Task").WithArguments("MyExtensions.GetAwaiter(System.Threading.Tasks.Task)", "test").WithLocation(34, 12));
CompileAndVerify(sourceCompilation, expectedOutput: "GetAwaiter called | GetResult called");
}
[Fact]
public void ImplementGetAwaiterGetResultViaExtensionMethods_ObsoleteFailing()
{
var source = @"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices {
public class ExtensionAttribute {}
}
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
public void GetResult() {}
}
public class Task {}
}
public static class MyExtensions {
[System.Obsolete(""test"", true)]
public static Awaiter GetAwaiter(this Task task) {
return null;
}
}
static class Program {
static Task Main() {
return new Task();
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = sourceCompilation.VerifyEmitDiagnostics(
// (25,43): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// public static Awaiter GetAwaiter(this Task task) {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(25, 43),
// (31,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(31, 12),
// (32,20): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// return new Task();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(32, 20),
// (31,12): warning CS0618: 'MyExtensions.GetAwaiter(Task)' is obsolete: 'test'
// static Task Main() {
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Task").WithArguments("MyExtensions.GetAwaiter(System.Threading.Tasks.Task)", "test").WithLocation(31, 12));
}
[Fact]
[WorkItem(33542, "https://github.com/dotnet/roslyn/issues/33542")]
public void AwaitInFinallyInNestedTry_01()
{
string source =
@"using System.Threading.Tasks;
class Program
{
static async Task Main()
{
try
{
try
{
return;
}
finally
{
await Task.CompletedTask;
}
}
catch
{
}
finally
{
await Task.CompletedTask;
}
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe.WithOptimizationLevel(OptimizationLevel.Release));
var verifier = CompileAndVerify(comp, expectedOutput: "");
verifier.VerifyIL("Program.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"{
// Code size 426 (0x1aa)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
int V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_001f
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_0125
IL_0011: ldarg.0
IL_0012: ldnull
IL_0013: stfld ""object Program.<Main>d__0.<>7__wrap1""
IL_0018: ldarg.0
IL_0019: ldc.i4.0
IL_001a: stfld ""int Program.<Main>d__0.<>7__wrap2""
IL_001f: nop
.try
{
IL_0020: ldloc.0
IL_0021: pop
IL_0022: nop
.try
{
IL_0023: ldloc.0
IL_0024: brfalse.s IL_007e
IL_0026: ldarg.0
IL_0027: ldnull
IL_0028: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_002d: ldarg.0
IL_002e: ldc.i4.0
IL_002f: stfld ""int Program.<Main>d__0.<>7__wrap4""
.try
{
IL_0034: ldarg.0
IL_0035: ldc.i4.1
IL_0036: stfld ""int Program.<Main>d__0.<>7__wrap4""
IL_003b: leave.s IL_0047
}
catch object
{
IL_003d: stloc.1
IL_003e: ldarg.0
IL_003f: ldloc.1
IL_0040: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_0045: leave.s IL_0047
}
IL_0047: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.CompletedTask.get""
IL_004c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_0051: stloc.2
IL_0052: ldloca.s V_2
IL_0054: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0059: brtrue.s IL_009a
IL_005b: ldarg.0
IL_005c: ldc.i4.0
IL_005d: dup
IL_005e: stloc.0
IL_005f: stfld ""int Program.<Main>d__0.<>1__state""
IL_0064: ldarg.0
IL_0065: ldloc.2
IL_0066: stfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_006b: ldarg.0
IL_006c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_0071: ldloca.s V_2
IL_0073: ldarg.0
IL_0074: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Program.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Program.<Main>d__0)""
IL_0079: leave IL_01a9
IL_007e: ldarg.0
IL_007f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_0084: stloc.2
IL_0085: ldarg.0
IL_0086: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_008b: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_0091: ldarg.0
IL_0092: ldc.i4.m1
IL_0093: dup
IL_0094: stloc.0
IL_0095: stfld ""int Program.<Main>d__0.<>1__state""
IL_009a: ldloca.s V_2
IL_009c: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_00a1: ldarg.0
IL_00a2: ldfld ""object Program.<Main>d__0.<>7__wrap3""
IL_00a7: stloc.1
IL_00a8: ldloc.1
IL_00a9: brfalse.s IL_00c0
IL_00ab: ldloc.1
IL_00ac: isinst ""System.Exception""
IL_00b1: dup
IL_00b2: brtrue.s IL_00b6
IL_00b4: ldloc.1
IL_00b5: throw
IL_00b6: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00bb: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00c0: ldarg.0
IL_00c1: ldfld ""int Program.<Main>d__0.<>7__wrap4""
IL_00c6: stloc.3
IL_00c7: ldloc.3
IL_00c8: ldc.i4.1
IL_00c9: bne.un.s IL_00cd
IL_00cb: leave.s IL_00db
IL_00cd: ldarg.0
IL_00ce: ldnull
IL_00cf: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_00d4: leave.s IL_00d9
}
catch object
{
IL_00d6: pop
IL_00d7: leave.s IL_00d9
}
IL_00d9: leave.s IL_00ee
IL_00db: ldarg.0
IL_00dc: ldc.i4.1
IL_00dd: stfld ""int Program.<Main>d__0.<>7__wrap2""
IL_00e2: leave.s IL_00ee
}
catch object
{
IL_00e4: stloc.1
IL_00e5: ldarg.0
IL_00e6: ldloc.1
IL_00e7: stfld ""object Program.<Main>d__0.<>7__wrap1""
IL_00ec: leave.s IL_00ee
}
IL_00ee: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.CompletedTask.get""
IL_00f3: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_00f8: stloc.2
IL_00f9: ldloca.s V_2
IL_00fb: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0100: brtrue.s IL_0141
IL_0102: ldarg.0
IL_0103: ldc.i4.1
IL_0104: dup
IL_0105: stloc.0
IL_0106: stfld ""int Program.<Main>d__0.<>1__state""
IL_010b: ldarg.0
IL_010c: ldloc.2
IL_010d: stfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_0112: ldarg.0
IL_0113: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_0118: ldloca.s V_2
IL_011a: ldarg.0
IL_011b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Program.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Program.<Main>d__0)""
IL_0120: leave IL_01a9
IL_0125: ldarg.0
IL_0126: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_012b: stloc.2
IL_012c: ldarg.0
IL_012d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_0132: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_0138: ldarg.0
IL_0139: ldc.i4.m1
IL_013a: dup
IL_013b: stloc.0
IL_013c: stfld ""int Program.<Main>d__0.<>1__state""
IL_0141: ldloca.s V_2
IL_0143: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_0148: ldarg.0
IL_0149: ldfld ""object Program.<Main>d__0.<>7__wrap1""
IL_014e: stloc.1
IL_014f: ldloc.1
IL_0150: brfalse.s IL_0167
IL_0152: ldloc.1
IL_0153: isinst ""System.Exception""
IL_0158: dup
IL_0159: brtrue.s IL_015d
IL_015b: ldloc.1
IL_015c: throw
IL_015d: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_0162: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_0167: ldarg.0
IL_0168: ldfld ""int Program.<Main>d__0.<>7__wrap2""
IL_016d: stloc.3
IL_016e: ldloc.3
IL_016f: ldc.i4.1
IL_0170: bne.un.s IL_0174
IL_0172: leave.s IL_0196
IL_0174: ldarg.0
IL_0175: ldnull
IL_0176: stfld ""object Program.<Main>d__0.<>7__wrap1""
IL_017b: leave.s IL_0196
}
catch System.Exception
{
IL_017d: stloc.s V_4
IL_017f: ldarg.0
IL_0180: ldc.i4.s -2
IL_0182: stfld ""int Program.<Main>d__0.<>1__state""
IL_0187: ldarg.0
IL_0188: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_018d: ldloc.s V_4
IL_018f: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0194: leave.s IL_01a9
}
IL_0196: ldarg.0
IL_0197: ldc.i4.s -2
IL_0199: stfld ""int Program.<Main>d__0.<>1__state""
IL_019e: ldarg.0
IL_019f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_01a4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_01a9: ret
}");
}
[Fact]
[WorkItem(34720, "https://github.com/dotnet/roslyn/issues/34720")]
public void AwaitInFinallyInNestedTry_02()
{
string source =
@"using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
for (int i = 0; i < 5; i++)
{
using (new MemoryStream())
{
try
{
continue;
}
finally
{
await Task.Delay(1);
}
}
}
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe.WithOptimizationLevel(OptimizationLevel.Release));
var verifier = CompileAndVerify(comp, expectedOutput: "");
verifier.VerifyIL("Program.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"{
// Code size 320 (0x140)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
int V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0021
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: stfld ""int Program.<Main>d__0.<i>5__2""
IL_0011: br IL_0105
IL_0016: ldarg.0
IL_0017: newobj ""System.IO.MemoryStream..ctor()""
IL_001c: stfld ""System.IO.MemoryStream Program.<Main>d__0.<>7__wrap2""
IL_0021: nop
.try
{
IL_0022: ldloc.0
IL_0023: brfalse.s IL_007e
IL_0025: ldarg.0
IL_0026: ldnull
IL_0027: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_002c: ldarg.0
IL_002d: ldc.i4.0
IL_002e: stfld ""int Program.<Main>d__0.<>7__wrap4""
.try
{
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int Program.<Main>d__0.<>7__wrap4""
IL_003a: leave.s IL_0046
}
catch object
{
IL_003c: stloc.1
IL_003d: ldarg.0
IL_003e: ldloc.1
IL_003f: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_0044: leave.s IL_0046
}
IL_0046: ldc.i4.1
IL_0047: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)""
IL_004c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_0051: stloc.2
IL_0052: ldloca.s V_2
IL_0054: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0059: brtrue.s IL_009a
IL_005b: ldarg.0
IL_005c: ldc.i4.0
IL_005d: dup
IL_005e: stloc.0
IL_005f: stfld ""int Program.<Main>d__0.<>1__state""
IL_0064: ldarg.0
IL_0065: ldloc.2
IL_0066: stfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_006b: ldarg.0
IL_006c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_0071: ldloca.s V_2
IL_0073: ldarg.0
IL_0074: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Program.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Program.<Main>d__0)""
IL_0079: leave IL_013f
IL_007e: ldarg.0
IL_007f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_0084: stloc.2
IL_0085: ldarg.0
IL_0086: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_008b: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_0091: ldarg.0
IL_0092: ldc.i4.m1
IL_0093: dup
IL_0094: stloc.0
IL_0095: stfld ""int Program.<Main>d__0.<>1__state""
IL_009a: ldloca.s V_2
IL_009c: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_00a1: ldarg.0
IL_00a2: ldfld ""object Program.<Main>d__0.<>7__wrap3""
IL_00a7: stloc.1
IL_00a8: ldloc.1
IL_00a9: brfalse.s IL_00c0
IL_00ab: ldloc.1
IL_00ac: isinst ""System.Exception""
IL_00b1: dup
IL_00b2: brtrue.s IL_00b6
IL_00b4: ldloc.1
IL_00b5: throw
IL_00b6: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00bb: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00c0: ldarg.0
IL_00c1: ldfld ""int Program.<Main>d__0.<>7__wrap4""
IL_00c6: stloc.3
IL_00c7: ldloc.3
IL_00c8: ldc.i4.1
IL_00c9: bne.un.s IL_00cd
IL_00cb: leave.s IL_00f5
IL_00cd: ldarg.0
IL_00ce: ldnull
IL_00cf: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_00d4: leave.s IL_00ee
}
finally
{
IL_00d6: ldloc.0
IL_00d7: ldc.i4.0
IL_00d8: bge.s IL_00ed
IL_00da: ldarg.0
IL_00db: ldfld ""System.IO.MemoryStream Program.<Main>d__0.<>7__wrap2""
IL_00e0: brfalse.s IL_00ed
IL_00e2: ldarg.0
IL_00e3: ldfld ""System.IO.MemoryStream Program.<Main>d__0.<>7__wrap2""
IL_00e8: callvirt ""void System.IDisposable.Dispose()""
IL_00ed: endfinally
}
IL_00ee: ldarg.0
IL_00ef: ldnull
IL_00f0: stfld ""System.IO.MemoryStream Program.<Main>d__0.<>7__wrap2""
IL_00f5: ldarg.0
IL_00f6: ldfld ""int Program.<Main>d__0.<i>5__2""
IL_00fb: stloc.3
IL_00fc: ldarg.0
IL_00fd: ldloc.3
IL_00fe: ldc.i4.1
IL_00ff: add
IL_0100: stfld ""int Program.<Main>d__0.<i>5__2""
IL_0105: ldarg.0
IL_0106: ldfld ""int Program.<Main>d__0.<i>5__2""
IL_010b: ldc.i4.5
IL_010c: blt IL_0016
IL_0111: leave.s IL_012c
}
catch System.Exception
{
IL_0113: stloc.s V_4
IL_0115: ldarg.0
IL_0116: ldc.i4.s -2
IL_0118: stfld ""int Program.<Main>d__0.<>1__state""
IL_011d: ldarg.0
IL_011e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_0123: ldloc.s V_4
IL_0125: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_012a: leave.s IL_013f
}
IL_012c: ldarg.0
IL_012d: ldc.i4.s -2
IL_012f: stfld ""int Program.<Main>d__0.<>1__state""
IL_0134: ldarg.0
IL_0135: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_013a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_013f: ret
}");
}
[Fact]
public void ValueTask()
{
var source =
@"using System.Threading.Tasks;
class Program
{
static async ValueTask Main()
{
await Task.Delay(0);
}
}";
var comp = CreateCompilationWithTasksExtensions(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (4,28): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static async ValueTask Main()
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(4, 28));
}
[Fact]
public void ValueTaskOfInt()
{
var source =
@"using System.Threading.Tasks;
class Program
{
static async ValueTask<int> Main()
{
await Task.Delay(0);
return 0;
}
}";
var comp = CreateCompilationWithTasksExtensions(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (4,33): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static async ValueTask<int> Main()
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(4, 33));
}
[Fact]
public void TasklikeType()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : System.Attribute
{
public AsyncMethodBuilderAttribute(System.Type t) { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask
{
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
struct MyTaskMethodBuilder
{
private MyTask _task;
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(new MyTask());
internal MyTaskMethodBuilder(MyTask task)
{
_task = task;
}
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => _task;
}
class Program
{
static async MyTask Main()
{
await Task.Delay(0);
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (43,25): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static async MyTask Main()
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(43, 25));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
[CompilerTrait(CompilerFeature.AsyncMain)]
public class CodeGenAsyncMainTests : EmitMetadataTestBase
{
[Fact]
public void MultipleMainsOneOfWhichHasBadTaskType_CSharp71_WithMainType()
{
var source = @"
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
static void Main(string[] args) { }
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe.WithMainTypeName("Program"), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (11,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(11, 12));
}
[Fact]
public void MultipleMainsOneOfWhichHasBadTaskType_CSharp7()
{
var source = @"
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
static void Main(string[] args) { }
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
sourceCompilation.VerifyEmitDiagnostics(
// (11,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(11, 12),
// (11,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(11, 22));
}
[Fact]
public void MultipleMainsOneOfWhichHasBadTaskType_CSharp7_WithExplicitMain()
{
var source = @"
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
static void Main(string[] args) { }
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe.WithMainTypeName("Program"), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
sourceCompilation.VerifyEmitDiagnostics(
// (11,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(11, 12));
}
[Fact]
public void MultipleMainsOneOfWhichHasBadTaskType_CSharp71()
{
var source = @"
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
static void Main(string[] args) { }
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (11,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(11, 12),
// (11,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(11, 22));
}
[Fact]
public void GetResultReturnsSomethingElse_CSharp7()
{
var source = @"
using System.Threading.Tasks;
using System;
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public double GetResult() { return 0.0; }
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
}
public class Task<T> {
public Awaiter GetAwaiter() {
return new Awaiter();
}
}
}
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
sourceCompilation.VerifyEmitDiagnostics(
// (25,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(25, 12),
// (25,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(25, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void GetResultReturnsSomethingElse_CSharp71()
{
var source = @"
using System.Threading.Tasks;
using System;
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public double GetResult() { return 0.0; }
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
}
public class Task<T> {
public Awaiter GetAwaiter() {
return new Awaiter();
}
}
}
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (25,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(25, 12),
// (25,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(25, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskOfTGetAwaiterReturnsVoid_CSharp7()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
sourceCompilation.VerifyDiagnostics(
// (12,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(12, 12),
// (12,12): error CS1986: 'await' requires that the type Task<int> have a suitable GetAwaiter method
// static Task<int> Main() {
Diagnostic(ErrorCode.ERR_BadAwaitArg, "Task<int>").WithArguments("System.Threading.Tasks.Task<int>").WithLocation(12, 12),
// (12,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(12, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (2,1): hidden CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(2, 1));
}
[Fact]
public void TaskOfTGetAwaiterReturnsVoid_CSharp71()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task<T> {
public void GetAwaiter() {}
}
}
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyDiagnostics(
// (12,12): warning CS0436: The type 'Task<T>' in '' conflicts with the imported type 'Task<TResult>' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task<int>").WithArguments("", "System.Threading.Tasks.Task<T>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task<TResult>").WithLocation(12, 12),
// (12,12): error CS1986: 'await' requires that the type Task<int> have a suitable GetAwaiter method
// static Task<int> Main() {
Diagnostic(ErrorCode.ERR_BadAwaitArg, "Task<int>").WithArguments("System.Threading.Tasks.Task<int>").WithLocation(12, 12),
// (12,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(12, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (2,1): hidden CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(2, 1));
}
[Fact]
public void TaskGetAwaiterReturnsVoid()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task {
public void GetAwaiter() {}
}
}
static class Program {
static Task Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (12,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(12, 12),
// (12,12): error CS1986: 'await' requires that the type Task have a suitable GetAwaiter method
// static Task Main() {
Diagnostic(ErrorCode.ERR_BadAwaitArg, "Task").WithArguments("System.Threading.Tasks.Task").WithLocation(12, 12),
// (12,17): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(12, 17),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MissingMethodsOnTask()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace System.Threading.Tasks {
public class Task {}
}
static class Program {
static Task Main() {
return null;
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.VerifyEmitDiagnostics(
// (10,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(10, 12),
// (10,12): error CS1061: 'Task' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly reference?)
// static Task Main() {
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Task").WithArguments("System.Threading.Tasks.Task", "GetAwaiter").WithLocation(10, 12),
// (10,17): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(10, 17),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void EmitTaskOfIntReturningMainWithoutInt()
{
var corAssembly = @"
namespace System {
public class Object {}
public class Void {}
public abstract class ValueType{}
public struct Int32{}
}";
var corCompilation = CreateEmptyCompilation(corAssembly, options: TestOptions.DebugDll);
corCompilation.VerifyDiagnostics();
var taskAssembly = @"
namespace System.Threading.Tasks {
public class Task<T>{}
}";
var taskCompilation = CreateCompilationWithMscorlib45(taskAssembly, options: TestOptions.DebugDll);
taskCompilation.VerifyDiagnostics();
var source = @"
using System;
using System.Threading.Tasks;
static class Program {
static Task<int> Main() {
return null;
}
}";
var sourceCompilation = CreateEmptyCompilation(source, new[] { corCompilation.ToMetadataReference(), taskCompilation.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.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),
// (6,17): error CS0518: Predefined type 'System.Int32' is not defined or imported
// static Task<int> Main() {
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Task<int>").WithArguments("System.Threading.Tasks.Task<int>", "GetAwaiter").WithLocation(6, 12),
// (6,22): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task<int> Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(6, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void EmitTaskReturningMainWithoutVoid()
{
var corAssembly = @"
namespace System {
public class Object {}
}";
var corCompilation = CreateEmptyCompilation(corAssembly, options: TestOptions.DebugDll);
corCompilation.VerifyDiagnostics();
var taskAssembly = @"
namespace System.Threading.Tasks {
public class Task{}
}";
var taskCompilation = CreateCompilationWithMscorlib45(taskAssembly, options: TestOptions.DebugDll);
taskCompilation.VerifyDiagnostics();
var source = @"
using System;
using System.Threading.Tasks;
static class Program {
static Task Main() {
return null;
}
}";
var sourceCompilation = CreateEmptyCompilation(source, new[] { corCompilation.ToMetadataReference(), taskCompilation.ToMetadataReference() }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
sourceCompilation.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),
// (6,12): error CS1061: 'Task' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly reference?)
// static Task Main() {
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Task").WithArguments("System.Threading.Tasks.Task", "GetAwaiter").WithLocation(6, 12),
// (6,17): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static Task Main() {
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(6, 17),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void AsyncEmitMainTest()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task Main() {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(""async main"");
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 0);
}
[Fact]
public void AsyncMainTestCodegenWithErrors()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main() {
Console.WriteLine(""hello"");
await Task.Factory.StartNew(() => 5);
Console.WriteLine(""async main"");
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
c.VerifyEmitDiagnostics(
// (6,28): error CS0161: 'Program.Main()': not all code paths return a value
// static async Task<int> Main() {
Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Program.Main()").WithLocation(6, 28));
}
[Fact]
public void AsyncEmitMainOfIntTest_StringArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main(string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(""async main"");
return 10;
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 10);
}
[Fact]
public void AsyncEmitMainOfIntTest_ParamsStringArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main(params string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(""async main"");
return 10;
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 10);
}
[Fact]
public void AsyncEmitMainTest_StringArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task Main(string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(""async main"");
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 0);
}
[Fact]
public void AsyncEmitMainTestCodegenWithErrors_StringArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main(string[] args) {
Console.WriteLine(""hello"");
await Task.Factory.StartNew(() => 5);
Console.WriteLine(""async main"");
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
c.VerifyEmitDiagnostics(
// (6,28): error CS0161: 'Program.Main()': not all code paths return a value
// static async Task<int> Main() {
Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Program.Main(string[])").WithLocation(6, 28));
}
[Fact]
public void AsyncEmitMainOfIntTest_StringArgs_WithArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task<int> Main(string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(args[0]);
return 10;
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 10, args: new string[] { "async main" });
}
[Fact]
public void AsyncEmitMainTest_StringArgs_WithArgs()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program {
static async Task Main(string[] args) {
Console.Write(""hello "");
await Task.Factory.StartNew(() => 5);
Console.Write(args[0]);
}
}";
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = CompileAndVerify(c, expectedOutput: "hello async main", expectedReturnCode: 0, args: new string[] { "async main" });
}
[Fact]
public void MainCanBeAsyncWithArgs()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task A.Main(System.String[] args)", entry.ToTestDisplayString());
CompileAndVerify(compilation, expectedReturnCode: 0);
}
[Fact]
public void MainCanReturnTaskWithArgs_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task Main(string[] args)
{
return Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task A.Main(System.String[] args)", entry.ToTestDisplayString());
CompileAndVerify(compilation, expectedReturnCode: 0);
}
[Fact]
public void MainCantBeAsyncWithRefTask()
{
var source = @"
using System.Threading.Tasks;
class A
{
static ref Task Main(string[] args)
{
throw new System.Exception();
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics(
// (6,21): warning CS0028: 'A.Main(string[])' has the wrong signature to be an entry point
// static ref Task Main(string[] args)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(string[])").WithLocation(6, 21),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncWithArgs_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7.0. Please use language version 7.1 or greater.
// async static Task Main(string[] args)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task").WithArguments("async main", "7.1").WithLocation(6, 18),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1)
);
}
[Fact]
public void MainCantBeAsyncWithArgs_CSharp7_NoAwait()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task Main(string[] args)
{
return Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task Main(string[] args)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task").WithArguments("async main", "7.1").WithLocation(6, 12),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCanReturnTask()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task Main()
{
await Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task A.Main()", entry.ToTestDisplayString());
var image = compilation.EmitToArray();
using var reader = new PEReader(image);
var metadataReader = reader.GetMetadataReader();
var main = metadataReader.MethodDefinitions.Where(mh => getMethodName(mh) == "<Main>").Single();
Assert.Equal(new[] { "MemberReference:Void System.Diagnostics.DebuggerStepThroughAttribute..ctor()" }, getMethodAttributes(main));
string getMethodName(MethodDefinitionHandle handle)
=> metadataReader.GetString(metadataReader.GetMethodDefinition(handle).Name);
IEnumerable<string> getMethodAttributes(MethodDefinitionHandle handle)
=> metadataReader.GetMethodDefinition(handle).GetCustomAttributes()
.Select(a => metadataReader.Dump(metadataReader.GetCustomAttribute(a).Constructor));
if (ExecutionConditionUtil.IsWindows)
{
_ = ConditionalSkipReason.NativePdbRequiresDesktop;
// Verify asyncInfo.catchHandler
compilation.VerifyPdb("A+<Main>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""A"" methodName=""<Main>"" />
<methods>
<method containingType=""A+<Main>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""A+<>c"" methodName=""<Main>b__0_0"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""48"" document=""1"" />
<entry offset=""0x3e"" hidden=""true"" document=""1"" />
<entry offset=""0x91"" hidden=""true"" document=""1"" />
<entry offset=""0xa9"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0xb1"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x91"" />
<kickoffMethod declaringType=""A"" methodName=""Main"" />
<await yield=""0x50"" resume=""0x6b"" declaringType=""A+<Main>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>", options: PdbValidationOptions.SkipConversionValidation);
}
// The PDB conversion from portable to windows drops the entryPoint node
// Tracked by https://github.com/dotnet/roslyn/issues/34561
}
[Fact]
public void MainCanReturnTask_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task Main()
{
return Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task A.Main()", entry.ToTestDisplayString());
}
[Fact]
public void MainCantBeAsyncVoid_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main()
{
await Task.Factory.StartNew(() => { });
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,23): error CS8413: Async Main methods must return Task or Task<int>
// async static void Main()
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main()").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncInt()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static int Main()
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics(
// (6,22): error CS1983: The return type of an async method must be void, Task or Task<T>
// async static int Main()
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "Main").WithLocation(6, 22),
// (6,22): error CS4009: A void or int returning entry point cannot be async
// async static int Main()
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main()").WithLocation(6, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.Null(entry);
}
[Fact]
public void MainCantBeAsyncInt_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static int Main()
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,22): error CS1983: The return type of an async method must be void, Task or Task<T>
// async static int Main()
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "Main").WithLocation(6, 22),
// (6,22): error CS8413: Async Main methods must return Task or Task<int>
// async static int Main()
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main()").WithLocation(6, 22),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCanReturnTaskAndGenericOnInt_WithArgs()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main(string[] args)
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task<System.Int32> A.Main(System.String[] args)", entry.ToTestDisplayString());
}
[Fact]
public void MainCanReturnTaskAndGenericOnInt_WithArgs_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main(string[] args)
{
return Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task<System.Int32> A.Main(System.String[] args)", entry.ToTestDisplayString());
}
[Fact]
public void MainCantBeAsyncAndGenericOnInt_WithArgs_Csharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main(string[] args)
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main(string[] args)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 18),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncAndGenericOnInt_WithArgs_Csharp7_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main(string[] args)
{
return Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main(string[] args)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 12),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCanReturnTaskAndGenericOnInt()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main()
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task<System.Int32> A.Main()", entry.ToTestDisplayString());
}
[Fact]
public void MainCanReturnTaskAndGenericOnInt_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main()
{
return Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics();
var entry = compilation.GetEntryPoint(CancellationToken.None);
Assert.NotNull(entry);
Assert.Equal("System.Threading.Tasks.Task<System.Int32> A.Main()", entry.ToTestDisplayString());
}
[Fact]
public void MainCantBeAsyncAndGenericOnInt_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main()
{
return await Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 18),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncAndGenericOnInt_CSharp7_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main()
{
return Task.Factory.StartNew(() => 5);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
compilation.VerifyDiagnostics(
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 12),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsyncAndGenericOverFloats()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<float> Main()
{
await Task.Factory.StartNew(() => { });
return 0;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
compilation.VerifyDiagnostics(
// (6,30): warning CS0028: 'A.Main()' has the wrong signature to be an entry point
// async static Task<float> Main()
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main()").WithLocation(6, 30),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsync_AndGeneric()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main<T>()
{
await Task.Factory.StartNew(() => { });
}
}";
CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)).VerifyDiagnostics(
// (6,23): warning CS0402: 'A.Main<T>()': an entry point cannot be generic or in a generic type
// async static void Main<T>()
Diagnostic(ErrorCode.WRN_MainCantBeGeneric, "Main").WithArguments("A.Main<T>()").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsync_AndBadSig()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main(bool truth)
{
await Task.Factory.StartNew(() => { });
}
}";
CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(
// (6,23): warning CS0028: 'A.Main(bool)' has the wrong signature to be an entry point
// async static void Main(bool truth)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(bool)").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void MainCantBeAsync_AndGeneric_AndBadSig()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main<T>(bool truth)
{
await Task.Factory.StartNew(() => { });
}
}";
CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(
// (6,23): warning CS0028: 'A.Main<T>(bool)' has the wrong signature to be an entry point
// async static void Main<T>(bool truth)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main<T>(bool)").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskMainAndNonTaskMain()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void TaskMainAndNonTaskMain_CSharp71()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)).VerifyDiagnostics(
// (10,23): warning CS8892: Method 'A.Main(string[])' will not be used as an entry point because a synchronous entry point 'A.Main()' was found.
// async static Task Main(string[] args)
Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("A.Main(string[])", "A.Main()").WithLocation(10, 23)
);
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void AsyncVoidMain_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static void Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Async Void Main"");
}
async static int Main()
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Async Void Main"");
return 1;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(
// (11,22): error CS1983: The return type of an async method must be void, Task or Task<T>
// async static int Main()
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "Main").WithLocation(11, 22),
// (11,22): error CS4009: A void or int returning entry point cannot be async
// async static int Main()
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main()").WithLocation(11, 22),
// (6,23): error CS4009: A void or int returning entry point cannot be async
// async static void Main(string[] args)
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main(string[])").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void AsyncVoidMain_CSharp71()
{
var source = @"
using System.Threading.Tasks;
class A
{
static async void Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Async Void Main"");
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)).VerifyDiagnostics(
// (6,23): error CS4009: A void or int returning entry point cannot be async
// static async void Main(string[] args)
Diagnostic(ErrorCode.ERR_NonTaskMainCantBeAsync, "Main").WithArguments("A.Main(string[])").WithLocation(6, 23),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskMainAndNonTaskMain_WithExplicitMain()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithMainTypeName("A")).VerifyDiagnostics(
// (10,23): warning CS8892: Method 'A.Main(string[])' will not be used as an entry point because a synchronous entry point 'A.Main()' was found.
// async static Task Main(string[] args)
Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("A.Main(string[])", "A.Main()").WithLocation(10, 23));
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void TaskIntAndTaskFloat_CSharp7()
{
var source = @"
using System.Threading.Tasks;
class A
{
async static Task<int> Main()
{
System.Console.WriteLine(""Task<int>"");
return 0;
}
async static Task<float> Main(string[] args)
{
System.Console.WriteLine(""Task<float>"");
return 0.0F;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)).VerifyDiagnostics(
// (6,28): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async static Task<int> Main()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(6, 28),
// (12,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async static Task<float> Main(string[] args)
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(12, 30),
// (6,18): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// async static Task<int> Main()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 18),
// (12,30): warning CS0028: 'A.Main(string[])' has the wrong signature to be an entry point
// async static Task<float> Main(string[] args)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(string[])").WithLocation(12, 30),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskIntAndTaskFloat_CSharp7_NoAsync()
{
var source = @"
using System.Threading.Tasks;
class A
{
static Task<int> Main()
{
System.Console.WriteLine(""Task<int>"");
return Task.FromResult(0);
}
static Task<float> Main(string[] args)
{
System.Console.WriteLine(""Task<float>"");
return Task.FromResult(0.0F);
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)).VerifyDiagnostics(
// (6,12): error CS8107: Feature 'async main' is not available in C# 7. Please use language version 7.1 or greater.
// static Task<int> Main()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "Task<int>").WithArguments("async main", "7.1").WithLocation(6, 12),
// (12,24): warning CS0028: 'A.Main(string[])' has the wrong signature to be an entry point
// static Task<float> Main(string[] args)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(string[])").WithLocation(12, 24),
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1));
}
[Fact]
public void TaskOfFloatMainAndNonTaskMain()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task<float> Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
return 0.0f;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(
// (10,30): warning CS0028: 'A.Main(string[])' has the wrong signature to be an entry point
// async static Task<float> Main(string[] args)
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("A.Main(string[])").WithLocation(11, 30));
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void TaskOfFloatMainAndNonTaskMain_WithExplicitMain()
{
var source = @"
using System.Threading.Tasks;
class A
{
static void Main()
{
System.Console.WriteLine(""Non Task Main"");
}
async static Task<float> Main(string[] args)
{
await Task.Factory.StartNew(() => { });
System.Console.WriteLine(""Task Main"");
return 0.0f;
}
}";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithMainTypeName("A")).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Non Task Main", expectedReturnCode: 0);
}
[Fact]
public void ImplementGetAwaiterGetResultViaExtensionMethods()
{
var source = @"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices {
public class ExtensionAttribute {}
}
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
public void GetResult() {
System.Console.Write(""GetResult called"");
}
}
public class Task {}
}
public static class MyExtensions {
public static Awaiter GetAwaiter(this Task task) {
System.Console.Write(""GetAwaiter called | "");
return new Awaiter();
}
}
static class Program {
static Task Main() {
return new Task();
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = sourceCompilation.VerifyEmitDiagnostics(
// (26,43): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// public static Awaiter GetAwaiter(this Task task) {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(26, 43),
// (33,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(33, 12),
// (34,20): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// return new Task();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(34, 20));
CompileAndVerify(sourceCompilation, expectedOutput: "GetAwaiter called | GetResult called");
}
[Fact]
public void ImplementGetAwaiterGetResultViaExtensionMethods_Obsolete()
{
var source = @"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices {
public class ExtensionAttribute {}
}
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
public void GetResult() {
System.Console.Write(""GetResult called"");
}
}
public class Task {}
}
public static class MyExtensions {
[System.Obsolete(""test"")]
public static Awaiter GetAwaiter(this Task task) {
System.Console.Write(""GetAwaiter called | "");
return new Awaiter();
}
}
static class Program {
static Task Main() {
return new Task();
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = sourceCompilation.VerifyEmitDiagnostics(
// (34,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(34, 12),
// (27,43): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// public static Awaiter GetAwaiter(this Task task) {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(27, 43),
// (35,20): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// return new Task();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(35, 20),
// (34,12): warning CS0618: 'MyExtensions.GetAwaiter(Task)' is obsolete: 'test'
// static Task Main() {
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "Task").WithArguments("MyExtensions.GetAwaiter(System.Threading.Tasks.Task)", "test").WithLocation(34, 12));
CompileAndVerify(sourceCompilation, expectedOutput: "GetAwaiter called | GetResult called");
}
[Fact]
public void ImplementGetAwaiterGetResultViaExtensionMethods_ObsoleteFailing()
{
var source = @"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices {
public class ExtensionAttribute {}
}
namespace System.Runtime.CompilerServices {
public interface INotifyCompletion {
void OnCompleted(Action action);
}
}
namespace System.Threading.Tasks {
public class Awaiter: System.Runtime.CompilerServices.INotifyCompletion {
public bool IsCompleted => true;
public void OnCompleted(Action action) {}
public void GetResult() {}
}
public class Task {}
}
public static class MyExtensions {
[System.Obsolete(""test"", true)]
public static Awaiter GetAwaiter(this Task task) {
return null;
}
}
static class Program {
static Task Main() {
return new Task();
}
}";
var sourceCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
var verifier = sourceCompilation.VerifyEmitDiagnostics(
// (25,43): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// public static Awaiter GetAwaiter(this Task task) {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(25, 43),
// (31,12): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// static Task Main() {
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(31, 12),
// (32,20): warning CS0436: The type 'Task' in '' conflicts with the imported type 'Task' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// return new Task();
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Task").WithArguments("", "System.Threading.Tasks.Task", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Threading.Tasks.Task").WithLocation(32, 20),
// (31,12): warning CS0618: 'MyExtensions.GetAwaiter(Task)' is obsolete: 'test'
// static Task Main() {
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Task").WithArguments("MyExtensions.GetAwaiter(System.Threading.Tasks.Task)", "test").WithLocation(31, 12));
}
[Fact]
[WorkItem(33542, "https://github.com/dotnet/roslyn/issues/33542")]
public void AwaitInFinallyInNestedTry_01()
{
string source =
@"using System.Threading.Tasks;
class Program
{
static async Task Main()
{
try
{
try
{
return;
}
finally
{
await Task.CompletedTask;
}
}
catch
{
}
finally
{
await Task.CompletedTask;
}
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe.WithOptimizationLevel(OptimizationLevel.Release));
var verifier = CompileAndVerify(comp, expectedOutput: "");
verifier.VerifyIL("Program.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"{
// Code size 426 (0x1aa)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
int V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_001f
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_0125
IL_0011: ldarg.0
IL_0012: ldnull
IL_0013: stfld ""object Program.<Main>d__0.<>7__wrap1""
IL_0018: ldarg.0
IL_0019: ldc.i4.0
IL_001a: stfld ""int Program.<Main>d__0.<>7__wrap2""
IL_001f: nop
.try
{
IL_0020: ldloc.0
IL_0021: pop
IL_0022: nop
.try
{
IL_0023: ldloc.0
IL_0024: brfalse.s IL_007e
IL_0026: ldarg.0
IL_0027: ldnull
IL_0028: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_002d: ldarg.0
IL_002e: ldc.i4.0
IL_002f: stfld ""int Program.<Main>d__0.<>7__wrap4""
.try
{
IL_0034: ldarg.0
IL_0035: ldc.i4.1
IL_0036: stfld ""int Program.<Main>d__0.<>7__wrap4""
IL_003b: leave.s IL_0047
}
catch object
{
IL_003d: stloc.1
IL_003e: ldarg.0
IL_003f: ldloc.1
IL_0040: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_0045: leave.s IL_0047
}
IL_0047: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.CompletedTask.get""
IL_004c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_0051: stloc.2
IL_0052: ldloca.s V_2
IL_0054: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0059: brtrue.s IL_009a
IL_005b: ldarg.0
IL_005c: ldc.i4.0
IL_005d: dup
IL_005e: stloc.0
IL_005f: stfld ""int Program.<Main>d__0.<>1__state""
IL_0064: ldarg.0
IL_0065: ldloc.2
IL_0066: stfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_006b: ldarg.0
IL_006c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_0071: ldloca.s V_2
IL_0073: ldarg.0
IL_0074: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Program.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Program.<Main>d__0)""
IL_0079: leave IL_01a9
IL_007e: ldarg.0
IL_007f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_0084: stloc.2
IL_0085: ldarg.0
IL_0086: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_008b: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_0091: ldarg.0
IL_0092: ldc.i4.m1
IL_0093: dup
IL_0094: stloc.0
IL_0095: stfld ""int Program.<Main>d__0.<>1__state""
IL_009a: ldloca.s V_2
IL_009c: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_00a1: ldarg.0
IL_00a2: ldfld ""object Program.<Main>d__0.<>7__wrap3""
IL_00a7: stloc.1
IL_00a8: ldloc.1
IL_00a9: brfalse.s IL_00c0
IL_00ab: ldloc.1
IL_00ac: isinst ""System.Exception""
IL_00b1: dup
IL_00b2: brtrue.s IL_00b6
IL_00b4: ldloc.1
IL_00b5: throw
IL_00b6: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00bb: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00c0: ldarg.0
IL_00c1: ldfld ""int Program.<Main>d__0.<>7__wrap4""
IL_00c6: stloc.3
IL_00c7: ldloc.3
IL_00c8: ldc.i4.1
IL_00c9: bne.un.s IL_00cd
IL_00cb: leave.s IL_00db
IL_00cd: ldarg.0
IL_00ce: ldnull
IL_00cf: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_00d4: leave.s IL_00d9
}
catch object
{
IL_00d6: pop
IL_00d7: leave.s IL_00d9
}
IL_00d9: leave.s IL_00ee
IL_00db: ldarg.0
IL_00dc: ldc.i4.1
IL_00dd: stfld ""int Program.<Main>d__0.<>7__wrap2""
IL_00e2: leave.s IL_00ee
}
catch object
{
IL_00e4: stloc.1
IL_00e5: ldarg.0
IL_00e6: ldloc.1
IL_00e7: stfld ""object Program.<Main>d__0.<>7__wrap1""
IL_00ec: leave.s IL_00ee
}
IL_00ee: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.CompletedTask.get""
IL_00f3: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_00f8: stloc.2
IL_00f9: ldloca.s V_2
IL_00fb: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0100: brtrue.s IL_0141
IL_0102: ldarg.0
IL_0103: ldc.i4.1
IL_0104: dup
IL_0105: stloc.0
IL_0106: stfld ""int Program.<Main>d__0.<>1__state""
IL_010b: ldarg.0
IL_010c: ldloc.2
IL_010d: stfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_0112: ldarg.0
IL_0113: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_0118: ldloca.s V_2
IL_011a: ldarg.0
IL_011b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Program.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Program.<Main>d__0)""
IL_0120: leave IL_01a9
IL_0125: ldarg.0
IL_0126: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_012b: stloc.2
IL_012c: ldarg.0
IL_012d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_0132: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_0138: ldarg.0
IL_0139: ldc.i4.m1
IL_013a: dup
IL_013b: stloc.0
IL_013c: stfld ""int Program.<Main>d__0.<>1__state""
IL_0141: ldloca.s V_2
IL_0143: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_0148: ldarg.0
IL_0149: ldfld ""object Program.<Main>d__0.<>7__wrap1""
IL_014e: stloc.1
IL_014f: ldloc.1
IL_0150: brfalse.s IL_0167
IL_0152: ldloc.1
IL_0153: isinst ""System.Exception""
IL_0158: dup
IL_0159: brtrue.s IL_015d
IL_015b: ldloc.1
IL_015c: throw
IL_015d: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_0162: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_0167: ldarg.0
IL_0168: ldfld ""int Program.<Main>d__0.<>7__wrap2""
IL_016d: stloc.3
IL_016e: ldloc.3
IL_016f: ldc.i4.1
IL_0170: bne.un.s IL_0174
IL_0172: leave.s IL_0196
IL_0174: ldarg.0
IL_0175: ldnull
IL_0176: stfld ""object Program.<Main>d__0.<>7__wrap1""
IL_017b: leave.s IL_0196
}
catch System.Exception
{
IL_017d: stloc.s V_4
IL_017f: ldarg.0
IL_0180: ldc.i4.s -2
IL_0182: stfld ""int Program.<Main>d__0.<>1__state""
IL_0187: ldarg.0
IL_0188: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_018d: ldloc.s V_4
IL_018f: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0194: leave.s IL_01a9
}
IL_0196: ldarg.0
IL_0197: ldc.i4.s -2
IL_0199: stfld ""int Program.<Main>d__0.<>1__state""
IL_019e: ldarg.0
IL_019f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_01a4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_01a9: ret
}");
}
[Fact]
[WorkItem(34720, "https://github.com/dotnet/roslyn/issues/34720")]
public void AwaitInFinallyInNestedTry_02()
{
string source =
@"using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
for (int i = 0; i < 5; i++)
{
using (new MemoryStream())
{
try
{
continue;
}
finally
{
await Task.Delay(1);
}
}
}
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe.WithOptimizationLevel(OptimizationLevel.Release));
var verifier = CompileAndVerify(comp, expectedOutput: "");
verifier.VerifyIL("Program.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"{
// Code size 320 (0x140)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
int V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0021
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: stfld ""int Program.<Main>d__0.<i>5__2""
IL_0011: br IL_0105
IL_0016: ldarg.0
IL_0017: newobj ""System.IO.MemoryStream..ctor()""
IL_001c: stfld ""System.IO.MemoryStream Program.<Main>d__0.<>7__wrap2""
IL_0021: nop
.try
{
IL_0022: ldloc.0
IL_0023: brfalse.s IL_007e
IL_0025: ldarg.0
IL_0026: ldnull
IL_0027: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_002c: ldarg.0
IL_002d: ldc.i4.0
IL_002e: stfld ""int Program.<Main>d__0.<>7__wrap4""
.try
{
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int Program.<Main>d__0.<>7__wrap4""
IL_003a: leave.s IL_0046
}
catch object
{
IL_003c: stloc.1
IL_003d: ldarg.0
IL_003e: ldloc.1
IL_003f: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_0044: leave.s IL_0046
}
IL_0046: ldc.i4.1
IL_0047: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)""
IL_004c: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_0051: stloc.2
IL_0052: ldloca.s V_2
IL_0054: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0059: brtrue.s IL_009a
IL_005b: ldarg.0
IL_005c: ldc.i4.0
IL_005d: dup
IL_005e: stloc.0
IL_005f: stfld ""int Program.<Main>d__0.<>1__state""
IL_0064: ldarg.0
IL_0065: ldloc.2
IL_0066: stfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_006b: ldarg.0
IL_006c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_0071: ldloca.s V_2
IL_0073: ldarg.0
IL_0074: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Program.<Main>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Program.<Main>d__0)""
IL_0079: leave IL_013f
IL_007e: ldarg.0
IL_007f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_0084: stloc.2
IL_0085: ldarg.0
IL_0086: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Program.<Main>d__0.<>u__1""
IL_008b: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_0091: ldarg.0
IL_0092: ldc.i4.m1
IL_0093: dup
IL_0094: stloc.0
IL_0095: stfld ""int Program.<Main>d__0.<>1__state""
IL_009a: ldloca.s V_2
IL_009c: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_00a1: ldarg.0
IL_00a2: ldfld ""object Program.<Main>d__0.<>7__wrap3""
IL_00a7: stloc.1
IL_00a8: ldloc.1
IL_00a9: brfalse.s IL_00c0
IL_00ab: ldloc.1
IL_00ac: isinst ""System.Exception""
IL_00b1: dup
IL_00b2: brtrue.s IL_00b6
IL_00b4: ldloc.1
IL_00b5: throw
IL_00b6: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00bb: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00c0: ldarg.0
IL_00c1: ldfld ""int Program.<Main>d__0.<>7__wrap4""
IL_00c6: stloc.3
IL_00c7: ldloc.3
IL_00c8: ldc.i4.1
IL_00c9: bne.un.s IL_00cd
IL_00cb: leave.s IL_00f5
IL_00cd: ldarg.0
IL_00ce: ldnull
IL_00cf: stfld ""object Program.<Main>d__0.<>7__wrap3""
IL_00d4: leave.s IL_00ee
}
finally
{
IL_00d6: ldloc.0
IL_00d7: ldc.i4.0
IL_00d8: bge.s IL_00ed
IL_00da: ldarg.0
IL_00db: ldfld ""System.IO.MemoryStream Program.<Main>d__0.<>7__wrap2""
IL_00e0: brfalse.s IL_00ed
IL_00e2: ldarg.0
IL_00e3: ldfld ""System.IO.MemoryStream Program.<Main>d__0.<>7__wrap2""
IL_00e8: callvirt ""void System.IDisposable.Dispose()""
IL_00ed: endfinally
}
IL_00ee: ldarg.0
IL_00ef: ldnull
IL_00f0: stfld ""System.IO.MemoryStream Program.<Main>d__0.<>7__wrap2""
IL_00f5: ldarg.0
IL_00f6: ldfld ""int Program.<Main>d__0.<i>5__2""
IL_00fb: stloc.3
IL_00fc: ldarg.0
IL_00fd: ldloc.3
IL_00fe: ldc.i4.1
IL_00ff: add
IL_0100: stfld ""int Program.<Main>d__0.<i>5__2""
IL_0105: ldarg.0
IL_0106: ldfld ""int Program.<Main>d__0.<i>5__2""
IL_010b: ldc.i4.5
IL_010c: blt IL_0016
IL_0111: leave.s IL_012c
}
catch System.Exception
{
IL_0113: stloc.s V_4
IL_0115: ldarg.0
IL_0116: ldc.i4.s -2
IL_0118: stfld ""int Program.<Main>d__0.<>1__state""
IL_011d: ldarg.0
IL_011e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_0123: ldloc.s V_4
IL_0125: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_012a: leave.s IL_013f
}
IL_012c: ldarg.0
IL_012d: ldc.i4.s -2
IL_012f: stfld ""int Program.<Main>d__0.<>1__state""
IL_0134: ldarg.0
IL_0135: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<Main>d__0.<>t__builder""
IL_013a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_013f: ret
}");
}
[Fact]
public void ValueTask()
{
var source =
@"using System.Threading.Tasks;
class Program
{
static async ValueTask Main()
{
await Task.Delay(0);
}
}";
var comp = CreateCompilationWithTasksExtensions(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (4,28): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static async ValueTask Main()
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(4, 28));
}
[Fact]
public void ValueTaskOfInt()
{
var source =
@"using System.Threading.Tasks;
class Program
{
static async ValueTask<int> Main()
{
await Task.Delay(0);
return 0;
}
}";
var comp = CreateCompilationWithTasksExtensions(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (4,33): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static async ValueTask<int> Main()
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(4, 33));
}
[Fact]
public void TasklikeType()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
class AsyncMethodBuilderAttribute : System.Attribute
{
public AsyncMethodBuilderAttribute(System.Type t) { }
}
}
[AsyncMethodBuilder(typeof(MyTaskMethodBuilder))]
struct MyTask
{
internal Awaiter GetAwaiter() => new Awaiter();
internal class Awaiter : INotifyCompletion
{
public void OnCompleted(Action a) { }
internal bool IsCompleted => true;
internal void GetResult() { }
}
}
struct MyTaskMethodBuilder
{
private MyTask _task;
public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(new MyTask());
internal MyTaskMethodBuilder(MyTask task)
{
_task = task;
}
public void SetStateMachine(IAsyncStateMachine stateMachine) { }
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
stateMachine.MoveNext();
}
public void SetException(Exception e) { }
public void SetResult() { }
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { }
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { }
public MyTask Task => _task;
}
class Program
{
static async MyTask Main()
{
await Task.Delay(0);
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1),
// (43,25): warning CS0028: 'Program.Main()' has the wrong signature to be an entry point
// static async MyTask Main()
Diagnostic(ErrorCode.WRN_InvalidMainSig, "Main").WithArguments("Program.Main()").WithLocation(43, 25));
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrEvalAttribute.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
namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
{
public abstract class DkmClrEvalAttribute
{
internal DkmClrEvalAttribute(string targetMember)
{
this.TargetMember = targetMember;
}
public readonly string TargetMember;
}
}
| // Licensed to the .NET Foundation under one or more 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
namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
{
public abstract class DkmClrEvalAttribute
{
internal DkmClrEvalAttribute(string targetMember)
{
this.TargetMember = targetMember;
}
public readonly string TargetMember;
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/Core/Def/Implementation/TableDataSource/AbstractTableDataSource.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;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
/// <summary>
/// Base implementation of ITableDataSource
/// </summary>
internal abstract class AbstractTableDataSource<TItem, TData> : ITableDataSource
where TItem : TableItem
{
private readonly object _gate;
// This map holds aggregation key to factory
// Any data that shares same aggregation key will de-duplicated to same factory
private readonly Dictionary<object, TableEntriesFactory<TItem, TData>> _map;
// This map holds each data source key to its aggregation key
private readonly Dictionary<object, object> _aggregateKeyMap;
private ImmutableArray<SubscriptionWithoutLock> _subscriptions;
protected bool IsStable;
public AbstractTableDataSource(Workspace workspace)
{
_gate = new object();
_map = new Dictionary<object, TableEntriesFactory<TItem, TData>>();
_aggregateKeyMap = new Dictionary<object, object>();
_subscriptions = ImmutableArray<SubscriptionWithoutLock>.Empty;
Workspace = workspace;
IsStable = true;
}
public Workspace Workspace { get; }
public abstract string DisplayName { get; }
public abstract string SourceTypeIdentifier { get; }
public abstract string Identifier { get; }
public void RefreshAllFactories()
{
ImmutableArray<SubscriptionWithoutLock> snapshot;
List<TableEntriesFactory<TItem, TData>> factories;
lock (_gate)
{
snapshot = _subscriptions;
factories = _map.Values.ToList();
}
// let table manager know that we want to refresh factories.
for (var i = 0; i < snapshot.Length; i++)
{
foreach (var factory in factories)
{
factory.OnRefreshed();
snapshot[i].AddOrUpdate(factory, newFactory: false);
}
}
}
public void Refresh(TableEntriesFactory<TItem, TData> factory)
{
var snapshot = _subscriptions;
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].AddOrUpdate(factory, newFactory: false);
}
}
public void Shutdown()
{
// editor team wants us to update snapshot versions before
// removing factories on shutdown.
RefreshAllFactories();
// and then remove all factories.
ImmutableArray<SubscriptionWithoutLock> snapshot;
lock (_gate)
{
snapshot = _subscriptions;
_map.Clear();
}
// let table manager know that we want to clear all factories
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].RemoveAll();
}
}
public ImmutableArray<TItem> AggregateItems<TKey>(IEnumerable<IGrouping<TKey, TItem>> groupedItems)
{
using var _0 = ArrayBuilder<TItem>.GetInstance(out var aggregateItems);
using var _1 = ArrayBuilder<string>.GetInstance(out var projectNames);
using var _2 = ArrayBuilder<Guid>.GetInstance(out var projectGuids);
string[] stringArrayCache = null;
Guid[] guidArrayCache = null;
static T[] GetOrCreateArray<T>(ref T[] cache, ArrayBuilder<T> value)
=> (cache != null && Enumerable.SequenceEqual(cache, value)) ? cache : (cache = value.ToArray());
foreach (var (_, items) in groupedItems)
{
TItem firstItem = null;
var hasSingle = true;
foreach (var item in items)
{
if (firstItem == null)
{
firstItem = item;
}
else
{
hasSingle = false;
}
if (item.ProjectName != null)
{
projectNames.Add(item.ProjectName);
}
if (item.ProjectGuid != Guid.Empty)
{
projectGuids.Add(item.ProjectGuid);
}
}
if (hasSingle)
{
aggregateItems.Add(firstItem);
}
else
{
projectNames.SortAndRemoveDuplicates(StringComparer.Ordinal);
projectGuids.SortAndRemoveDuplicates(Comparer<Guid>.Default);
aggregateItems.Add((TItem)firstItem.WithAggregatedData(GetOrCreateArray(ref stringArrayCache, projectNames), GetOrCreateArray(ref guidArrayCache, projectGuids)));
}
projectNames.Clear();
projectGuids.Clear();
}
return Order(aggregateItems).ToImmutableArray();
}
public abstract IEqualityComparer<TItem> GroupingComparer { get; }
public abstract IEnumerable<TItem> Order(IEnumerable<TItem> groupedItems);
public abstract AbstractTableEntriesSnapshot<TItem> CreateSnapshot(AbstractTableEntriesSource<TItem> source, int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints);
/// <summary>
/// Get unique ID per given data such as DiagnosticUpdatedArgs or TodoUpdatedArgs.
/// Data contains multiple items belong to one logical chunk. and the Id represents this particular
/// chunk of the data
/// </summary>
public abstract object GetItemKey(TData data);
/// <summary>
/// Create TableEntriesSource for the given data.
/// </summary>
public abstract AbstractTableEntriesSource<TItem> CreateTableEntriesSource(object data);
/// <summary>
/// Get unique ID for given data that will be used to find data whose items needed to be merged together.
///
/// for example, for linked files, data that belong to same physical file will be gathered and items that belong to
/// those data will be de-duplicated.
/// </summary>
protected abstract object GetOrUpdateAggregationKey(TData data);
protected void OnDataAddedOrChanged(TData data)
{
// reuse factory. it is okay to re-use factory since we make sure we remove the factory before
// adding it back
ImmutableArray<SubscriptionWithoutLock> snapshot;
lock (_gate)
{
snapshot = _subscriptions;
GetOrCreateFactory_NoLock(data, out var factory, out var newFactory);
factory.OnDataAddedOrChanged(data);
NotifySubscriptionOnDataAddedOrChanged_NoLock(snapshot, factory, newFactory);
}
}
protected void OnDataRemoved(TData data)
{
lock (_gate)
{
RemoveStaledData(data);
}
}
protected void RemoveStaledData(TData data)
{
OnDataRemoved_NoLock(data);
RemoveAggregateKey_NoLock(data);
}
private void OnDataRemoved_NoLock(TData data)
{
ImmutableArray<SubscriptionWithoutLock> snapshot;
var key = TryGetAggregateKey(data);
if (key == null)
{
// never created before.
return;
}
snapshot = _subscriptions;
if (!_map.TryGetValue(key, out var factory))
{
// never reported about this before
return;
}
// remove this particular item from map
if (!factory.OnDataRemoved(data))
{
// let error list know that factory has changed.
NotifySubscriptionOnDataAddedOrChanged_NoLock(snapshot, factory, newFactory: false);
return;
}
// everything belong to the factory has removed. remove the factory
_map.Remove(key);
// let table manager know that we want to clear the entries
NotifySubscriptionOnDataRemoved_NoLock(snapshot, factory);
}
private static void NotifySubscriptionOnDataAddedOrChanged_NoLock(ImmutableArray<SubscriptionWithoutLock> snapshot, TableEntriesFactory<TItem, TData> factory, bool newFactory)
{
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].AddOrUpdate(factory, newFactory);
}
}
private static void NotifySubscriptionOnDataRemoved_NoLock(ImmutableArray<SubscriptionWithoutLock> snapshot, TableEntriesFactory<TItem, TData> factory)
{
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].Remove(factory);
}
}
private void GetOrCreateFactory_NoLock(TData data, out TableEntriesFactory<TItem, TData> factory, out bool newFactory)
{
newFactory = false;
var key = GetOrUpdateAggregationKey(data);
if (_map.TryGetValue(key, out factory))
{
return;
}
var source = CreateTableEntriesSource(data);
factory = new TableEntriesFactory<TItem, TData>(this, source);
_map.Add(key, factory);
newFactory = true;
}
protected void ChangeStableState(bool stable)
{
ImmutableArray<SubscriptionWithoutLock> snapshot;
lock (_gate)
{
snapshot = _subscriptions;
}
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].IsStable = stable;
}
}
protected void AddAggregateKey(TData data, object aggregateKey)
=> _aggregateKeyMap.Add(GetItemKey(data), aggregateKey);
protected object TryGetAggregateKey(TData data)
{
var key = GetItemKey(data);
if (_aggregateKeyMap.TryGetValue(key, out var aggregateKey))
{
return aggregateKey;
}
return null;
}
private void RemoveAggregateKey_NoLock(TData data)
=> _aggregateKeyMap.Remove(GetItemKey(data));
IDisposable ITableDataSource.Subscribe(ITableDataSink sink)
{
lock (_gate)
{
return new SubscriptionWithoutLock(this, sink);
}
}
internal int NumberOfSubscription_TestOnly
{
get { return _subscriptions.Length; }
}
protected class SubscriptionWithoutLock : IDisposable
{
private readonly AbstractTableDataSource<TItem, TData> _source;
private readonly ITableDataSink _sink;
public SubscriptionWithoutLock(AbstractTableDataSource<TItem, TData> source, ITableDataSink sink)
{
_source = source;
_sink = sink;
Register();
ReportInitialData();
}
public bool IsStable
{
get
{
return _sink.IsStable;
}
set
{
_sink.IsStable = value;
}
}
public void AddOrUpdate(ITableEntriesSnapshotFactory provider, bool newFactory)
{
if (newFactory)
{
_sink.AddFactory(provider);
return;
}
_sink.FactorySnapshotChanged(provider);
}
public void Remove(ITableEntriesSnapshotFactory factory)
=> _sink.RemoveFactory(factory);
public void RemoveAll()
=> _sink.RemoveAllFactories();
public void Dispose()
{
// REVIEW: will closing task hub dispose this subscription?
UnRegister();
}
private void ReportInitialData()
{
foreach (var provider in _source._map.Values)
{
AddOrUpdate(provider, newFactory: true);
}
IsStable = _source.IsStable;
}
private void Register()
=> UpdateSubscriptions(s => s.Add(this));
private void UnRegister()
=> UpdateSubscriptions(s => s.Remove(this));
private void UpdateSubscriptions(Func<ImmutableArray<SubscriptionWithoutLock>, ImmutableArray<SubscriptionWithoutLock>> update)
{
while (true)
{
var current = _source._subscriptions;
var @new = update(current);
// try replace with new list
var registered = ImmutableInterlocked.InterlockedCompareExchange(ref _source._subscriptions, @new, current);
if (registered == current)
{
// succeeded
break;
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
/// <summary>
/// Base implementation of ITableDataSource
/// </summary>
internal abstract class AbstractTableDataSource<TItem, TData> : ITableDataSource
where TItem : TableItem
{
private readonly object _gate;
// This map holds aggregation key to factory
// Any data that shares same aggregation key will de-duplicated to same factory
private readonly Dictionary<object, TableEntriesFactory<TItem, TData>> _map;
// This map holds each data source key to its aggregation key
private readonly Dictionary<object, object> _aggregateKeyMap;
private ImmutableArray<SubscriptionWithoutLock> _subscriptions;
protected bool IsStable;
public AbstractTableDataSource(Workspace workspace)
{
_gate = new object();
_map = new Dictionary<object, TableEntriesFactory<TItem, TData>>();
_aggregateKeyMap = new Dictionary<object, object>();
_subscriptions = ImmutableArray<SubscriptionWithoutLock>.Empty;
Workspace = workspace;
IsStable = true;
}
public Workspace Workspace { get; }
public abstract string DisplayName { get; }
public abstract string SourceTypeIdentifier { get; }
public abstract string Identifier { get; }
public void RefreshAllFactories()
{
ImmutableArray<SubscriptionWithoutLock> snapshot;
List<TableEntriesFactory<TItem, TData>> factories;
lock (_gate)
{
snapshot = _subscriptions;
factories = _map.Values.ToList();
}
// let table manager know that we want to refresh factories.
for (var i = 0; i < snapshot.Length; i++)
{
foreach (var factory in factories)
{
factory.OnRefreshed();
snapshot[i].AddOrUpdate(factory, newFactory: false);
}
}
}
public void Refresh(TableEntriesFactory<TItem, TData> factory)
{
var snapshot = _subscriptions;
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].AddOrUpdate(factory, newFactory: false);
}
}
public void Shutdown()
{
// editor team wants us to update snapshot versions before
// removing factories on shutdown.
RefreshAllFactories();
// and then remove all factories.
ImmutableArray<SubscriptionWithoutLock> snapshot;
lock (_gate)
{
snapshot = _subscriptions;
_map.Clear();
}
// let table manager know that we want to clear all factories
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].RemoveAll();
}
}
public ImmutableArray<TItem> AggregateItems<TKey>(IEnumerable<IGrouping<TKey, TItem>> groupedItems)
{
using var _0 = ArrayBuilder<TItem>.GetInstance(out var aggregateItems);
using var _1 = ArrayBuilder<string>.GetInstance(out var projectNames);
using var _2 = ArrayBuilder<Guid>.GetInstance(out var projectGuids);
string[] stringArrayCache = null;
Guid[] guidArrayCache = null;
static T[] GetOrCreateArray<T>(ref T[] cache, ArrayBuilder<T> value)
=> (cache != null && Enumerable.SequenceEqual(cache, value)) ? cache : (cache = value.ToArray());
foreach (var (_, items) in groupedItems)
{
TItem firstItem = null;
var hasSingle = true;
foreach (var item in items)
{
if (firstItem == null)
{
firstItem = item;
}
else
{
hasSingle = false;
}
if (item.ProjectName != null)
{
projectNames.Add(item.ProjectName);
}
if (item.ProjectGuid != Guid.Empty)
{
projectGuids.Add(item.ProjectGuid);
}
}
if (hasSingle)
{
aggregateItems.Add(firstItem);
}
else
{
projectNames.SortAndRemoveDuplicates(StringComparer.Ordinal);
projectGuids.SortAndRemoveDuplicates(Comparer<Guid>.Default);
aggregateItems.Add((TItem)firstItem.WithAggregatedData(GetOrCreateArray(ref stringArrayCache, projectNames), GetOrCreateArray(ref guidArrayCache, projectGuids)));
}
projectNames.Clear();
projectGuids.Clear();
}
return Order(aggregateItems).ToImmutableArray();
}
public abstract IEqualityComparer<TItem> GroupingComparer { get; }
public abstract IEnumerable<TItem> Order(IEnumerable<TItem> groupedItems);
public abstract AbstractTableEntriesSnapshot<TItem> CreateSnapshot(AbstractTableEntriesSource<TItem> source, int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints);
/// <summary>
/// Get unique ID per given data such as DiagnosticUpdatedArgs or TodoUpdatedArgs.
/// Data contains multiple items belong to one logical chunk. and the Id represents this particular
/// chunk of the data
/// </summary>
public abstract object GetItemKey(TData data);
/// <summary>
/// Create TableEntriesSource for the given data.
/// </summary>
public abstract AbstractTableEntriesSource<TItem> CreateTableEntriesSource(object data);
/// <summary>
/// Get unique ID for given data that will be used to find data whose items needed to be merged together.
///
/// for example, for linked files, data that belong to same physical file will be gathered and items that belong to
/// those data will be de-duplicated.
/// </summary>
protected abstract object GetOrUpdateAggregationKey(TData data);
protected void OnDataAddedOrChanged(TData data)
{
// reuse factory. it is okay to re-use factory since we make sure we remove the factory before
// adding it back
ImmutableArray<SubscriptionWithoutLock> snapshot;
lock (_gate)
{
snapshot = _subscriptions;
GetOrCreateFactory_NoLock(data, out var factory, out var newFactory);
factory.OnDataAddedOrChanged(data);
NotifySubscriptionOnDataAddedOrChanged_NoLock(snapshot, factory, newFactory);
}
}
protected void OnDataRemoved(TData data)
{
lock (_gate)
{
RemoveStaledData(data);
}
}
protected void RemoveStaledData(TData data)
{
OnDataRemoved_NoLock(data);
RemoveAggregateKey_NoLock(data);
}
private void OnDataRemoved_NoLock(TData data)
{
ImmutableArray<SubscriptionWithoutLock> snapshot;
var key = TryGetAggregateKey(data);
if (key == null)
{
// never created before.
return;
}
snapshot = _subscriptions;
if (!_map.TryGetValue(key, out var factory))
{
// never reported about this before
return;
}
// remove this particular item from map
if (!factory.OnDataRemoved(data))
{
// let error list know that factory has changed.
NotifySubscriptionOnDataAddedOrChanged_NoLock(snapshot, factory, newFactory: false);
return;
}
// everything belong to the factory has removed. remove the factory
_map.Remove(key);
// let table manager know that we want to clear the entries
NotifySubscriptionOnDataRemoved_NoLock(snapshot, factory);
}
private static void NotifySubscriptionOnDataAddedOrChanged_NoLock(ImmutableArray<SubscriptionWithoutLock> snapshot, TableEntriesFactory<TItem, TData> factory, bool newFactory)
{
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].AddOrUpdate(factory, newFactory);
}
}
private static void NotifySubscriptionOnDataRemoved_NoLock(ImmutableArray<SubscriptionWithoutLock> snapshot, TableEntriesFactory<TItem, TData> factory)
{
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].Remove(factory);
}
}
private void GetOrCreateFactory_NoLock(TData data, out TableEntriesFactory<TItem, TData> factory, out bool newFactory)
{
newFactory = false;
var key = GetOrUpdateAggregationKey(data);
if (_map.TryGetValue(key, out factory))
{
return;
}
var source = CreateTableEntriesSource(data);
factory = new TableEntriesFactory<TItem, TData>(this, source);
_map.Add(key, factory);
newFactory = true;
}
protected void ChangeStableState(bool stable)
{
ImmutableArray<SubscriptionWithoutLock> snapshot;
lock (_gate)
{
snapshot = _subscriptions;
}
for (var i = 0; i < snapshot.Length; i++)
{
snapshot[i].IsStable = stable;
}
}
protected void AddAggregateKey(TData data, object aggregateKey)
=> _aggregateKeyMap.Add(GetItemKey(data), aggregateKey);
protected object TryGetAggregateKey(TData data)
{
var key = GetItemKey(data);
if (_aggregateKeyMap.TryGetValue(key, out var aggregateKey))
{
return aggregateKey;
}
return null;
}
private void RemoveAggregateKey_NoLock(TData data)
=> _aggregateKeyMap.Remove(GetItemKey(data));
IDisposable ITableDataSource.Subscribe(ITableDataSink sink)
{
lock (_gate)
{
return new SubscriptionWithoutLock(this, sink);
}
}
internal int NumberOfSubscription_TestOnly
{
get { return _subscriptions.Length; }
}
protected class SubscriptionWithoutLock : IDisposable
{
private readonly AbstractTableDataSource<TItem, TData> _source;
private readonly ITableDataSink _sink;
public SubscriptionWithoutLock(AbstractTableDataSource<TItem, TData> source, ITableDataSink sink)
{
_source = source;
_sink = sink;
Register();
ReportInitialData();
}
public bool IsStable
{
get
{
return _sink.IsStable;
}
set
{
_sink.IsStable = value;
}
}
public void AddOrUpdate(ITableEntriesSnapshotFactory provider, bool newFactory)
{
if (newFactory)
{
_sink.AddFactory(provider);
return;
}
_sink.FactorySnapshotChanged(provider);
}
public void Remove(ITableEntriesSnapshotFactory factory)
=> _sink.RemoveFactory(factory);
public void RemoveAll()
=> _sink.RemoveAllFactories();
public void Dispose()
{
// REVIEW: will closing task hub dispose this subscription?
UnRegister();
}
private void ReportInitialData()
{
foreach (var provider in _source._map.Values)
{
AddOrUpdate(provider, newFactory: true);
}
IsStable = _source.IsStable;
}
private void Register()
=> UpdateSubscriptions(s => s.Add(this));
private void UnRegister()
=> UpdateSubscriptions(s => s.Remove(this));
private void UpdateSubscriptions(Func<ImmutableArray<SubscriptionWithoutLock>, ImmutableArray<SubscriptionWithoutLock>> update)
{
while (true)
{
var current = _source._subscriptions;
var @new = update(current);
// try replace with new list
var registered = ImmutableInterlocked.InterlockedCompareExchange(ref _source._subscriptions, @new, current);
if (registered == current)
{
// succeeded
break;
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpExpressionCompiler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpExpressionCompiler : ExpressionCompiler
{
private static readonly DkmCompilerId s_compilerId = new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.CSharp);
public CSharpExpressionCompiler() : base(new CSharpFrameDecoder(), new CSharpLanguageInstructionDecoder())
{
}
internal override DiagnosticFormatter DiagnosticFormatter
{
get { return DebuggerDiagnosticFormatter.Instance; }
}
internal override DkmCompilerId CompilerId
{
get { return s_compilerId; }
}
internal delegate MetadataContext<CSharpMetadataContext> GetMetadataContextDelegate<TAppDomain>(TAppDomain appDomain);
internal delegate void SetMetadataContextDelegate<TAppDomain>(TAppDomain appDomain, MetadataContext<CSharpMetadataContext> metadataContext, bool report);
internal override EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
bool useReferencedModulesOnly)
{
return CreateTypeContext(
appDomain,
ad => ad.GetMetadataContext<CSharpMetadataContext>(),
metadataBlocks,
moduleVersionId,
typeToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly));
}
internal static EvaluationContext CreateTypeContext<TAppDomain>(
TAppDomain appDomain,
GetMetadataContextDelegate<TAppDomain> getMetadataContext,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
MakeAssemblyReferencesKind kind)
{
CSharpCompilation? compilation;
if (kind == MakeAssemblyReferencesKind.DirectReferencesOnly)
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
return EvaluationContext.CreateTypeContext(
compilation,
moduleVersionId,
typeToken);
}
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var previous = getMetadataContext(appDomain);
CSharpMetadataContext previousMetadataContext = default;
if (previous.Matches(metadataBlocks))
{
previous.AssemblyContexts.TryGetValue(contextId, out previousMetadataContext);
}
// Re-use the previous compilation if possible.
compilation = previousMetadataContext.Compilation;
if (compilation == null)
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
}
var context = EvaluationContext.CreateTypeContext(
compilation,
moduleVersionId,
typeToken);
// New type context is not attached to the AppDomain since it is less
// re-usable than the previous attached method context. (We could hold
// on to it if we don't have a previous method context but it's unlikely
// that we evaluated a type-level expression before a method-level.)
Debug.Assert(context != previousMetadataContext.EvaluationContext);
return context;
}
internal override EvaluationContextBase CreateMethodContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Lazy<ImmutableArray<AssemblyReaders>> unusedLazyAssemblyReaders,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
bool useReferencedModulesOnly)
{
return CreateMethodContext(
appDomain,
ad => ad.GetMetadataContext<CSharpMetadataContext>(),
(ad, mc, report) => ad.SetMetadataContext<CSharpMetadataContext>(mc, report),
metadataBlocks,
symReader,
moduleVersionId,
methodToken,
methodVersion,
ilOffset,
localSignatureToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly));
}
internal static EvaluationContext CreateMethodContext<TAppDomain>(
TAppDomain appDomain,
GetMetadataContextDelegate<TAppDomain> getMetadataContext,
SetMetadataContextDelegate<TAppDomain> setMetadataContext,
ImmutableArray<MetadataBlock> metadataBlocks,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
MakeAssemblyReferencesKind kind)
{
CSharpCompilation compilation;
int offset = EvaluationContextBase.NormalizeILOffset(ilOffset);
if (kind == MakeAssemblyReferencesKind.DirectReferencesOnly)
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
return EvaluationContext.CreateMethodContext(
compilation,
symReader,
moduleVersionId,
methodToken,
methodVersion,
offset,
localSignatureToken);
}
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var previous = getMetadataContext(appDomain);
var assemblyContexts = previous.Matches(metadataBlocks) ? previous.AssemblyContexts : ImmutableDictionary<MetadataContextId, CSharpMetadataContext>.Empty;
CSharpMetadataContext previousMetadataContext;
assemblyContexts.TryGetValue(contextId, out previousMetadataContext);
// Re-use the previous compilation if possible.
compilation = previousMetadataContext.Compilation;
if (compilation != null)
{
// Re-use entire context if method scope has not changed.
var previousContext = previousMetadataContext.EvaluationContext;
if (previousContext != null &&
previousContext.MethodContextReuseConstraints.HasValue &&
previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset))
{
return previousContext;
}
}
else
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
}
var context = EvaluationContext.CreateMethodContext(
compilation,
symReader,
moduleVersionId,
methodToken,
methodVersion,
offset,
localSignatureToken);
if (context != previousMetadataContext.EvaluationContext)
{
setMetadataContext(
appDomain,
new MetadataContext<CSharpMetadataContext>(
metadataBlocks,
assemblyContexts.SetItem(contextId, new CSharpMetadataContext(context.Compilation, context))),
report: kind == MakeAssemblyReferencesKind.AllReferences);
}
return context;
}
internal override void RemoveDataItem(DkmClrAppDomain appDomain)
{
appDomain.RemoveMetadataContext<CSharpMetadataContext>();
}
internal override ImmutableArray<MetadataBlock> GetMetadataBlocks(DkmClrAppDomain appDomain, DkmClrRuntimeInstance runtimeInstance)
{
var previous = appDomain.GetMetadataContext<CSharpMetadataContext>();
return runtimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpExpressionCompiler : ExpressionCompiler
{
private static readonly DkmCompilerId s_compilerId = new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.CSharp);
public CSharpExpressionCompiler() : base(new CSharpFrameDecoder(), new CSharpLanguageInstructionDecoder())
{
}
internal override DiagnosticFormatter DiagnosticFormatter
{
get { return DebuggerDiagnosticFormatter.Instance; }
}
internal override DkmCompilerId CompilerId
{
get { return s_compilerId; }
}
internal delegate MetadataContext<CSharpMetadataContext> GetMetadataContextDelegate<TAppDomain>(TAppDomain appDomain);
internal delegate void SetMetadataContextDelegate<TAppDomain>(TAppDomain appDomain, MetadataContext<CSharpMetadataContext> metadataContext, bool report);
internal override EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
bool useReferencedModulesOnly)
{
return CreateTypeContext(
appDomain,
ad => ad.GetMetadataContext<CSharpMetadataContext>(),
metadataBlocks,
moduleVersionId,
typeToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly));
}
internal static EvaluationContext CreateTypeContext<TAppDomain>(
TAppDomain appDomain,
GetMetadataContextDelegate<TAppDomain> getMetadataContext,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
MakeAssemblyReferencesKind kind)
{
CSharpCompilation? compilation;
if (kind == MakeAssemblyReferencesKind.DirectReferencesOnly)
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
return EvaluationContext.CreateTypeContext(
compilation,
moduleVersionId,
typeToken);
}
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var previous = getMetadataContext(appDomain);
CSharpMetadataContext previousMetadataContext = default;
if (previous.Matches(metadataBlocks))
{
previous.AssemblyContexts.TryGetValue(contextId, out previousMetadataContext);
}
// Re-use the previous compilation if possible.
compilation = previousMetadataContext.Compilation;
if (compilation == null)
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
}
var context = EvaluationContext.CreateTypeContext(
compilation,
moduleVersionId,
typeToken);
// New type context is not attached to the AppDomain since it is less
// re-usable than the previous attached method context. (We could hold
// on to it if we don't have a previous method context but it's unlikely
// that we evaluated a type-level expression before a method-level.)
Debug.Assert(context != previousMetadataContext.EvaluationContext);
return context;
}
internal override EvaluationContextBase CreateMethodContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Lazy<ImmutableArray<AssemblyReaders>> unusedLazyAssemblyReaders,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
bool useReferencedModulesOnly)
{
return CreateMethodContext(
appDomain,
ad => ad.GetMetadataContext<CSharpMetadataContext>(),
(ad, mc, report) => ad.SetMetadataContext<CSharpMetadataContext>(mc, report),
metadataBlocks,
symReader,
moduleVersionId,
methodToken,
methodVersion,
ilOffset,
localSignatureToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly));
}
internal static EvaluationContext CreateMethodContext<TAppDomain>(
TAppDomain appDomain,
GetMetadataContextDelegate<TAppDomain> getMetadataContext,
SetMetadataContextDelegate<TAppDomain> setMetadataContext,
ImmutableArray<MetadataBlock> metadataBlocks,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
MakeAssemblyReferencesKind kind)
{
CSharpCompilation compilation;
int offset = EvaluationContextBase.NormalizeILOffset(ilOffset);
if (kind == MakeAssemblyReferencesKind.DirectReferencesOnly)
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
return EvaluationContext.CreateMethodContext(
compilation,
symReader,
moduleVersionId,
methodToken,
methodVersion,
offset,
localSignatureToken);
}
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var previous = getMetadataContext(appDomain);
var assemblyContexts = previous.Matches(metadataBlocks) ? previous.AssemblyContexts : ImmutableDictionary<MetadataContextId, CSharpMetadataContext>.Empty;
CSharpMetadataContext previousMetadataContext;
assemblyContexts.TryGetValue(contextId, out previousMetadataContext);
// Re-use the previous compilation if possible.
compilation = previousMetadataContext.Compilation;
if (compilation != null)
{
// Re-use entire context if method scope has not changed.
var previousContext = previousMetadataContext.EvaluationContext;
if (previousContext != null &&
previousContext.MethodContextReuseConstraints.HasValue &&
previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset))
{
return previousContext;
}
}
else
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
}
var context = EvaluationContext.CreateMethodContext(
compilation,
symReader,
moduleVersionId,
methodToken,
methodVersion,
offset,
localSignatureToken);
if (context != previousMetadataContext.EvaluationContext)
{
setMetadataContext(
appDomain,
new MetadataContext<CSharpMetadataContext>(
metadataBlocks,
assemblyContexts.SetItem(contextId, new CSharpMetadataContext(context.Compilation, context))),
report: kind == MakeAssemblyReferencesKind.AllReferences);
}
return context;
}
internal override void RemoveDataItem(DkmClrAppDomain appDomain)
{
appDomain.RemoveMetadataContext<CSharpMetadataContext>();
}
internal override ImmutableArray<MetadataBlock> GetMetadataBlocks(DkmClrAppDomain appDomain, DkmClrRuntimeInstance runtimeInstance)
{
var previous = appDomain.GetMetadataContext<CSharpMetadataContext>();
return runtimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks);
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/EditorFeatures/Core/Implementation/Indentation/EditorLayerInferredIndentationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Indentation
{
[ExportWorkspaceService(typeof(IInferredIndentationService), ServiceLayer.Editor), Shared]
internal sealed class EditorLayerInferredIndentationService : IInferredIndentationService
{
private readonly IIndentationManagerService _indentationManagerService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EditorLayerInferredIndentationService(IIndentationManagerService indentationManagerService)
{
_indentationManagerService = indentationManagerService;
}
public async Task<DocumentOptionSet> GetDocumentOptionsWithInferredIndentationAsync(Document document, bool explicitFormat, CancellationToken cancellationToken)
{
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var snapshot = text.FindCorrespondingEditorTextSnapshot();
if (snapshot != null)
{
_indentationManagerService.GetIndentation(snapshot.TextBuffer, explicitFormat, out var convertTabsToSpaces, out var tabSize, out var indentSize);
options = options.WithChangedOption(FormattingOptions.UseTabs, !convertTabsToSpaces)
.WithChangedOption(FormattingOptions.IndentationSize, indentSize)
.WithChangedOption(FormattingOptions.TabSize, tabSize);
}
return 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.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Indentation
{
[ExportWorkspaceService(typeof(IInferredIndentationService), ServiceLayer.Editor), Shared]
internal sealed class EditorLayerInferredIndentationService : IInferredIndentationService
{
private readonly IIndentationManagerService _indentationManagerService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EditorLayerInferredIndentationService(IIndentationManagerService indentationManagerService)
{
_indentationManagerService = indentationManagerService;
}
public async Task<DocumentOptionSet> GetDocumentOptionsWithInferredIndentationAsync(Document document, bool explicitFormat, CancellationToken cancellationToken)
{
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var snapshot = text.FindCorrespondingEditorTextSnapshot();
if (snapshot != null)
{
_indentationManagerService.GetIndentation(snapshot.TextBuffer, explicitFormat, out var convertTabsToSpaces, out var tabSize, out var indentSize);
options = options.WithChangedOption(FormattingOptions.UseTabs, !convertTabsToSpaces)
.WithChangedOption(FormattingOptions.IndentationSize, indentSize)
.WithChangedOption(FormattingOptions.TabSize, tabSize);
}
return options;
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Workspaces/Core/Portable/Serialization/SerializerService_Asset.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 System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Serialization
{
/// <summary>
/// serialize and deserialize objects to stream.
/// some of these could be moved into actual object, but putting everything here is a bit easier to find I believe.
/// </summary>
internal partial class SerializerService
{
public void SerializeSourceText(SerializableSourceText text, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (text.Storage is not null)
{
context.AddResource(text.Storage);
writer.WriteInt32((int)text.Storage.ChecksumAlgorithm);
writer.WriteEncoding(text.Storage.Encoding);
writer.WriteInt32((int)SerializationKinds.MemoryMapFile);
writer.WriteString(text.Storage.Name);
writer.WriteInt64(text.Storage.Offset);
writer.WriteInt64(text.Storage.Size);
}
else
{
RoslynDebug.AssertNotNull(text.Text);
writer.WriteInt32((int)text.Text.ChecksumAlgorithm);
writer.WriteEncoding(text.Text.Encoding);
writer.WriteInt32((int)SerializationKinds.Bits);
text.Text.WriteTo(writer, cancellationToken);
}
}
private SerializableSourceText DeserializeSerializableSourceText(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var checksumAlgorithm = (SourceHashAlgorithm)reader.ReadInt32();
var encoding = (Encoding)reader.ReadValue();
var kind = (SerializationKinds)reader.ReadInt32();
if (kind == SerializationKinds.MemoryMapFile)
{
var storage2 = (ITemporaryStorageService2)_storageService;
var name = reader.ReadString();
var offset = reader.ReadInt64();
var size = reader.ReadInt64();
var storage = storage2.AttachTemporaryTextStorage(name, offset, size, checksumAlgorithm, encoding, cancellationToken);
if (storage is ITemporaryTextStorageWithName storageWithName)
{
return new SerializableSourceText(storageWithName);
}
else
{
return new SerializableSourceText(storage.ReadText(cancellationToken));
}
}
Contract.ThrowIfFalse(kind == SerializationKinds.Bits);
return new SerializableSourceText(SourceTextExtensions.ReadFrom(_textService, reader, encoding, cancellationToken));
}
private SourceText DeserializeSourceText(ObjectReader reader, CancellationToken cancellationToken)
{
var serializableSourceText = DeserializeSerializableSourceText(reader, cancellationToken);
return serializableSourceText.Text ?? serializableSourceText.Storage!.ReadText(cancellationToken);
}
public void SerializeCompilationOptions(CompilationOptions options, ObjectWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var language = options.Language;
// TODO: once compiler team adds ability to serialize compilation options to ObjectWriter directly, we won't need this.
writer.WriteString(language);
var service = GetOptionsSerializationService(language);
service.WriteTo(options, writer, cancellationToken);
}
private CompilationOptions DeserializeCompilationOptions(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var language = reader.ReadString();
var service = GetOptionsSerializationService(language);
return service.ReadCompilationOptionsFrom(reader, cancellationToken);
}
public void SerializeParseOptions(ParseOptions options, ObjectWriter writer)
{
var language = options.Language;
// TODO: once compiler team adds ability to serialize parse options to ObjectWriter directly, we won't need this.
writer.WriteString(language);
var service = GetOptionsSerializationService(language);
service.WriteTo(options, writer);
}
private ParseOptions DeserializeParseOptions(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var language = reader.ReadString();
var service = GetOptionsSerializationService(language);
return service.ReadParseOptionsFrom(reader, cancellationToken);
}
public void SerializeProjectReference(ProjectReference reference, ObjectWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
reference.ProjectId.WriteTo(writer);
writer.WriteValue(reference.Aliases.ToArray());
writer.WriteBoolean(reference.EmbedInteropTypes);
}
private static ProjectReference DeserializeProjectReference(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var projectId = ProjectId.ReadFrom(reader);
var aliases = reader.ReadArray<string>();
var embedInteropTypes = reader.ReadBoolean();
return new ProjectReference(projectId, aliases.ToImmutableArrayOrEmpty(), embedInteropTypes);
}
public void SerializeMetadataReference(MetadataReference reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
WriteMetadataReferenceTo(reference, writer, context, cancellationToken);
}
private MetadataReference DeserializeMetadataReference(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return ReadMetadataReferenceFrom(reader, cancellationToken);
}
public void SerializeAnalyzerReference(AnalyzerReference reference, ObjectWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
WriteAnalyzerReferenceTo(reference, writer, cancellationToken);
}
private AnalyzerReference DeserializeAnalyzerReference(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return ReadAnalyzerReferenceFrom(reader, 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.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Serialization
{
/// <summary>
/// serialize and deserialize objects to stream.
/// some of these could be moved into actual object, but putting everything here is a bit easier to find I believe.
/// </summary>
internal partial class SerializerService
{
public void SerializeSourceText(SerializableSourceText text, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (text.Storage is not null)
{
context.AddResource(text.Storage);
writer.WriteInt32((int)text.Storage.ChecksumAlgorithm);
writer.WriteEncoding(text.Storage.Encoding);
writer.WriteInt32((int)SerializationKinds.MemoryMapFile);
writer.WriteString(text.Storage.Name);
writer.WriteInt64(text.Storage.Offset);
writer.WriteInt64(text.Storage.Size);
}
else
{
RoslynDebug.AssertNotNull(text.Text);
writer.WriteInt32((int)text.Text.ChecksumAlgorithm);
writer.WriteEncoding(text.Text.Encoding);
writer.WriteInt32((int)SerializationKinds.Bits);
text.Text.WriteTo(writer, cancellationToken);
}
}
private SerializableSourceText DeserializeSerializableSourceText(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var checksumAlgorithm = (SourceHashAlgorithm)reader.ReadInt32();
var encoding = (Encoding)reader.ReadValue();
var kind = (SerializationKinds)reader.ReadInt32();
if (kind == SerializationKinds.MemoryMapFile)
{
var storage2 = (ITemporaryStorageService2)_storageService;
var name = reader.ReadString();
var offset = reader.ReadInt64();
var size = reader.ReadInt64();
var storage = storage2.AttachTemporaryTextStorage(name, offset, size, checksumAlgorithm, encoding, cancellationToken);
if (storage is ITemporaryTextStorageWithName storageWithName)
{
return new SerializableSourceText(storageWithName);
}
else
{
return new SerializableSourceText(storage.ReadText(cancellationToken));
}
}
Contract.ThrowIfFalse(kind == SerializationKinds.Bits);
return new SerializableSourceText(SourceTextExtensions.ReadFrom(_textService, reader, encoding, cancellationToken));
}
private SourceText DeserializeSourceText(ObjectReader reader, CancellationToken cancellationToken)
{
var serializableSourceText = DeserializeSerializableSourceText(reader, cancellationToken);
return serializableSourceText.Text ?? serializableSourceText.Storage!.ReadText(cancellationToken);
}
public void SerializeCompilationOptions(CompilationOptions options, ObjectWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var language = options.Language;
// TODO: once compiler team adds ability to serialize compilation options to ObjectWriter directly, we won't need this.
writer.WriteString(language);
var service = GetOptionsSerializationService(language);
service.WriteTo(options, writer, cancellationToken);
}
private CompilationOptions DeserializeCompilationOptions(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var language = reader.ReadString();
var service = GetOptionsSerializationService(language);
return service.ReadCompilationOptionsFrom(reader, cancellationToken);
}
public void SerializeParseOptions(ParseOptions options, ObjectWriter writer)
{
var language = options.Language;
// TODO: once compiler team adds ability to serialize parse options to ObjectWriter directly, we won't need this.
writer.WriteString(language);
var service = GetOptionsSerializationService(language);
service.WriteTo(options, writer);
}
private ParseOptions DeserializeParseOptions(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var language = reader.ReadString();
var service = GetOptionsSerializationService(language);
return service.ReadParseOptionsFrom(reader, cancellationToken);
}
public void SerializeProjectReference(ProjectReference reference, ObjectWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
reference.ProjectId.WriteTo(writer);
writer.WriteValue(reference.Aliases.ToArray());
writer.WriteBoolean(reference.EmbedInteropTypes);
}
private static ProjectReference DeserializeProjectReference(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var projectId = ProjectId.ReadFrom(reader);
var aliases = reader.ReadArray<string>();
var embedInteropTypes = reader.ReadBoolean();
return new ProjectReference(projectId, aliases.ToImmutableArrayOrEmpty(), embedInteropTypes);
}
public void SerializeMetadataReference(MetadataReference reference, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
WriteMetadataReferenceTo(reference, writer, context, cancellationToken);
}
private MetadataReference DeserializeMetadataReference(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return ReadMetadataReferenceFrom(reader, cancellationToken);
}
public void SerializeAnalyzerReference(AnalyzerReference reference, ObjectWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
WriteAnalyzerReferenceTo(reference, writer, cancellationToken);
}
private AnalyzerReference DeserializeAnalyzerReference(ObjectReader reader, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return ReadAnalyzerReferenceFrom(reader, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectManagementService.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.Composition;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.ProjectManagement;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Roslyn.Utilities;
namespace Roslyn.VisualStudio.Services.Implementation.ProjectSystem
{
[ExportWorkspaceService(typeof(IProjectManagementService), ServiceLayer.Host), Shared]
internal class VisualStudioProjectManagementService : ForegroundThreadAffinitizedObject, IProjectManagementService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioProjectManagementService(IThreadingContext threadingContext)
: base(threadingContext)
{
}
public string GetDefaultNamespace(Microsoft.CodeAnalysis.Project project, Workspace workspace)
{
this.AssertIsForeground();
if (project.Language == LanguageNames.VisualBasic)
{
return "";
}
var defaultNamespace = "";
if (workspace is VisualStudioWorkspaceImpl vsWorkspace)
{
vsWorkspace.GetProjectData(project.Id,
out _, out var envDTEProject);
try
{
defaultNamespace = (string)envDTEProject.ProjectItems.ContainingProject.Properties.Item("DefaultNamespace").Value; // Do not Localize
}
catch (ArgumentException)
{
// DefaultNamespace does not exist for this project.
}
}
return defaultNamespace;
}
public IList<string> GetFolders(ProjectId projectId, Workspace workspace)
{
var folders = new List<string>();
if (workspace is VisualStudioWorkspaceImpl vsWorkspace)
{
vsWorkspace.GetProjectData(projectId,
out var hierarchy, out var envDTEProject);
var projectItems = envDTEProject.ProjectItems;
var projectItemsStack = new Stack<Tuple<ProjectItem, string>>();
// Populate the stack
projectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, "\\")));
while (projectItemsStack.Count != 0)
{
var projectItemTuple = projectItemsStack.Pop();
var projectItem = projectItemTuple.Item1;
var currentFolderPath = projectItemTuple.Item2;
var folderPath = currentFolderPath + projectItem.Name + "\\";
folders.Add(folderPath);
projectItem.ProjectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, folderPath)));
}
}
return folders;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Composition;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.ProjectManagement;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Roslyn.Utilities;
namespace Roslyn.VisualStudio.Services.Implementation.ProjectSystem
{
[ExportWorkspaceService(typeof(IProjectManagementService), ServiceLayer.Host), Shared]
internal class VisualStudioProjectManagementService : ForegroundThreadAffinitizedObject, IProjectManagementService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioProjectManagementService(IThreadingContext threadingContext)
: base(threadingContext)
{
}
public string GetDefaultNamespace(Microsoft.CodeAnalysis.Project project, Workspace workspace)
{
this.AssertIsForeground();
if (project.Language == LanguageNames.VisualBasic)
{
return "";
}
var defaultNamespace = "";
if (workspace is VisualStudioWorkspaceImpl vsWorkspace)
{
vsWorkspace.GetProjectData(project.Id,
out _, out var envDTEProject);
try
{
defaultNamespace = (string)envDTEProject.ProjectItems.ContainingProject.Properties.Item("DefaultNamespace").Value; // Do not Localize
}
catch (ArgumentException)
{
// DefaultNamespace does not exist for this project.
}
}
return defaultNamespace;
}
public IList<string> GetFolders(ProjectId projectId, Workspace workspace)
{
var folders = new List<string>();
if (workspace is VisualStudioWorkspaceImpl vsWorkspace)
{
vsWorkspace.GetProjectData(projectId,
out var hierarchy, out var envDTEProject);
var projectItems = envDTEProject.ProjectItems;
var projectItemsStack = new Stack<Tuple<ProjectItem, string>>();
// Populate the stack
projectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, "\\")));
while (projectItemsStack.Count != 0)
{
var projectItemTuple = projectItemsStack.Pop();
var projectItem = projectItemTuple.Item1;
var currentFolderPath = projectItemTuple.Item2;
var folderPath = currentFolderPath + projectItem.Name + "\\";
folders.Add(folderPath);
projectItem.ProjectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, folderPath)));
}
}
return folders;
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/CSharp/Portable/Structure/Providers/EventDeclarationStructureProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class EventDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<EventDeclarationSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
EventDeclarationSyntax eventDeclaration,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
CSharpStructureHelpers.CollectCommentBlockSpans(eventDeclaration, ref spans, optionProvider);
// fault tolerance
if (eventDeclaration.AccessorList == null ||
eventDeclaration.AccessorList.IsMissing ||
eventDeclaration.AccessorList.OpenBraceToken.IsMissing ||
eventDeclaration.AccessorList.CloseBraceToken.IsMissing)
{
return;
}
SyntaxNodeOrToken current = eventDeclaration;
var nextSibling = current.GetNextSibling();
// Check IsNode to compress blank lines after this node if it is the last child of the parent.
//
// Full events are grouped together with event field definitions in Metadata as Source.
var compressEmptyLines = optionProvider.IsMetadataAsSource
&& (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.EventDeclaration) || nextSibling.IsKind(SyntaxKind.EventFieldDeclaration));
spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan(
eventDeclaration,
eventDeclaration.Identifier,
compressEmptyLines: compressEmptyLines,
autoCollapse: true,
type: BlockTypes.Member,
isCollapsible: 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;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class EventDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<EventDeclarationSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
EventDeclarationSyntax eventDeclaration,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
CSharpStructureHelpers.CollectCommentBlockSpans(eventDeclaration, ref spans, optionProvider);
// fault tolerance
if (eventDeclaration.AccessorList == null ||
eventDeclaration.AccessorList.IsMissing ||
eventDeclaration.AccessorList.OpenBraceToken.IsMissing ||
eventDeclaration.AccessorList.CloseBraceToken.IsMissing)
{
return;
}
SyntaxNodeOrToken current = eventDeclaration;
var nextSibling = current.GetNextSibling();
// Check IsNode to compress blank lines after this node if it is the last child of the parent.
//
// Full events are grouped together with event field definitions in Metadata as Source.
var compressEmptyLines = optionProvider.IsMetadataAsSource
&& (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.EventDeclaration) || nextSibling.IsKind(SyntaxKind.EventFieldDeclaration));
spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan(
eventDeclaration,
eventDeclaration.Identifier,
compressEmptyLines: compressEmptyLines,
autoCollapse: true,
type: BlockTypes.Member,
isCollapsible: true));
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Analyzers/Core/Analyzers/MatchFolderAndNamespace/MatchFolderAndNamespaceConstants.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.Analyzers.MatchFolderAndNamespace
{
internal static class MatchFolderAndNamespaceConstants
{
public const string RootNamespaceOption = "build_property.RootNamespace";
public const string ProjectDirOption = "build_property.ProjectDir";
public const string TargetNamespace = "TargetNamespace";
}
}
| // Licensed to the .NET Foundation under one or more 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.Analyzers.MatchFolderAndNamespace
{
internal static class MatchFolderAndNamespaceConstants
{
public const string RootNamespaceOption = "build_property.RootNamespace";
public const string ProjectDirOption = "build_property.ProjectDir";
public const string TargetNamespace = "TargetNamespace";
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/VisualBasic/Portable/Lowering/StateMachineRewriter/StateMachineRewriter.StateMachineMethodToClassRewriter.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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend MustInherit Class StateMachineRewriter(Of TProxy)
Friend MustInherit Class StateMachineMethodToClassRewriter
Inherits MethodToClassRewriter(Of TProxy)
Protected Friend ReadOnly F As SyntheticBoundNodeFactory
Protected NextState As Integer = 0
''' <summary>
''' The "state" of the state machine that is the translation of the iterator method.
''' </summary>
Protected ReadOnly StateField As FieldSymbol
''' <summary>
''' Cached "state" of the state machine within the MoveNext method. We work with a copy of
''' the state to avoid shared mutable state between threads. (Two threads can be executing
''' in a Task's MoveNext method because an awaited task may complete after the awaiter has
''' tested whether the subtask is complete but before the awaiter has returned)
''' </summary>
Protected ReadOnly CachedState As LocalSymbol
''' <summary>
''' For each distinct label, the set of states that need to be dispatched to that label.
''' Note that there is a dispatch occurring at every try-finally statement, so this
''' variable takes on a new set of values inside each try block.
''' </summary>
Protected Dispatches As New Dictionary(Of LabelSymbol, List(Of Integer))
''' <summary>
''' A mapping from each state of the state machine to the new state that will be used to execute
''' finally blocks in case the state machine is disposed. The Dispose method computes the new
''' state and then runs MoveNext.
''' </summary>
Protected ReadOnly FinalizerStateMap As New Dictionary(Of Integer, Integer)()
''' <summary>
''' A try block might have no state (transitions) within it, in which case it does not need
''' to have a state to represent finalization. This flag tells us whether the current try
''' block that we are within has a finalizer state. Initially true as we have the (trivial)
''' finalizer state of -1 at the top level.
''' </summary>
Private _hasFinalizerState As Boolean = True
''' <summary>
''' If hasFinalizerState is true, this is the state for finalization from anywhere in this try block.
''' Initially set to -1, representing the no-op finalization required at the top level.
''' </summary>
Private _currentFinalizerState As Integer = -1
''' <summary>
''' The set of local variables and parameters that were hoisted and need a proxy.
''' </summary>
Private ReadOnly _hoistedVariables As IReadOnlySet(Of Symbol) = Nothing
Private ReadOnly _synthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser
Private ReadOnly _nextFreeHoistedLocalSlot As Integer
Public Sub New(F As SyntheticBoundNodeFactory,
stateField As FieldSymbol,
hoistedVariables As IReadOnlySet(Of Symbol),
initialProxies As Dictionary(Of Symbol, TProxy),
synthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser,
slotAllocatorOpt As VariableSlotAllocator,
nextFreeHoistedLocalSlot As Integer,
diagnostics As BindingDiagnosticBag)
MyBase.New(slotAllocatorOpt, F.CompilationState, diagnostics, preserveOriginalLocals:=False)
Debug.Assert(F IsNot Nothing)
Debug.Assert(stateField IsNot Nothing)
Debug.Assert(hoistedVariables IsNot Nothing)
Debug.Assert(initialProxies IsNot Nothing)
Debug.Assert(nextFreeHoistedLocalSlot >= 0)
Debug.Assert(diagnostics IsNot Nothing)
Me.F = F
Me.StateField = stateField
Me.CachedState = F.SynthesizedLocal(F.SpecialType(SpecialType.System_Int32), SynthesizedLocalKind.StateMachineCachedState, F.Syntax)
Me._hoistedVariables = hoistedVariables
Me._synthesizedLocalOrdinals = synthesizedLocalOrdinals
Me._nextFreeHoistedLocalSlot = nextFreeHoistedLocalSlot
For Each p In initialProxies
Me.Proxies.Add(p.Key, p.Value)
Next
End Sub
''' <summary>
''' Implementation-specific name for labels to mark state machine resume points.
''' </summary>
Protected MustOverride ReadOnly Property ResumeLabelName As String
''' <summary>
''' Generate return statements from the state machine method body.
''' </summary>
Protected MustOverride Function GenerateReturn(finished As Boolean) As BoundStatement
Protected Overrides ReadOnly Property TypeMap As TypeSubstitution
Get
Return Me.F.CurrentType.TypeSubstitution
End Get
End Property
Protected Overrides ReadOnly Property CurrentMethod As MethodSymbol
Get
Return Me.F.CurrentMethod
End Get
End Property
Protected Overrides ReadOnly Property TopLevelMethod As MethodSymbol
Get
Return Me.F.TopLevelMethod
End Get
End Property
Friend Overrides Function FramePointer(syntax As SyntaxNode, frameClass As NamedTypeSymbol) As BoundExpression
Dim oldSyntax As SyntaxNode = Me.F.Syntax
Me.F.Syntax = syntax
Dim result = Me.F.Me()
Debug.Assert(TypeSymbol.Equals(frameClass, result.Type, TypeCompareKind.ConsiderEverything))
Me.F.Syntax = oldSyntax
Return result
End Function
Protected Structure StateInfo
Public ReadOnly Number As Integer
Public ReadOnly ResumeLabel As GeneratedLabelSymbol
Public Sub New(stateNumber As Integer, resumeLabel As GeneratedLabelSymbol)
Me.Number = stateNumber
Me.ResumeLabel = resumeLabel
End Sub
End Structure
Protected Function AddState() As StateInfo
Dim stateNumber As Integer = Me.NextState
Me.NextState += 1
If Me.Dispatches Is Nothing Then
Me.Dispatches = New Dictionary(Of LabelSymbol, List(Of Integer))()
End If
If Not Me._hasFinalizerState Then
Me._currentFinalizerState = Me.NextState
Me.NextState += 1
Me._hasFinalizerState = True
End If
Dim resumeLabel As GeneratedLabelSymbol = Me.F.GenerateLabel(ResumeLabelName)
Me.Dispatches.Add(resumeLabel, New List(Of Integer)() From {stateNumber})
Me.FinalizerStateMap.Add(stateNumber, Me._currentFinalizerState)
Return New StateInfo(stateNumber, resumeLabel)
End Function
Protected Function Dispatch() As BoundStatement
Return Me.F.Select(
Me.F.Local(Me.CachedState, isLValue:=False),
From kv In Me.Dispatches
Order By kv.Value(0)
Select Me.F.SwitchSection(kv.Value, F.Goto(kv.Key)))
End Function
#Region "Visitors"
Public Overrides Function Visit(node As BoundNode) As BoundNode
If node Is Nothing Then
Return node
End If
Dim oldSyntax As SyntaxNode = Me.F.Syntax
Me.F.Syntax = node.Syntax
Dim result As BoundNode = MyBase.Visit(node)
Me.F.Syntax = oldSyntax
Return result
End Function
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
Return PossibleStateMachineScope(node.Locals, MyBase.VisitBlock(node))
End Function
Private Function PossibleStateMachineScope(locals As ImmutableArray(Of LocalSymbol), wrapped As BoundNode) As BoundNode
If locals.IsEmpty Then
Return wrapped
End If
Dim hoistedLocalsWithDebugScopes = ArrayBuilder(Of FieldSymbol).GetInstance()
For Each local In locals
If Not NeedsProxy(local) Then
Continue For
End If
' Ref synthesized variables have proxies that are allocated in VisitAssignmentOperator.
If local.IsByRef Then
Debug.Assert(local.SynthesizedKind = SynthesizedLocalKind.Spill)
Continue For
End If
Debug.Assert(local.SynthesizedKind.IsLongLived())
' We need to produce hoisted local scope debug information for user locals as well as
' lambda display classes, since Dev12 EE uses them to determine which variables are displayed
' in Locals window.
If local.SynthesizedKind = SynthesizedLocalKind.UserDefined OrElse local.SynthesizedKind = SynthesizedLocalKind.LambdaDisplayClass Then
Dim proxy As TProxy = Nothing
If Proxies.TryGetValue(local, proxy) Then
Me.AddProxyFieldsForStateMachineScope(proxy, hoistedLocalsWithDebugScopes)
End If
End If
Next
' Wrap the node in a StateMachineScope for debugging
Dim translatedStatement As BoundNode = wrapped
If hoistedLocalsWithDebugScopes.Count > 0 Then
translatedStatement = MakeStateMachineScope(hoistedLocalsWithDebugScopes.ToImmutable(), DirectCast(translatedStatement, BoundStatement))
End If
hoistedLocalsWithDebugScopes.Free()
Return translatedStatement
End Function
''' <remarks>
''' Must remain in sync with <see cref="TryUnwrapBoundStateMachineScope"/>.
''' </remarks>
Friend Function MakeStateMachineScope(hoistedLocals As ImmutableArray(Of FieldSymbol), statement As BoundStatement) As BoundBlock
Return Me.F.Block(New BoundStateMachineScope(Me.F.Syntax, hoistedLocals, statement).MakeCompilerGenerated)
End Function
''' <remarks>
''' Must remain in sync with <see cref="MakeStateMachineScope"/>.
''' </remarks>
Friend Function TryUnwrapBoundStateMachineScope(ByRef statement As BoundStatement, <Out> ByRef hoistedLocals As ImmutableArray(Of FieldSymbol)) As Boolean
If statement.Kind = BoundKind.Block Then
Dim rewrittenBlock = DirectCast(statement, BoundBlock)
Dim rewrittenStatements = rewrittenBlock.Statements
If rewrittenStatements.Length = 1 AndAlso rewrittenStatements(0).Kind = BoundKind.StateMachineScope Then
Dim stateMachineScope = DirectCast(rewrittenStatements(0), BoundStateMachineScope)
statement = stateMachineScope.Statement
hoistedLocals = stateMachineScope.Fields
Return True
End If
End If
hoistedLocals = ImmutableArray(Of FieldSymbol).Empty
Return False
End Function
Private Function NeedsProxy(localOrParameter As Symbol) As Boolean
Debug.Assert(localOrParameter.Kind = SymbolKind.Local OrElse localOrParameter.Kind = SymbolKind.Parameter)
Return _hoistedVariables.Contains(localOrParameter)
End Function
Friend MustOverride Sub AddProxyFieldsForStateMachineScope(proxy As TProxy, proxyFields As ArrayBuilder(Of FieldSymbol))
''' <summary>
''' The try statement is the most complex part of the state machine transformation.
''' Since the CLR will not allow a 'goto' into the scope of a try statement, we must
''' generate the dispatch to the state's label stepwise. That is done by translating
''' the try statements from the inside to the outside. Within a try statement, we
''' start with an empty dispatch table (representing the mapping from state numbers
''' to labels). During translation of the try statement's body, the dispatch table
''' will be filled in with the data necessary to dispatch once we're inside the try
''' block. We generate that at the head of the translated try statement. Then, we
''' copy all of the states from that table into the table for the enclosing construct,
''' but associate them with a label just before the translated try block. That way
''' the enclosing construct will generate the code necessary to get control into the
''' try block for all of those states.
''' </summary>
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Dim oldDispatches As Dictionary(Of LabelSymbol, List(Of Integer)) = Me.Dispatches
Dim oldFinalizerState As Integer = Me._currentFinalizerState
Dim oldHasFinalizerState As Boolean = Me._hasFinalizerState
Me.Dispatches = Nothing
Me._currentFinalizerState = -1
Me._hasFinalizerState = False
Dim tryBlock As BoundBlock = Me.F.Block(DirectCast(Me.Visit(node.TryBlock), BoundStatement))
Dim dispatchLabel As GeneratedLabelSymbol = Nothing
If Me.Dispatches IsNot Nothing Then
dispatchLabel = Me.F.GenerateLabel("tryDispatch")
If Me._hasFinalizerState Then
' cause the current finalizer state to arrive here and then "return false"
Dim finalizer As GeneratedLabelSymbol = Me.F.GenerateLabel("finalizer")
Me.Dispatches.Add(finalizer, New List(Of Integer)() From {Me._currentFinalizerState})
Dim skipFinalizer As GeneratedLabelSymbol = Me.F.GenerateLabel("skipFinalizer")
tryBlock = Me.F.Block(SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.Dispatch(),
Me.F.Goto(skipFinalizer),
Me.F.Label(finalizer),
Me.F.Assignment(
F.Field(F.Me(), Me.StateField, True),
F.AssignmentExpression(F.Local(Me.CachedState, True), F.Literal(StateMachineStates.NotStartedStateMachine))),
Me.GenerateReturn(False),
Me.F.Label(skipFinalizer),
tryBlock)
Else
tryBlock = Me.F.Block(SyntheticBoundNodeFactory.HiddenSequencePoint(), Me.Dispatch(), tryBlock)
End If
If oldDispatches Is Nothing Then
oldDispatches = New Dictionary(Of LabelSymbol, List(Of Integer))()
End If
oldDispatches.Add(dispatchLabel, New List(Of Integer)(From kv In Dispatches.Values From n In kv Order By n Select n))
End If
Me._hasFinalizerState = oldHasFinalizerState
Me._currentFinalizerState = oldFinalizerState
Me.Dispatches = oldDispatches
Dim catchBlocks As ImmutableArray(Of BoundCatchBlock) = Me.VisitList(node.CatchBlocks)
Dim finallyBlockOpt As BoundBlock = If(node.FinallyBlockOpt Is Nothing, Nothing,
Me.F.Block(
SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.F.If(
condition:=Me.F.IntLessThan(
Me.F.Local(Me.CachedState, False),
Me.F.Literal(StateMachineStates.FirstUnusedState)),
thenClause:=DirectCast(Me.Visit(node.FinallyBlockOpt), BoundBlock)),
SyntheticBoundNodeFactory.HiddenSequencePoint()))
Dim result As BoundStatement = node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.ExitLabelOpt)
If dispatchLabel IsNot Nothing Then
result = Me.F.Block(SyntheticBoundNodeFactory.HiddenSequencePoint(), Me.F.Label(dispatchLabel), result)
End If
Return result
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Return Me.MaterializeProxy(node, Me.Proxies(Me.TopLevelMethod.MeParameter))
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Return Me.MaterializeProxy(node, Me.Proxies(Me.TopLevelMethod.MeParameter))
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Return Me.MaterializeProxy(node, Me.Proxies(Me.TopLevelMethod.MeParameter))
End Function
Private Function TryRewriteLocal(local As LocalSymbol) As LocalSymbol
If NeedsProxy(local) Then
' no longer a local symbol
Return Nothing
End If
Dim newLocal As LocalSymbol = Nothing
If Not LocalMap.TryGetValue(local, newLocal) Then
Dim newType = VisitType(local.Type)
If TypeSymbol.Equals(newType, local.Type, TypeCompareKind.ConsiderEverything) Then
' keeping same local
newLocal = local
Else
' need a local of a different type
newLocal = LocalSymbol.Create(local, newType)
LocalMap.Add(local, newLocal)
End If
End If
Return newLocal
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
' Yield/Await aren't supported in Catch block, but we need to
' rewrite the type of the variable owned by the catch block.
' Note that this variable might be a closure frame reference.
Dim rewrittenCatchLocal As LocalSymbol = Nothing
Dim origLocal As LocalSymbol = node.LocalOpt
If origLocal IsNot Nothing Then
rewrittenCatchLocal = TryRewriteLocal(origLocal)
End If
Dim rewrittenExceptionVariable As BoundExpression = DirectCast(Me.Visit(node.ExceptionSourceOpt), BoundExpression)
' rewrite filter and body
' NOTE: this will proxy all accesses to exception local if that got hoisted.
Dim rewrittenErrorLineNumber = DirectCast(Me.Visit(node.ErrorLineNumberOpt), BoundExpression)
Dim rewrittenFilter = DirectCast(Me.Visit(node.ExceptionFilterOpt), BoundExpression)
Dim rewrittenBody = DirectCast(Me.Visit(node.Body), BoundBlock)
' rebuild the node.
Return node.Update(rewrittenCatchLocal,
rewrittenExceptionVariable,
rewrittenErrorLineNumber,
rewrittenFilter,
rewrittenBody,
isSynthesizedAsyncCatchAll:=node.IsSynthesizedAsyncCatchAll)
End Function
#End Region
#Region "Nodes not existing by the time State Machine rewriter is involved"
Public NotOverridable Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitBadVariable(node As BoundBadVariable) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAttribute(node As BoundAttribute) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlName(node As BoundXmlName) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlDeclaration(node As BoundXmlDeclaration) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlComment(node As BoundXmlComment) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlElement(node As BoundXmlElement) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlCData(node As BoundXmlCData) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitNewT(node As BoundNewT) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitDup(node As BoundDup) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitOmittedArgument(node As BoundOmittedArgument) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitTypeArguments(node As BoundTypeArguments) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
#End Region
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.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend MustInherit Class StateMachineRewriter(Of TProxy)
Friend MustInherit Class StateMachineMethodToClassRewriter
Inherits MethodToClassRewriter(Of TProxy)
Protected Friend ReadOnly F As SyntheticBoundNodeFactory
Protected NextState As Integer = 0
''' <summary>
''' The "state" of the state machine that is the translation of the iterator method.
''' </summary>
Protected ReadOnly StateField As FieldSymbol
''' <summary>
''' Cached "state" of the state machine within the MoveNext method. We work with a copy of
''' the state to avoid shared mutable state between threads. (Two threads can be executing
''' in a Task's MoveNext method because an awaited task may complete after the awaiter has
''' tested whether the subtask is complete but before the awaiter has returned)
''' </summary>
Protected ReadOnly CachedState As LocalSymbol
''' <summary>
''' For each distinct label, the set of states that need to be dispatched to that label.
''' Note that there is a dispatch occurring at every try-finally statement, so this
''' variable takes on a new set of values inside each try block.
''' </summary>
Protected Dispatches As New Dictionary(Of LabelSymbol, List(Of Integer))
''' <summary>
''' A mapping from each state of the state machine to the new state that will be used to execute
''' finally blocks in case the state machine is disposed. The Dispose method computes the new
''' state and then runs MoveNext.
''' </summary>
Protected ReadOnly FinalizerStateMap As New Dictionary(Of Integer, Integer)()
''' <summary>
''' A try block might have no state (transitions) within it, in which case it does not need
''' to have a state to represent finalization. This flag tells us whether the current try
''' block that we are within has a finalizer state. Initially true as we have the (trivial)
''' finalizer state of -1 at the top level.
''' </summary>
Private _hasFinalizerState As Boolean = True
''' <summary>
''' If hasFinalizerState is true, this is the state for finalization from anywhere in this try block.
''' Initially set to -1, representing the no-op finalization required at the top level.
''' </summary>
Private _currentFinalizerState As Integer = -1
''' <summary>
''' The set of local variables and parameters that were hoisted and need a proxy.
''' </summary>
Private ReadOnly _hoistedVariables As IReadOnlySet(Of Symbol) = Nothing
Private ReadOnly _synthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser
Private ReadOnly _nextFreeHoistedLocalSlot As Integer
Public Sub New(F As SyntheticBoundNodeFactory,
stateField As FieldSymbol,
hoistedVariables As IReadOnlySet(Of Symbol),
initialProxies As Dictionary(Of Symbol, TProxy),
synthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser,
slotAllocatorOpt As VariableSlotAllocator,
nextFreeHoistedLocalSlot As Integer,
diagnostics As BindingDiagnosticBag)
MyBase.New(slotAllocatorOpt, F.CompilationState, diagnostics, preserveOriginalLocals:=False)
Debug.Assert(F IsNot Nothing)
Debug.Assert(stateField IsNot Nothing)
Debug.Assert(hoistedVariables IsNot Nothing)
Debug.Assert(initialProxies IsNot Nothing)
Debug.Assert(nextFreeHoistedLocalSlot >= 0)
Debug.Assert(diagnostics IsNot Nothing)
Me.F = F
Me.StateField = stateField
Me.CachedState = F.SynthesizedLocal(F.SpecialType(SpecialType.System_Int32), SynthesizedLocalKind.StateMachineCachedState, F.Syntax)
Me._hoistedVariables = hoistedVariables
Me._synthesizedLocalOrdinals = synthesizedLocalOrdinals
Me._nextFreeHoistedLocalSlot = nextFreeHoistedLocalSlot
For Each p In initialProxies
Me.Proxies.Add(p.Key, p.Value)
Next
End Sub
''' <summary>
''' Implementation-specific name for labels to mark state machine resume points.
''' </summary>
Protected MustOverride ReadOnly Property ResumeLabelName As String
''' <summary>
''' Generate return statements from the state machine method body.
''' </summary>
Protected MustOverride Function GenerateReturn(finished As Boolean) As BoundStatement
Protected Overrides ReadOnly Property TypeMap As TypeSubstitution
Get
Return Me.F.CurrentType.TypeSubstitution
End Get
End Property
Protected Overrides ReadOnly Property CurrentMethod As MethodSymbol
Get
Return Me.F.CurrentMethod
End Get
End Property
Protected Overrides ReadOnly Property TopLevelMethod As MethodSymbol
Get
Return Me.F.TopLevelMethod
End Get
End Property
Friend Overrides Function FramePointer(syntax As SyntaxNode, frameClass As NamedTypeSymbol) As BoundExpression
Dim oldSyntax As SyntaxNode = Me.F.Syntax
Me.F.Syntax = syntax
Dim result = Me.F.Me()
Debug.Assert(TypeSymbol.Equals(frameClass, result.Type, TypeCompareKind.ConsiderEverything))
Me.F.Syntax = oldSyntax
Return result
End Function
Protected Structure StateInfo
Public ReadOnly Number As Integer
Public ReadOnly ResumeLabel As GeneratedLabelSymbol
Public Sub New(stateNumber As Integer, resumeLabel As GeneratedLabelSymbol)
Me.Number = stateNumber
Me.ResumeLabel = resumeLabel
End Sub
End Structure
Protected Function AddState() As StateInfo
Dim stateNumber As Integer = Me.NextState
Me.NextState += 1
If Me.Dispatches Is Nothing Then
Me.Dispatches = New Dictionary(Of LabelSymbol, List(Of Integer))()
End If
If Not Me._hasFinalizerState Then
Me._currentFinalizerState = Me.NextState
Me.NextState += 1
Me._hasFinalizerState = True
End If
Dim resumeLabel As GeneratedLabelSymbol = Me.F.GenerateLabel(ResumeLabelName)
Me.Dispatches.Add(resumeLabel, New List(Of Integer)() From {stateNumber})
Me.FinalizerStateMap.Add(stateNumber, Me._currentFinalizerState)
Return New StateInfo(stateNumber, resumeLabel)
End Function
Protected Function Dispatch() As BoundStatement
Return Me.F.Select(
Me.F.Local(Me.CachedState, isLValue:=False),
From kv In Me.Dispatches
Order By kv.Value(0)
Select Me.F.SwitchSection(kv.Value, F.Goto(kv.Key)))
End Function
#Region "Visitors"
Public Overrides Function Visit(node As BoundNode) As BoundNode
If node Is Nothing Then
Return node
End If
Dim oldSyntax As SyntaxNode = Me.F.Syntax
Me.F.Syntax = node.Syntax
Dim result As BoundNode = MyBase.Visit(node)
Me.F.Syntax = oldSyntax
Return result
End Function
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
Return PossibleStateMachineScope(node.Locals, MyBase.VisitBlock(node))
End Function
Private Function PossibleStateMachineScope(locals As ImmutableArray(Of LocalSymbol), wrapped As BoundNode) As BoundNode
If locals.IsEmpty Then
Return wrapped
End If
Dim hoistedLocalsWithDebugScopes = ArrayBuilder(Of FieldSymbol).GetInstance()
For Each local In locals
If Not NeedsProxy(local) Then
Continue For
End If
' Ref synthesized variables have proxies that are allocated in VisitAssignmentOperator.
If local.IsByRef Then
Debug.Assert(local.SynthesizedKind = SynthesizedLocalKind.Spill)
Continue For
End If
Debug.Assert(local.SynthesizedKind.IsLongLived())
' We need to produce hoisted local scope debug information for user locals as well as
' lambda display classes, since Dev12 EE uses them to determine which variables are displayed
' in Locals window.
If local.SynthesizedKind = SynthesizedLocalKind.UserDefined OrElse local.SynthesizedKind = SynthesizedLocalKind.LambdaDisplayClass Then
Dim proxy As TProxy = Nothing
If Proxies.TryGetValue(local, proxy) Then
Me.AddProxyFieldsForStateMachineScope(proxy, hoistedLocalsWithDebugScopes)
End If
End If
Next
' Wrap the node in a StateMachineScope for debugging
Dim translatedStatement As BoundNode = wrapped
If hoistedLocalsWithDebugScopes.Count > 0 Then
translatedStatement = MakeStateMachineScope(hoistedLocalsWithDebugScopes.ToImmutable(), DirectCast(translatedStatement, BoundStatement))
End If
hoistedLocalsWithDebugScopes.Free()
Return translatedStatement
End Function
''' <remarks>
''' Must remain in sync with <see cref="TryUnwrapBoundStateMachineScope"/>.
''' </remarks>
Friend Function MakeStateMachineScope(hoistedLocals As ImmutableArray(Of FieldSymbol), statement As BoundStatement) As BoundBlock
Return Me.F.Block(New BoundStateMachineScope(Me.F.Syntax, hoistedLocals, statement).MakeCompilerGenerated)
End Function
''' <remarks>
''' Must remain in sync with <see cref="MakeStateMachineScope"/>.
''' </remarks>
Friend Function TryUnwrapBoundStateMachineScope(ByRef statement As BoundStatement, <Out> ByRef hoistedLocals As ImmutableArray(Of FieldSymbol)) As Boolean
If statement.Kind = BoundKind.Block Then
Dim rewrittenBlock = DirectCast(statement, BoundBlock)
Dim rewrittenStatements = rewrittenBlock.Statements
If rewrittenStatements.Length = 1 AndAlso rewrittenStatements(0).Kind = BoundKind.StateMachineScope Then
Dim stateMachineScope = DirectCast(rewrittenStatements(0), BoundStateMachineScope)
statement = stateMachineScope.Statement
hoistedLocals = stateMachineScope.Fields
Return True
End If
End If
hoistedLocals = ImmutableArray(Of FieldSymbol).Empty
Return False
End Function
Private Function NeedsProxy(localOrParameter As Symbol) As Boolean
Debug.Assert(localOrParameter.Kind = SymbolKind.Local OrElse localOrParameter.Kind = SymbolKind.Parameter)
Return _hoistedVariables.Contains(localOrParameter)
End Function
Friend MustOverride Sub AddProxyFieldsForStateMachineScope(proxy As TProxy, proxyFields As ArrayBuilder(Of FieldSymbol))
''' <summary>
''' The try statement is the most complex part of the state machine transformation.
''' Since the CLR will not allow a 'goto' into the scope of a try statement, we must
''' generate the dispatch to the state's label stepwise. That is done by translating
''' the try statements from the inside to the outside. Within a try statement, we
''' start with an empty dispatch table (representing the mapping from state numbers
''' to labels). During translation of the try statement's body, the dispatch table
''' will be filled in with the data necessary to dispatch once we're inside the try
''' block. We generate that at the head of the translated try statement. Then, we
''' copy all of the states from that table into the table for the enclosing construct,
''' but associate them with a label just before the translated try block. That way
''' the enclosing construct will generate the code necessary to get control into the
''' try block for all of those states.
''' </summary>
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Dim oldDispatches As Dictionary(Of LabelSymbol, List(Of Integer)) = Me.Dispatches
Dim oldFinalizerState As Integer = Me._currentFinalizerState
Dim oldHasFinalizerState As Boolean = Me._hasFinalizerState
Me.Dispatches = Nothing
Me._currentFinalizerState = -1
Me._hasFinalizerState = False
Dim tryBlock As BoundBlock = Me.F.Block(DirectCast(Me.Visit(node.TryBlock), BoundStatement))
Dim dispatchLabel As GeneratedLabelSymbol = Nothing
If Me.Dispatches IsNot Nothing Then
dispatchLabel = Me.F.GenerateLabel("tryDispatch")
If Me._hasFinalizerState Then
' cause the current finalizer state to arrive here and then "return false"
Dim finalizer As GeneratedLabelSymbol = Me.F.GenerateLabel("finalizer")
Me.Dispatches.Add(finalizer, New List(Of Integer)() From {Me._currentFinalizerState})
Dim skipFinalizer As GeneratedLabelSymbol = Me.F.GenerateLabel("skipFinalizer")
tryBlock = Me.F.Block(SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.Dispatch(),
Me.F.Goto(skipFinalizer),
Me.F.Label(finalizer),
Me.F.Assignment(
F.Field(F.Me(), Me.StateField, True),
F.AssignmentExpression(F.Local(Me.CachedState, True), F.Literal(StateMachineStates.NotStartedStateMachine))),
Me.GenerateReturn(False),
Me.F.Label(skipFinalizer),
tryBlock)
Else
tryBlock = Me.F.Block(SyntheticBoundNodeFactory.HiddenSequencePoint(), Me.Dispatch(), tryBlock)
End If
If oldDispatches Is Nothing Then
oldDispatches = New Dictionary(Of LabelSymbol, List(Of Integer))()
End If
oldDispatches.Add(dispatchLabel, New List(Of Integer)(From kv In Dispatches.Values From n In kv Order By n Select n))
End If
Me._hasFinalizerState = oldHasFinalizerState
Me._currentFinalizerState = oldFinalizerState
Me.Dispatches = oldDispatches
Dim catchBlocks As ImmutableArray(Of BoundCatchBlock) = Me.VisitList(node.CatchBlocks)
Dim finallyBlockOpt As BoundBlock = If(node.FinallyBlockOpt Is Nothing, Nothing,
Me.F.Block(
SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.F.If(
condition:=Me.F.IntLessThan(
Me.F.Local(Me.CachedState, False),
Me.F.Literal(StateMachineStates.FirstUnusedState)),
thenClause:=DirectCast(Me.Visit(node.FinallyBlockOpt), BoundBlock)),
SyntheticBoundNodeFactory.HiddenSequencePoint()))
Dim result As BoundStatement = node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.ExitLabelOpt)
If dispatchLabel IsNot Nothing Then
result = Me.F.Block(SyntheticBoundNodeFactory.HiddenSequencePoint(), Me.F.Label(dispatchLabel), result)
End If
Return result
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Return Me.MaterializeProxy(node, Me.Proxies(Me.TopLevelMethod.MeParameter))
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Return Me.MaterializeProxy(node, Me.Proxies(Me.TopLevelMethod.MeParameter))
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Return Me.MaterializeProxy(node, Me.Proxies(Me.TopLevelMethod.MeParameter))
End Function
Private Function TryRewriteLocal(local As LocalSymbol) As LocalSymbol
If NeedsProxy(local) Then
' no longer a local symbol
Return Nothing
End If
Dim newLocal As LocalSymbol = Nothing
If Not LocalMap.TryGetValue(local, newLocal) Then
Dim newType = VisitType(local.Type)
If TypeSymbol.Equals(newType, local.Type, TypeCompareKind.ConsiderEverything) Then
' keeping same local
newLocal = local
Else
' need a local of a different type
newLocal = LocalSymbol.Create(local, newType)
LocalMap.Add(local, newLocal)
End If
End If
Return newLocal
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
' Yield/Await aren't supported in Catch block, but we need to
' rewrite the type of the variable owned by the catch block.
' Note that this variable might be a closure frame reference.
Dim rewrittenCatchLocal As LocalSymbol = Nothing
Dim origLocal As LocalSymbol = node.LocalOpt
If origLocal IsNot Nothing Then
rewrittenCatchLocal = TryRewriteLocal(origLocal)
End If
Dim rewrittenExceptionVariable As BoundExpression = DirectCast(Me.Visit(node.ExceptionSourceOpt), BoundExpression)
' rewrite filter and body
' NOTE: this will proxy all accesses to exception local if that got hoisted.
Dim rewrittenErrorLineNumber = DirectCast(Me.Visit(node.ErrorLineNumberOpt), BoundExpression)
Dim rewrittenFilter = DirectCast(Me.Visit(node.ExceptionFilterOpt), BoundExpression)
Dim rewrittenBody = DirectCast(Me.Visit(node.Body), BoundBlock)
' rebuild the node.
Return node.Update(rewrittenCatchLocal,
rewrittenExceptionVariable,
rewrittenErrorLineNumber,
rewrittenFilter,
rewrittenBody,
isSynthesizedAsyncCatchAll:=node.IsSynthesizedAsyncCatchAll)
End Function
#End Region
#Region "Nodes not existing by the time State Machine rewriter is involved"
Public NotOverridable Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitBadVariable(node As BoundBadVariable) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAttribute(node As BoundAttribute) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlName(node As BoundXmlName) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlDeclaration(node As BoundXmlDeclaration) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlComment(node As BoundXmlComment) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlElement(node As BoundXmlElement) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlCData(node As BoundXmlCData) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitNewT(node As BoundNewT) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitDup(node As BoundDup) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitOmittedArgument(node As BoundOmittedArgument) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitTypeArguments(node As BoundTypeArguments) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
Public NotOverridable Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Throw ExceptionUtilities.Unreachable
End Function
#End Region
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceFieldSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal abstract class SourceFieldSymbol : FieldSymbolWithAttributesAndModifiers
{
protected readonly SourceMemberContainerTypeSymbol containingType;
protected SourceFieldSymbol(SourceMemberContainerTypeSymbol containingType)
{
Debug.Assert((object)containingType != null);
this.containingType = containingType;
}
public abstract override string Name { get; }
protected override IAttributeTargetSymbol AttributeOwner
{
get { return this; }
}
internal sealed override bool RequiresCompletion
{
get { return true; }
}
internal bool IsNew
{
get
{
return (Modifiers & DeclarationModifiers.New) != 0;
}
}
protected void CheckAccessibility(BindingDiagnosticBag diagnostics)
{
var info = ModifierUtils.CheckAccessibility(Modifiers, this, isExplicitInterfaceImplementation: false);
if (info != null)
{
diagnostics.Add(new CSDiagnostic(info, this.ErrorLocation));
}
}
protected void ReportModifiersDiagnostics(BindingDiagnosticBag diagnostics)
{
if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected())
{
diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(containingType), ErrorLocation, this);
}
else if (IsVolatile && IsReadOnly)
{
diagnostics.Add(ErrorCode.ERR_VolatileAndReadonly, ErrorLocation, this);
}
else if (containingType.IsStatic && !IsStatic)
{
diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, ErrorLocation, this);
}
else if (!IsStatic && !IsReadOnly && containingType.IsReadOnly)
{
diagnostics.Add(ErrorCode.ERR_FieldsInRoStruct, ErrorLocation);
}
// TODO: Consider checking presence of core type System.Runtime.CompilerServices.IsVolatile
// if there is a volatile modifier. Perhaps an appropriate error should be reported if the
// type isn't available.
}
protected ImmutableArray<CustomModifier> RequiredCustomModifiers
{
get
{
if (!IsVolatile)
{
return ImmutableArray<CustomModifier>.Empty;
}
else
{
return ImmutableArray.Create<CustomModifier>(
CSharpCustomModifier.CreateRequired(this.ContainingAssembly.GetSpecialType(SpecialType.System_Runtime_CompilerServices_IsVolatile)));
}
}
}
public sealed override Symbol ContainingSymbol
{
get
{
return containingType;
}
}
public override NamedTypeSymbol ContainingType
{
get
{
return this.containingType;
}
}
internal sealed override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
{
Debug.Assert((object)arguments.AttributeSyntaxOpt != null);
Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag);
var attribute = arguments.Attribute;
Debug.Assert(!attribute.HasErrors);
Debug.Assert(arguments.SymbolPart == AttributeLocation.None);
if (attribute.IsTargetAttribute(this, AttributeDescription.FixedBufferAttribute))
{
// error CS1716: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead.
((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_DoNotUseFixedBufferAttr, arguments.AttributeSyntaxOpt.Name.Location);
}
else
{
base.DecodeWellKnownAttribute(ref arguments);
}
}
internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics)
{
var compilation = DeclaringCompilation;
var location = ErrorLocation;
if (Type.ContainsNativeInteger())
{
compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true);
}
if (compilation.ShouldEmitNullableAttributes(this) &&
TypeWithAnnotations.NeedsNullableAttribute())
{
compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true);
}
}
internal sealed override bool HasRuntimeSpecialName
{
get
{
return this.Name == WellKnownMemberNames.EnumBackingFieldName;
}
}
}
internal abstract class SourceFieldSymbolWithSyntaxReference : SourceFieldSymbol
{
private readonly string _name;
private readonly Location _location;
private readonly SyntaxReference _syntaxReference;
private string _lazyDocComment;
private string _lazyExpandedDocComment;
private ConstantValue _lazyConstantEarlyDecodingValue = Microsoft.CodeAnalysis.ConstantValue.Unset;
private ConstantValue _lazyConstantValue = Microsoft.CodeAnalysis.ConstantValue.Unset;
protected SourceFieldSymbolWithSyntaxReference(SourceMemberContainerTypeSymbol containingType, string name, SyntaxReference syntax, Location location)
: base(containingType)
{
Debug.Assert(name != null);
Debug.Assert(syntax != null);
Debug.Assert(location != null);
_name = name;
_syntaxReference = syntax;
_location = location;
}
public SyntaxTree SyntaxTree
{
get
{
return _syntaxReference.SyntaxTree;
}
}
public CSharpSyntaxNode SyntaxNode
{
get
{
return (CSharpSyntaxNode)_syntaxReference.GetSyntax();
}
}
public sealed override string Name
{
get
{
return _name;
}
}
internal override LexicalSortKey GetLexicalSortKey()
{
return new LexicalSortKey(_location, this.DeclaringCompilation);
}
public sealed override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray.Create(_location);
}
}
internal sealed override Location ErrorLocation
{
get
{
return _location;
}
}
public sealed override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray.Create<SyntaxReference>(_syntaxReference);
}
}
public sealed override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken))
{
ref var lazyDocComment = ref expandIncludes ? ref _lazyExpandedDocComment : ref _lazyDocComment;
return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref lazyDocComment);
}
internal sealed override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes)
{
var value = this.GetLazyConstantValue(earlyDecodingWellKnownAttributes);
if (value != Microsoft.CodeAnalysis.ConstantValue.Unset)
{
return value;
}
if (!inProgress.IsEmpty)
{
// Add this field as a dependency of the original field, and
// return Unset. The outer GetConstantValue caller will call
// this method again after evaluating any dependencies.
inProgress.AddDependency(this);
return Microsoft.CodeAnalysis.ConstantValue.Unset;
}
// Order dependencies.
var order = ArrayBuilder<ConstantEvaluationHelpers.FieldInfo>.GetInstance();
this.OrderAllDependencies(order, earlyDecodingWellKnownAttributes);
// Evaluate fields in order.
foreach (var info in order)
{
// Bind the field value regardless of whether the field represents
// the start of a cycle. In the cycle case, there will be unevaluated
// dependencies and the result will be ConstantValue.Bad plus cycle error.
var field = info.Field;
field.BindConstantValueIfNecessary(earlyDecodingWellKnownAttributes, startsCycle: info.StartsCycle);
}
order.Free();
// Return the value of this field.
return this.GetLazyConstantValue(earlyDecodingWellKnownAttributes);
}
/// <summary>
/// Return the constant value dependencies. Compute the dependencies
/// if necessary by evaluating the constant value but only persist the
/// constant value if there were no dependencies. (If there are dependencies,
/// the constant value will be re-evaluated after evaluating dependencies.)
/// </summary>
internal ImmutableHashSet<SourceFieldSymbolWithSyntaxReference> GetConstantValueDependencies(bool earlyDecodingWellKnownAttributes)
{
var value = this.GetLazyConstantValue(earlyDecodingWellKnownAttributes);
if (value != Microsoft.CodeAnalysis.ConstantValue.Unset)
{
// Constant value already determined. No need to
// compute dependencies since the constant values
// of all dependencies should be evaluated as well.
return ImmutableHashSet<SourceFieldSymbolWithSyntaxReference>.Empty;
}
ImmutableHashSet<SourceFieldSymbolWithSyntaxReference> dependencies;
var builder = PooledHashSet<SourceFieldSymbolWithSyntaxReference>.GetInstance();
var diagnostics = BindingDiagnosticBag.GetInstance();
value = MakeConstantValue(builder, earlyDecodingWellKnownAttributes, diagnostics);
// Only persist if there are no dependencies and the calculation
// completed successfully. (We could probably persist in other
// scenarios but it's probably not worth the added complexity.)
if ((builder.Count == 0) &&
(value != null) &&
!value.IsBad &&
(value != Microsoft.CodeAnalysis.ConstantValue.Unset) &&
!diagnostics.HasAnyResolvedErrors())
{
this.SetLazyConstantValue(
value,
earlyDecodingWellKnownAttributes,
diagnostics,
startsCycle: false);
dependencies = ImmutableHashSet<SourceFieldSymbolWithSyntaxReference>.Empty;
}
else
{
dependencies = ImmutableHashSet<SourceFieldSymbolWithSyntaxReference>.Empty.Union(builder);
}
diagnostics.Free();
builder.Free();
return dependencies;
}
private void BindConstantValueIfNecessary(bool earlyDecodingWellKnownAttributes, bool startsCycle)
{
if (this.GetLazyConstantValue(earlyDecodingWellKnownAttributes) != Microsoft.CodeAnalysis.ConstantValue.Unset)
{
return;
}
var builder = PooledHashSet<SourceFieldSymbolWithSyntaxReference>.GetInstance();
var diagnostics = BindingDiagnosticBag.GetInstance();
if (startsCycle)
{
diagnostics.Add(ErrorCode.ERR_CircConstValue, _location, this);
}
var value = MakeConstantValue(builder, earlyDecodingWellKnownAttributes, diagnostics);
this.SetLazyConstantValue(
value,
earlyDecodingWellKnownAttributes,
diagnostics,
startsCycle);
diagnostics.Free();
builder.Free();
}
private ConstantValue GetLazyConstantValue(bool earlyDecodingWellKnownAttributes)
{
return earlyDecodingWellKnownAttributes ? _lazyConstantEarlyDecodingValue : _lazyConstantValue;
}
private void SetLazyConstantValue(
ConstantValue value,
bool earlyDecodingWellKnownAttributes,
BindingDiagnosticBag diagnostics,
bool startsCycle)
{
Debug.Assert(value != Microsoft.CodeAnalysis.ConstantValue.Unset);
Debug.Assert((GetLazyConstantValue(earlyDecodingWellKnownAttributes) == Microsoft.CodeAnalysis.ConstantValue.Unset) ||
(GetLazyConstantValue(earlyDecodingWellKnownAttributes) == value));
if (earlyDecodingWellKnownAttributes)
{
Interlocked.CompareExchange(ref _lazyConstantEarlyDecodingValue, value, Microsoft.CodeAnalysis.ConstantValue.Unset);
}
else
{
if (Interlocked.CompareExchange(ref _lazyConstantValue, value, Microsoft.CodeAnalysis.ConstantValue.Unset) == Microsoft.CodeAnalysis.ConstantValue.Unset)
{
#if REPORT_ALL
Console.WriteLine("Thread {0}, Field {1}, StartsCycle {2}", Thread.CurrentThread.ManagedThreadId, this, startsCycle);
#endif
this.AddDeclarationDiagnostics(diagnostics);
// CompletionPart.ConstantValue is the last part for a field
DeclaringCompilation.SymbolDeclaredEvent(this);
var wasSetThisThread = this.state.NotePartComplete(CompletionPart.ConstantValue);
Debug.Assert(wasSetThisThread);
}
}
}
protected abstract ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal abstract class SourceFieldSymbol : FieldSymbolWithAttributesAndModifiers
{
protected readonly SourceMemberContainerTypeSymbol containingType;
protected SourceFieldSymbol(SourceMemberContainerTypeSymbol containingType)
{
Debug.Assert((object)containingType != null);
this.containingType = containingType;
}
public abstract override string Name { get; }
protected override IAttributeTargetSymbol AttributeOwner
{
get { return this; }
}
internal sealed override bool RequiresCompletion
{
get { return true; }
}
internal bool IsNew
{
get
{
return (Modifiers & DeclarationModifiers.New) != 0;
}
}
protected void CheckAccessibility(BindingDiagnosticBag diagnostics)
{
var info = ModifierUtils.CheckAccessibility(Modifiers, this, isExplicitInterfaceImplementation: false);
if (info != null)
{
diagnostics.Add(new CSDiagnostic(info, this.ErrorLocation));
}
}
protected void ReportModifiersDiagnostics(BindingDiagnosticBag diagnostics)
{
if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected())
{
diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(containingType), ErrorLocation, this);
}
else if (IsVolatile && IsReadOnly)
{
diagnostics.Add(ErrorCode.ERR_VolatileAndReadonly, ErrorLocation, this);
}
else if (containingType.IsStatic && !IsStatic)
{
diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, ErrorLocation, this);
}
else if (!IsStatic && !IsReadOnly && containingType.IsReadOnly)
{
diagnostics.Add(ErrorCode.ERR_FieldsInRoStruct, ErrorLocation);
}
// TODO: Consider checking presence of core type System.Runtime.CompilerServices.IsVolatile
// if there is a volatile modifier. Perhaps an appropriate error should be reported if the
// type isn't available.
}
protected ImmutableArray<CustomModifier> RequiredCustomModifiers
{
get
{
if (!IsVolatile)
{
return ImmutableArray<CustomModifier>.Empty;
}
else
{
return ImmutableArray.Create<CustomModifier>(
CSharpCustomModifier.CreateRequired(this.ContainingAssembly.GetSpecialType(SpecialType.System_Runtime_CompilerServices_IsVolatile)));
}
}
}
public sealed override Symbol ContainingSymbol
{
get
{
return containingType;
}
}
public override NamedTypeSymbol ContainingType
{
get
{
return this.containingType;
}
}
internal sealed override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
{
Debug.Assert((object)arguments.AttributeSyntaxOpt != null);
Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag);
var attribute = arguments.Attribute;
Debug.Assert(!attribute.HasErrors);
Debug.Assert(arguments.SymbolPart == AttributeLocation.None);
if (attribute.IsTargetAttribute(this, AttributeDescription.FixedBufferAttribute))
{
// error CS1716: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead.
((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_DoNotUseFixedBufferAttr, arguments.AttributeSyntaxOpt.Name.Location);
}
else
{
base.DecodeWellKnownAttribute(ref arguments);
}
}
internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics)
{
var compilation = DeclaringCompilation;
var location = ErrorLocation;
if (Type.ContainsNativeInteger())
{
compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true);
}
if (compilation.ShouldEmitNullableAttributes(this) &&
TypeWithAnnotations.NeedsNullableAttribute())
{
compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true);
}
}
internal sealed override bool HasRuntimeSpecialName
{
get
{
return this.Name == WellKnownMemberNames.EnumBackingFieldName;
}
}
}
internal abstract class SourceFieldSymbolWithSyntaxReference : SourceFieldSymbol
{
private readonly string _name;
private readonly Location _location;
private readonly SyntaxReference _syntaxReference;
private string _lazyDocComment;
private string _lazyExpandedDocComment;
private ConstantValue _lazyConstantEarlyDecodingValue = Microsoft.CodeAnalysis.ConstantValue.Unset;
private ConstantValue _lazyConstantValue = Microsoft.CodeAnalysis.ConstantValue.Unset;
protected SourceFieldSymbolWithSyntaxReference(SourceMemberContainerTypeSymbol containingType, string name, SyntaxReference syntax, Location location)
: base(containingType)
{
Debug.Assert(name != null);
Debug.Assert(syntax != null);
Debug.Assert(location != null);
_name = name;
_syntaxReference = syntax;
_location = location;
}
public SyntaxTree SyntaxTree
{
get
{
return _syntaxReference.SyntaxTree;
}
}
public CSharpSyntaxNode SyntaxNode
{
get
{
return (CSharpSyntaxNode)_syntaxReference.GetSyntax();
}
}
public sealed override string Name
{
get
{
return _name;
}
}
internal override LexicalSortKey GetLexicalSortKey()
{
return new LexicalSortKey(_location, this.DeclaringCompilation);
}
public sealed override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray.Create(_location);
}
}
internal sealed override Location ErrorLocation
{
get
{
return _location;
}
}
public sealed override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray.Create<SyntaxReference>(_syntaxReference);
}
}
public sealed override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken))
{
ref var lazyDocComment = ref expandIncludes ? ref _lazyExpandedDocComment : ref _lazyDocComment;
return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref lazyDocComment);
}
internal sealed override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes)
{
var value = this.GetLazyConstantValue(earlyDecodingWellKnownAttributes);
if (value != Microsoft.CodeAnalysis.ConstantValue.Unset)
{
return value;
}
if (!inProgress.IsEmpty)
{
// Add this field as a dependency of the original field, and
// return Unset. The outer GetConstantValue caller will call
// this method again after evaluating any dependencies.
inProgress.AddDependency(this);
return Microsoft.CodeAnalysis.ConstantValue.Unset;
}
// Order dependencies.
var order = ArrayBuilder<ConstantEvaluationHelpers.FieldInfo>.GetInstance();
this.OrderAllDependencies(order, earlyDecodingWellKnownAttributes);
// Evaluate fields in order.
foreach (var info in order)
{
// Bind the field value regardless of whether the field represents
// the start of a cycle. In the cycle case, there will be unevaluated
// dependencies and the result will be ConstantValue.Bad plus cycle error.
var field = info.Field;
field.BindConstantValueIfNecessary(earlyDecodingWellKnownAttributes, startsCycle: info.StartsCycle);
}
order.Free();
// Return the value of this field.
return this.GetLazyConstantValue(earlyDecodingWellKnownAttributes);
}
/// <summary>
/// Return the constant value dependencies. Compute the dependencies
/// if necessary by evaluating the constant value but only persist the
/// constant value if there were no dependencies. (If there are dependencies,
/// the constant value will be re-evaluated after evaluating dependencies.)
/// </summary>
internal ImmutableHashSet<SourceFieldSymbolWithSyntaxReference> GetConstantValueDependencies(bool earlyDecodingWellKnownAttributes)
{
var value = this.GetLazyConstantValue(earlyDecodingWellKnownAttributes);
if (value != Microsoft.CodeAnalysis.ConstantValue.Unset)
{
// Constant value already determined. No need to
// compute dependencies since the constant values
// of all dependencies should be evaluated as well.
return ImmutableHashSet<SourceFieldSymbolWithSyntaxReference>.Empty;
}
ImmutableHashSet<SourceFieldSymbolWithSyntaxReference> dependencies;
var builder = PooledHashSet<SourceFieldSymbolWithSyntaxReference>.GetInstance();
var diagnostics = BindingDiagnosticBag.GetInstance();
value = MakeConstantValue(builder, earlyDecodingWellKnownAttributes, diagnostics);
// Only persist if there are no dependencies and the calculation
// completed successfully. (We could probably persist in other
// scenarios but it's probably not worth the added complexity.)
if ((builder.Count == 0) &&
(value != null) &&
!value.IsBad &&
(value != Microsoft.CodeAnalysis.ConstantValue.Unset) &&
!diagnostics.HasAnyResolvedErrors())
{
this.SetLazyConstantValue(
value,
earlyDecodingWellKnownAttributes,
diagnostics,
startsCycle: false);
dependencies = ImmutableHashSet<SourceFieldSymbolWithSyntaxReference>.Empty;
}
else
{
dependencies = ImmutableHashSet<SourceFieldSymbolWithSyntaxReference>.Empty.Union(builder);
}
diagnostics.Free();
builder.Free();
return dependencies;
}
private void BindConstantValueIfNecessary(bool earlyDecodingWellKnownAttributes, bool startsCycle)
{
if (this.GetLazyConstantValue(earlyDecodingWellKnownAttributes) != Microsoft.CodeAnalysis.ConstantValue.Unset)
{
return;
}
var builder = PooledHashSet<SourceFieldSymbolWithSyntaxReference>.GetInstance();
var diagnostics = BindingDiagnosticBag.GetInstance();
if (startsCycle)
{
diagnostics.Add(ErrorCode.ERR_CircConstValue, _location, this);
}
var value = MakeConstantValue(builder, earlyDecodingWellKnownAttributes, diagnostics);
this.SetLazyConstantValue(
value,
earlyDecodingWellKnownAttributes,
diagnostics,
startsCycle);
diagnostics.Free();
builder.Free();
}
private ConstantValue GetLazyConstantValue(bool earlyDecodingWellKnownAttributes)
{
return earlyDecodingWellKnownAttributes ? _lazyConstantEarlyDecodingValue : _lazyConstantValue;
}
private void SetLazyConstantValue(
ConstantValue value,
bool earlyDecodingWellKnownAttributes,
BindingDiagnosticBag diagnostics,
bool startsCycle)
{
Debug.Assert(value != Microsoft.CodeAnalysis.ConstantValue.Unset);
Debug.Assert((GetLazyConstantValue(earlyDecodingWellKnownAttributes) == Microsoft.CodeAnalysis.ConstantValue.Unset) ||
(GetLazyConstantValue(earlyDecodingWellKnownAttributes) == value));
if (earlyDecodingWellKnownAttributes)
{
Interlocked.CompareExchange(ref _lazyConstantEarlyDecodingValue, value, Microsoft.CodeAnalysis.ConstantValue.Unset);
}
else
{
if (Interlocked.CompareExchange(ref _lazyConstantValue, value, Microsoft.CodeAnalysis.ConstantValue.Unset) == Microsoft.CodeAnalysis.ConstantValue.Unset)
{
#if REPORT_ALL
Console.WriteLine("Thread {0}, Field {1}, StartsCycle {2}", Thread.CurrentThread.ManagedThreadId, this, startsCycle);
#endif
this.AddDeclarationDiagnostics(diagnostics);
// CompletionPart.ConstantValue is the last part for a field
DeclaringCompilation.SymbolDeclaredEvent(this);
var wasSetThisThread = this.state.NotePartComplete(CompletionPart.ConstantValue);
Debug.Assert(wasSetThisThread);
}
}
}
protected abstract ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics);
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractSyncNamespaceCodeRefactoringProvider.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.ChangeNamespace;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace
{
internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax>
: CodeRefactoringProvider
where TNamespaceDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
{
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles ||
document.IsGeneratedCode(cancellationToken))
{
return;
}
var state = await State.CreateAsync(this, document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return;
}
// No move file action if rootnamespace isn't a prefix of current declared namespace
if (state.RelativeDeclaredNamespace != null)
{
// These code actions try to move file to a new location based on declared namespace
// and the default namespace of the project. The new location is a list of folders
// determined by the relative part of the declared namespace compare to the default namespace.
//
// For example, if he default namespace is `A.B.C`, file path is
// "[project root dir]\Class1.cs" and declared namespace in the file is
// `A.B.C.D.E`, then this action will move the file to [project root dir]\D\E\Class1.cs". .
//
// We also try to use existing folders as target if possible, using the same example above,
// if folder "[project root dir]\D.E\" already exist, we will also offer to move file to
// "[project root dir]\D.E\Class1.cs".
context.RegisterRefactorings(MoveFileCodeAction.Create(state));
}
// No change namespace action if we can't construct a valid namespace from rootnamespace and folder names.
if (state.TargetNamespace != null)
{
// This code action tries to change the name of the namespace declaration to
// match the folder hierarchy of the document. The new namespace is constructed
// by concatenating the default namespace of the project and all the folders in
// the file path up to the project root.
//
// For example, if he default namespace is `A.B.C`, file path is
// "[project root dir]\D\E\F\Class1.cs" and declared namespace in the file is
// `Foo.Bar.Baz`, then this action will change the namespace declaration
// to `A.B.C.D.E.F`.
//
// Note that it also handles the case where the target namespace or declared namespace
// is global namespace, i.e. default namespace is "" and the file is located at project
// root directory, and no namespace declaration in the document, respectively.
var service = document.GetLanguageService<IChangeNamespaceService>();
var solutionChangeAction = new ChangeNamespaceCodeAction(
state.TargetNamespace.Length == 0
? FeaturesResources.Change_to_global_namespace
: string.Format(FeaturesResources.Change_namespace_to_0, state.TargetNamespace),
token => service.ChangeNamespaceAsync(document, state.Container, state.TargetNamespace, token));
context.RegisterRefactoring(solutionChangeAction, textSpan);
}
}
/// <summary>
/// Try to get the node that can be used to trigger the refactoring based on current cursor position.
/// </summary>
/// <returns>
/// (1) a node of type <typeparamref name="TNamespaceDeclarationSyntax"/> node, if cursor in the name and it's the
/// only namespace declaration in the document.
/// (2) a node of type <typeparamref name="TCompilationUnitSyntax"/> node, if the cursor is in the name of first
/// declaration in global namespace and there's no namespace declaration in this document.
/// (3) otherwise, null.
/// </returns>
protected abstract Task<SyntaxNode> TryGetApplicableInvocationNodeAsync(Document document, TextSpan span, CancellationToken cancellationToken);
protected abstract string EscapeIdentifier(string identifier);
private class ChangeNamespaceCodeAction : SolutionChangeAction
{
public ChangeNamespaceCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution)
: base(title, createChangedSolution, title)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.ChangeNamespace;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace
{
internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax>
: CodeRefactoringProvider
where TNamespaceDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
{
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles ||
document.IsGeneratedCode(cancellationToken))
{
return;
}
var state = await State.CreateAsync(this, document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return;
}
// No move file action if rootnamespace isn't a prefix of current declared namespace
if (state.RelativeDeclaredNamespace != null)
{
// These code actions try to move file to a new location based on declared namespace
// and the default namespace of the project. The new location is a list of folders
// determined by the relative part of the declared namespace compare to the default namespace.
//
// For example, if he default namespace is `A.B.C`, file path is
// "[project root dir]\Class1.cs" and declared namespace in the file is
// `A.B.C.D.E`, then this action will move the file to [project root dir]\D\E\Class1.cs". .
//
// We also try to use existing folders as target if possible, using the same example above,
// if folder "[project root dir]\D.E\" already exist, we will also offer to move file to
// "[project root dir]\D.E\Class1.cs".
context.RegisterRefactorings(MoveFileCodeAction.Create(state));
}
// No change namespace action if we can't construct a valid namespace from rootnamespace and folder names.
if (state.TargetNamespace != null)
{
// This code action tries to change the name of the namespace declaration to
// match the folder hierarchy of the document. The new namespace is constructed
// by concatenating the default namespace of the project and all the folders in
// the file path up to the project root.
//
// For example, if he default namespace is `A.B.C`, file path is
// "[project root dir]\D\E\F\Class1.cs" and declared namespace in the file is
// `Foo.Bar.Baz`, then this action will change the namespace declaration
// to `A.B.C.D.E.F`.
//
// Note that it also handles the case where the target namespace or declared namespace
// is global namespace, i.e. default namespace is "" and the file is located at project
// root directory, and no namespace declaration in the document, respectively.
var service = document.GetLanguageService<IChangeNamespaceService>();
var solutionChangeAction = new ChangeNamespaceCodeAction(
state.TargetNamespace.Length == 0
? FeaturesResources.Change_to_global_namespace
: string.Format(FeaturesResources.Change_namespace_to_0, state.TargetNamespace),
token => service.ChangeNamespaceAsync(document, state.Container, state.TargetNamespace, token));
context.RegisterRefactoring(solutionChangeAction, textSpan);
}
}
/// <summary>
/// Try to get the node that can be used to trigger the refactoring based on current cursor position.
/// </summary>
/// <returns>
/// (1) a node of type <typeparamref name="TNamespaceDeclarationSyntax"/> node, if cursor in the name and it's the
/// only namespace declaration in the document.
/// (2) a node of type <typeparamref name="TCompilationUnitSyntax"/> node, if the cursor is in the name of first
/// declaration in global namespace and there's no namespace declaration in this document.
/// (3) otherwise, null.
/// </returns>
protected abstract Task<SyntaxNode> TryGetApplicableInvocationNodeAsync(Document document, TextSpan span, CancellationToken cancellationToken);
protected abstract string EscapeIdentifier(string identifier);
private class ChangeNamespaceCodeAction : SolutionChangeAction
{
public ChangeNamespaceCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution)
: base(title, createChangedSolution, title)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolDisplayFormats.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SymbolDisplayFormats
{
/// <summary>
/// Standard format for displaying to the user.
/// </summary>
/// <remarks>
/// No return type.
/// </remarks>
public static readonly SymbolDisplayFormat NameFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
/// <summary>
/// Contains enough information to determine whether two symbols have the same signature.
/// </summary>
public static readonly SymbolDisplayFormat SignatureFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SymbolDisplayFormats
{
/// <summary>
/// Standard format for displaying to the user.
/// </summary>
/// <remarks>
/// No return type.
/// </remarks>
public static readonly SymbolDisplayFormat NameFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
/// <summary>
/// Contains enough information to determine whether two symbols have the same signature.
/// </summary>
public static readonly SymbolDisplayFormat SignatureFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeContainingType |
SymbolDisplayMemberOptions.IncludeExplicitInterface |
SymbolDisplayMemberOptions.IncludeType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType);
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType
{
internal abstract class AbstractMoveTypeService : IMoveTypeService
{
/// <summary>
/// Annotation to mark the namespace encapsulating the type that has been moved
/// </summary>
public static SyntaxAnnotation NamespaceScopeMovedAnnotation = new(nameof(MoveTypeOperationKind.MoveTypeNamespaceScope));
public abstract Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken);
public abstract Task<ImmutableArray<CodeAction>> GetRefactoringAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
}
internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> :
AbstractMoveTypeService
where TService : AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax>
where TTypeDeclarationSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
{
public override async Task<ImmutableArray<CodeAction>> GetRefactoringAsync(
Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var state = await CreateStateAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return ImmutableArray<CodeAction>.Empty;
}
var actions = CreateActions(state, cancellationToken);
return actions;
}
public override async Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken)
{
var state = await CreateStateAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return document.Project.Solution;
}
var suggestedFileNames = GetSuggestedFileNames(
state.TypeNode,
IsNestedType(state.TypeNode),
state.TypeName,
state.SemanticDocument.Document.Name,
state.SemanticDocument.SemanticModel,
cancellationToken);
var editor = Editor.GetEditor(operationKind, (TService)this, state, suggestedFileNames.FirstOrDefault(), cancellationToken);
var modifiedSolution = await editor.GetModifiedSolutionAsync().ConfigureAwait(false);
return modifiedSolution ?? document.Project.Solution;
}
protected abstract Task<TTypeDeclarationSyntax> GetRelevantNodeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
private async Task<State> CreateStateAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var nodeToAnalyze = await GetRelevantNodeAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (nodeToAnalyze == null)
{
return null;
}
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
return State.Generate(semanticDocument, nodeToAnalyze, cancellationToken);
}
private ImmutableArray<CodeAction> CreateActions(State state, CancellationToken cancellationToken)
{
var typeMatchesDocumentName = TypeMatchesDocumentName(
state.TypeNode,
state.TypeName,
state.DocumentNameWithoutExtension,
state.SemanticDocument.SemanticModel,
cancellationToken);
if (typeMatchesDocumentName)
{
// if type name matches document name, per style conventions, we have nothing to do.
return ImmutableArray<CodeAction>.Empty;
}
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions);
var manyTypes = MultipleTopLevelTypeDeclarationInSourceDocument(state.SemanticDocument.Root);
var isNestedType = IsNestedType(state.TypeNode);
var syntaxFacts = state.SemanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>();
var isClassNextToGlobalStatements = manyTypes
? false
: ClassNextToGlobalStatements(state.SemanticDocument.Root, syntaxFacts);
var suggestedFileNames = GetSuggestedFileNames(
state.TypeNode,
isNestedType,
state.TypeName,
state.SemanticDocument.Document.Name,
state.SemanticDocument.SemanticModel,
cancellationToken);
// (1) Add Move type to new file code action:
// case 1: There are multiple type declarations in current document. offer, move to new file.
// case 2: This is a nested type, offer to move to new file.
// case 3: If there is a single type decl in current file, *do not* offer move to new file,
// rename actions are sufficient in this case.
// case 4: If there are top level statements(Global statements) offer to move even
// in cases where there are only one class in the file.
if (manyTypes || isNestedType || isClassNextToGlobalStatements)
{
foreach (var fileName in suggestedFileNames)
{
actions.Add(GetCodeAction(state, fileName, operationKind: MoveTypeOperationKind.MoveType));
}
}
// (2) Add rename file and rename type code actions:
// Case: No type declaration in file matches the file name.
if (!AnyTopLevelTypeMatchesDocumentName(state, cancellationToken))
{
foreach (var fileName in suggestedFileNames)
{
actions.Add(GetCodeAction(state, fileName, operationKind: MoveTypeOperationKind.RenameFile));
}
// only if the document name can be legal identifier in the language,
// offer to rename type with document name
if (state.IsDocumentNameAValidIdentifier)
{
actions.Add(GetCodeAction(
state, fileName: state.DocumentNameWithoutExtension,
operationKind: MoveTypeOperationKind.RenameType));
}
}
Debug.Assert(actions.Count != 0, "No code actions found for MoveType Refactoring");
return actions.ToImmutable();
}
private static bool ClassNextToGlobalStatements(SyntaxNode root, ISyntaxFactsService syntaxFacts)
=> syntaxFacts.ContainsGlobalStatement(root);
private CodeAction GetCodeAction(State state, string fileName, MoveTypeOperationKind operationKind) =>
new MoveTypeCodeAction((TService)this, state, operationKind, fileName);
private static bool IsNestedType(TTypeDeclarationSyntax typeNode) =>
typeNode.Parent is TTypeDeclarationSyntax;
/// <summary>
/// checks if there is a single top level type declaration in a document
/// </summary>
/// <remarks>
/// optimized for perf, uses Skip(1).Any() instead of Count() > 1
/// </remarks>
private static bool MultipleTopLevelTypeDeclarationInSourceDocument(SyntaxNode root) =>
TopLevelTypeDeclarations(root).Skip(1).Any();
private static IEnumerable<TTypeDeclarationSyntax> TopLevelTypeDeclarations(SyntaxNode root) =>
root.DescendantNodes(n => n is TCompilationUnitSyntax or TNamespaceDeclarationSyntax)
.OfType<TTypeDeclarationSyntax>();
private static bool AnyTopLevelTypeMatchesDocumentName(State state, CancellationToken cancellationToken)
{
var root = state.SemanticDocument.Root;
var semanticModel = state.SemanticDocument.SemanticModel;
return TopLevelTypeDeclarations(root).Any(
typeDeclaration =>
{
var typeName = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken).Name;
return TypeMatchesDocumentName(
typeDeclaration, typeName, state.DocumentNameWithoutExtension,
semanticModel, cancellationToken);
});
}
/// <summary>
/// checks if type name matches its parent document name, per style rules.
/// </summary>
/// <remarks>
/// Note: For a nested type, a matching document name could be just the type name or a
/// dotted qualified name of its type hierarchy.
/// </remarks>
protected static bool TypeMatchesDocumentName(
TTypeDeclarationSyntax typeNode,
string typeName,
string documentNameWithoutExtension,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// If it is not a nested type, we compare the unqualified type name with the document name.
// If it is a nested type, the type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs`
var namesMatch = typeName.Equals(documentNameWithoutExtension, StringComparison.CurrentCulture);
if (!namesMatch)
{
var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken);
var fileNameParts = documentNameWithoutExtension.Split('.');
// qualified type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs`
return typeNameParts.SequenceEqual(fileNameParts, StringComparer.CurrentCulture);
}
return namesMatch;
}
private static ImmutableArray<string> GetSuggestedFileNames(
TTypeDeclarationSyntax typeNode,
bool isNestedType,
string typeName,
string documentNameWithExtension,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var fileExtension = Path.GetExtension(documentNameWithExtension);
var standaloneName = typeName + fileExtension;
// If it is a nested type, we should match type hierarchy's name parts with the file name.
if (isNestedType)
{
var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken);
var dottedName = typeNameParts.Join(".") + fileExtension;
return ImmutableArray.Create(standaloneName, dottedName);
}
else
{
return ImmutableArray.Create(standaloneName);
}
}
private static IEnumerable<string> GetTypeNamePartsForNestedTypeNode(
TTypeDeclarationSyntax typeNode, SemanticModel semanticModel, CancellationToken cancellationToken) =>
typeNode.AncestorsAndSelf()
.OfType<TTypeDeclarationSyntax>()
.Select(n => semanticModel.GetDeclaredSymbol(n, cancellationToken).Name)
.Reverse();
}
}
| // Licensed to the .NET Foundation under one or more 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType
{
internal abstract class AbstractMoveTypeService : IMoveTypeService
{
/// <summary>
/// Annotation to mark the namespace encapsulating the type that has been moved
/// </summary>
public static SyntaxAnnotation NamespaceScopeMovedAnnotation = new(nameof(MoveTypeOperationKind.MoveTypeNamespaceScope));
public abstract Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken);
public abstract Task<ImmutableArray<CodeAction>> GetRefactoringAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
}
internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> :
AbstractMoveTypeService
where TService : AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax>
where TTypeDeclarationSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
{
public override async Task<ImmutableArray<CodeAction>> GetRefactoringAsync(
Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var state = await CreateStateAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return ImmutableArray<CodeAction>.Empty;
}
var actions = CreateActions(state, cancellationToken);
return actions;
}
public override async Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken)
{
var state = await CreateStateAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return document.Project.Solution;
}
var suggestedFileNames = GetSuggestedFileNames(
state.TypeNode,
IsNestedType(state.TypeNode),
state.TypeName,
state.SemanticDocument.Document.Name,
state.SemanticDocument.SemanticModel,
cancellationToken);
var editor = Editor.GetEditor(operationKind, (TService)this, state, suggestedFileNames.FirstOrDefault(), cancellationToken);
var modifiedSolution = await editor.GetModifiedSolutionAsync().ConfigureAwait(false);
return modifiedSolution ?? document.Project.Solution;
}
protected abstract Task<TTypeDeclarationSyntax> GetRelevantNodeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
private async Task<State> CreateStateAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var nodeToAnalyze = await GetRelevantNodeAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (nodeToAnalyze == null)
{
return null;
}
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
return State.Generate(semanticDocument, nodeToAnalyze, cancellationToken);
}
private ImmutableArray<CodeAction> CreateActions(State state, CancellationToken cancellationToken)
{
var typeMatchesDocumentName = TypeMatchesDocumentName(
state.TypeNode,
state.TypeName,
state.DocumentNameWithoutExtension,
state.SemanticDocument.SemanticModel,
cancellationToken);
if (typeMatchesDocumentName)
{
// if type name matches document name, per style conventions, we have nothing to do.
return ImmutableArray<CodeAction>.Empty;
}
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions);
var manyTypes = MultipleTopLevelTypeDeclarationInSourceDocument(state.SemanticDocument.Root);
var isNestedType = IsNestedType(state.TypeNode);
var syntaxFacts = state.SemanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>();
var isClassNextToGlobalStatements = manyTypes
? false
: ClassNextToGlobalStatements(state.SemanticDocument.Root, syntaxFacts);
var suggestedFileNames = GetSuggestedFileNames(
state.TypeNode,
isNestedType,
state.TypeName,
state.SemanticDocument.Document.Name,
state.SemanticDocument.SemanticModel,
cancellationToken);
// (1) Add Move type to new file code action:
// case 1: There are multiple type declarations in current document. offer, move to new file.
// case 2: This is a nested type, offer to move to new file.
// case 3: If there is a single type decl in current file, *do not* offer move to new file,
// rename actions are sufficient in this case.
// case 4: If there are top level statements(Global statements) offer to move even
// in cases where there are only one class in the file.
if (manyTypes || isNestedType || isClassNextToGlobalStatements)
{
foreach (var fileName in suggestedFileNames)
{
actions.Add(GetCodeAction(state, fileName, operationKind: MoveTypeOperationKind.MoveType));
}
}
// (2) Add rename file and rename type code actions:
// Case: No type declaration in file matches the file name.
if (!AnyTopLevelTypeMatchesDocumentName(state, cancellationToken))
{
foreach (var fileName in suggestedFileNames)
{
actions.Add(GetCodeAction(state, fileName, operationKind: MoveTypeOperationKind.RenameFile));
}
// only if the document name can be legal identifier in the language,
// offer to rename type with document name
if (state.IsDocumentNameAValidIdentifier)
{
actions.Add(GetCodeAction(
state, fileName: state.DocumentNameWithoutExtension,
operationKind: MoveTypeOperationKind.RenameType));
}
}
Debug.Assert(actions.Count != 0, "No code actions found for MoveType Refactoring");
return actions.ToImmutable();
}
private static bool ClassNextToGlobalStatements(SyntaxNode root, ISyntaxFactsService syntaxFacts)
=> syntaxFacts.ContainsGlobalStatement(root);
private CodeAction GetCodeAction(State state, string fileName, MoveTypeOperationKind operationKind) =>
new MoveTypeCodeAction((TService)this, state, operationKind, fileName);
private static bool IsNestedType(TTypeDeclarationSyntax typeNode) =>
typeNode.Parent is TTypeDeclarationSyntax;
/// <summary>
/// checks if there is a single top level type declaration in a document
/// </summary>
/// <remarks>
/// optimized for perf, uses Skip(1).Any() instead of Count() > 1
/// </remarks>
private static bool MultipleTopLevelTypeDeclarationInSourceDocument(SyntaxNode root) =>
TopLevelTypeDeclarations(root).Skip(1).Any();
private static IEnumerable<TTypeDeclarationSyntax> TopLevelTypeDeclarations(SyntaxNode root) =>
root.DescendantNodes(n => n is TCompilationUnitSyntax or TNamespaceDeclarationSyntax)
.OfType<TTypeDeclarationSyntax>();
private static bool AnyTopLevelTypeMatchesDocumentName(State state, CancellationToken cancellationToken)
{
var root = state.SemanticDocument.Root;
var semanticModel = state.SemanticDocument.SemanticModel;
return TopLevelTypeDeclarations(root).Any(
typeDeclaration =>
{
var typeName = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken).Name;
return TypeMatchesDocumentName(
typeDeclaration, typeName, state.DocumentNameWithoutExtension,
semanticModel, cancellationToken);
});
}
/// <summary>
/// checks if type name matches its parent document name, per style rules.
/// </summary>
/// <remarks>
/// Note: For a nested type, a matching document name could be just the type name or a
/// dotted qualified name of its type hierarchy.
/// </remarks>
protected static bool TypeMatchesDocumentName(
TTypeDeclarationSyntax typeNode,
string typeName,
string documentNameWithoutExtension,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// If it is not a nested type, we compare the unqualified type name with the document name.
// If it is a nested type, the type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs`
var namesMatch = typeName.Equals(documentNameWithoutExtension, StringComparison.CurrentCulture);
if (!namesMatch)
{
var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken);
var fileNameParts = documentNameWithoutExtension.Split('.');
// qualified type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs`
return typeNameParts.SequenceEqual(fileNameParts, StringComparer.CurrentCulture);
}
return namesMatch;
}
private static ImmutableArray<string> GetSuggestedFileNames(
TTypeDeclarationSyntax typeNode,
bool isNestedType,
string typeName,
string documentNameWithExtension,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var fileExtension = Path.GetExtension(documentNameWithExtension);
var standaloneName = typeName + fileExtension;
// If it is a nested type, we should match type hierarchy's name parts with the file name.
if (isNestedType)
{
var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken);
var dottedName = typeNameParts.Join(".") + fileExtension;
return ImmutableArray.Create(standaloneName, dottedName);
}
else
{
return ImmutableArray.Create(standaloneName);
}
}
private static IEnumerable<string> GetTypeNamePartsForNestedTypeNode(
TTypeDeclarationSyntax typeNode, SemanticModel semanticModel, CancellationToken cancellationToken) =>
typeNode.AncestorsAndSelf()
.OfType<TTypeDeclarationSyntax>()
.Select(n => semanticModel.GetDeclaredSymbol(n, cancellationToken).Name)
.Reverse();
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/EditorFeatures/CSharpTest2/Recommendations/ByteKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ByteKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot()
{
await VerifyKeywordAsync(
@"$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement()
{
await VerifyKeywordAsync(
@"System.Console.WriteLine();
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration()
{
await VerifyKeywordAsync(
@"int i = 0;
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* goo = stackalloc $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInFixedStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"fixed ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInCastType(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInCastType2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterConstInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterConstLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInEmptyStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"enum E : $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType1(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType3(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType4(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterIs(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo is $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAs(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo as $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInLocalVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInForVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInForeachVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInUsingVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInFromVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInJoinVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterNewInExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInTypeOf(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInDefault(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInSizeOf(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(byte x) { }
}
");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinType()
{
await VerifyKeywordAsync(@"
class Program
{
($$
}");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInTupleWithinMember(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ByteKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot()
{
await VerifyKeywordAsync(
@"$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement()
{
await VerifyKeywordAsync(
@"System.Console.WriteLine();
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration()
{
await VerifyKeywordAsync(
@"int i = 0;
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* goo = stackalloc $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInFixedStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"fixed ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInCastType(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInCastType2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterConstInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterConstLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInEmptyStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"enum E : $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType1(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType3(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType4(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterIs(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo is $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAs(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo as $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInLocalVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInForVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInForeachVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInUsingVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInFromVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInJoinVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterNewInExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInTypeOf(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInDefault(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInSizeOf(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(byte x) { }
}
");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinType()
{
await VerifyKeywordAsync(@"
class Program
{
($$
}");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInTupleWithinMember(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Dependencies/Collections/ImmutableSegmentedList`1+PrivateInterlocked.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.Runtime.CompilerServices;
using System.Threading;
namespace Microsoft.CodeAnalysis.Collections
{
internal partial struct ImmutableSegmentedList<T>
{
/// <summary>
/// Private helper class for use only by <see cref="RoslynImmutableInterlocked"/>.
/// </summary>
internal static class PrivateInterlocked
{
internal static ImmutableSegmentedList<T> VolatileRead(in ImmutableSegmentedList<T> location)
{
var list = Volatile.Read(ref Unsafe.AsRef(in location._list));
if (list is null)
return default;
return new ImmutableSegmentedList<T>(list);
}
internal static ImmutableSegmentedList<T> InterlockedExchange(ref ImmutableSegmentedList<T> location, ImmutableSegmentedList<T> value)
{
var list = Interlocked.Exchange(ref Unsafe.AsRef(in location._list), value._list);
if (list is null)
return default;
return new ImmutableSegmentedList<T>(list);
}
internal static ImmutableSegmentedList<T> InterlockedCompareExchange(ref ImmutableSegmentedList<T> location, ImmutableSegmentedList<T> value, ImmutableSegmentedList<T> comparand)
{
var list = Interlocked.CompareExchange(ref Unsafe.AsRef(in location._list), value._list, comparand._list);
if (list is null)
return default;
return new ImmutableSegmentedList<T>(list);
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices;
using System.Threading;
namespace Microsoft.CodeAnalysis.Collections
{
internal partial struct ImmutableSegmentedList<T>
{
/// <summary>
/// Private helper class for use only by <see cref="RoslynImmutableInterlocked"/>.
/// </summary>
internal static class PrivateInterlocked
{
internal static ImmutableSegmentedList<T> VolatileRead(in ImmutableSegmentedList<T> location)
{
var list = Volatile.Read(ref Unsafe.AsRef(in location._list));
if (list is null)
return default;
return new ImmutableSegmentedList<T>(list);
}
internal static ImmutableSegmentedList<T> InterlockedExchange(ref ImmutableSegmentedList<T> location, ImmutableSegmentedList<T> value)
{
var list = Interlocked.Exchange(ref Unsafe.AsRef(in location._list), value._list);
if (list is null)
return default;
return new ImmutableSegmentedList<T>(list);
}
internal static ImmutableSegmentedList<T> InterlockedCompareExchange(ref ImmutableSegmentedList<T> location, ImmutableSegmentedList<T> value, ImmutableSegmentedList<T> comparand)
{
var list = Interlocked.CompareExchange(ref Unsafe.AsRef(in location._list), value._list, comparand._list);
if (list is null)
return default;
return new ImmutableSegmentedList<T>(list);
}
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/Core/Portable/SolutionCrawler/IDocumentDifferenceService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal class DocumentDifferenceResult
{
public InvocationReasons ChangeType { get; }
public SyntaxNode? ChangedMember { get; }
public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null)
{
ChangeType = changeType;
ChangedMember = changedMember;
}
}
internal interface IDocumentDifferenceService : ILanguageService
{
Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal class DocumentDifferenceResult
{
public InvocationReasons ChangeType { get; }
public SyntaxNode? ChangedMember { get; }
public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null)
{
ChangeType = changeType;
ChangedMember = changedMember;
}
}
internal interface IDocumentDifferenceService : ILanguageService
{
Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/Core/Portable/SignatureHelp/SignatureHelpItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SignatureHelp
{
internal class SignatureHelpItem
{
/// <summary>
/// True if this signature help item can have an unbounded number of arguments passed to it.
/// If it is variadic then the last parameter will be considered selected, even if the
/// selected parameter index strictly goes past the number of defined parameters for this
/// item.
/// </summary>
public bool IsVariadic { get; }
public ImmutableArray<TaggedText> PrefixDisplayParts { get; }
public ImmutableArray<TaggedText> SuffixDisplayParts { get; }
// TODO: This probably won't be sufficient for VB query signature help. It has
// arbitrary separators between parameters.
public ImmutableArray<TaggedText> SeparatorDisplayParts { get; }
public ImmutableArray<SignatureHelpParameter> Parameters { get; }
public ImmutableArray<TaggedText> DescriptionParts { get; internal set; }
public Func<CancellationToken, IEnumerable<TaggedText>> DocumentationFactory { get; }
private static readonly Func<CancellationToken, IEnumerable<TaggedText>> s_emptyDocumentationFactory =
_ => SpecializedCollections.EmptyEnumerable<TaggedText>();
public SignatureHelpItem(
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IEnumerable<TaggedText> prefixParts,
IEnumerable<TaggedText> separatorParts,
IEnumerable<TaggedText> suffixParts,
IEnumerable<SignatureHelpParameter> parameters,
IEnumerable<TaggedText>? descriptionParts)
{
if (isVariadic && !parameters.Any())
{
throw new ArgumentException(FeaturesResources.Variadic_SignatureHelpItem_must_have_at_least_one_parameter);
}
IsVariadic = isVariadic;
DocumentationFactory = documentationFactory ?? s_emptyDocumentationFactory;
PrefixDisplayParts = prefixParts.ToImmutableArrayOrEmpty();
SeparatorDisplayParts = separatorParts.ToImmutableArrayOrEmpty();
SuffixDisplayParts = suffixParts.ToImmutableArrayOrEmpty();
Parameters = parameters.ToImmutableArrayOrEmpty();
DescriptionParts = descriptionParts.ToImmutableArrayOrEmpty();
}
// Constructor kept for back compat
public SignatureHelpItem(
bool isVariadic,
Func<CancellationToken, IEnumerable<SymbolDisplayPart>> documentationFactory,
IEnumerable<SymbolDisplayPart> prefixParts,
IEnumerable<SymbolDisplayPart> separatorParts,
IEnumerable<SymbolDisplayPart> suffixParts,
IEnumerable<SignatureHelpParameter> parameters,
IEnumerable<SymbolDisplayPart> descriptionParts)
: this(isVariadic,
documentationFactory != null
? c => documentationFactory(c).ToTaggedText()
: s_emptyDocumentationFactory,
prefixParts.ToTaggedText(),
separatorParts.ToTaggedText(),
suffixParts.ToTaggedText(),
parameters,
descriptionParts.ToTaggedText())
{
}
internal IEnumerable<TaggedText> GetAllParts()
{
return
PrefixDisplayParts.Concat(
SeparatorDisplayParts.Concat(
SuffixDisplayParts.Concat(
Parameters.SelectMany(p => p.GetAllParts())).Concat(
DescriptionParts)));
}
public override string ToString()
{
var prefix = string.Concat(PrefixDisplayParts);
var suffix = string.Concat(SuffixDisplayParts);
var parameters = string.Join(string.Concat(SeparatorDisplayParts), Parameters);
var description = string.Concat(DescriptionParts);
return string.Concat(prefix, parameters, suffix, description);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SignatureHelp
{
internal class SignatureHelpItem
{
/// <summary>
/// True if this signature help item can have an unbounded number of arguments passed to it.
/// If it is variadic then the last parameter will be considered selected, even if the
/// selected parameter index strictly goes past the number of defined parameters for this
/// item.
/// </summary>
public bool IsVariadic { get; }
public ImmutableArray<TaggedText> PrefixDisplayParts { get; }
public ImmutableArray<TaggedText> SuffixDisplayParts { get; }
// TODO: This probably won't be sufficient for VB query signature help. It has
// arbitrary separators between parameters.
public ImmutableArray<TaggedText> SeparatorDisplayParts { get; }
public ImmutableArray<SignatureHelpParameter> Parameters { get; }
public ImmutableArray<TaggedText> DescriptionParts { get; internal set; }
public Func<CancellationToken, IEnumerable<TaggedText>> DocumentationFactory { get; }
private static readonly Func<CancellationToken, IEnumerable<TaggedText>> s_emptyDocumentationFactory =
_ => SpecializedCollections.EmptyEnumerable<TaggedText>();
public SignatureHelpItem(
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IEnumerable<TaggedText> prefixParts,
IEnumerable<TaggedText> separatorParts,
IEnumerable<TaggedText> suffixParts,
IEnumerable<SignatureHelpParameter> parameters,
IEnumerable<TaggedText>? descriptionParts)
{
if (isVariadic && !parameters.Any())
{
throw new ArgumentException(FeaturesResources.Variadic_SignatureHelpItem_must_have_at_least_one_parameter);
}
IsVariadic = isVariadic;
DocumentationFactory = documentationFactory ?? s_emptyDocumentationFactory;
PrefixDisplayParts = prefixParts.ToImmutableArrayOrEmpty();
SeparatorDisplayParts = separatorParts.ToImmutableArrayOrEmpty();
SuffixDisplayParts = suffixParts.ToImmutableArrayOrEmpty();
Parameters = parameters.ToImmutableArrayOrEmpty();
DescriptionParts = descriptionParts.ToImmutableArrayOrEmpty();
}
// Constructor kept for back compat
public SignatureHelpItem(
bool isVariadic,
Func<CancellationToken, IEnumerable<SymbolDisplayPart>> documentationFactory,
IEnumerable<SymbolDisplayPart> prefixParts,
IEnumerable<SymbolDisplayPart> separatorParts,
IEnumerable<SymbolDisplayPart> suffixParts,
IEnumerable<SignatureHelpParameter> parameters,
IEnumerable<SymbolDisplayPart> descriptionParts)
: this(isVariadic,
documentationFactory != null
? c => documentationFactory(c).ToTaggedText()
: s_emptyDocumentationFactory,
prefixParts.ToTaggedText(),
separatorParts.ToTaggedText(),
suffixParts.ToTaggedText(),
parameters,
descriptionParts.ToTaggedText())
{
}
internal IEnumerable<TaggedText> GetAllParts()
{
return
PrefixDisplayParts.Concat(
SeparatorDisplayParts.Concat(
SuffixDisplayParts.Concat(
Parameters.SelectMany(p => p.GetAllParts())).Concat(
DescriptionParts)));
}
public override string ToString()
{
var prefix = string.Concat(PrefixDisplayParts);
var suffix = string.Concat(SuffixDisplayParts);
var parameters = string.Join(string.Concat(SeparatorDisplayParts), Parameters);
var description = string.Concat(DescriptionParts);
return string.Concat(prefix, parameters, suffix, description);
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Analyzers/Core/CodeFixes/SimplifyBooleanExpression/SimplifyConditionalCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.SimplifyBooleanExpression
{
using static SimplifyBooleanExpressionConstants;
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.SimplifyConditionalExpression), Shared]
internal sealed class SimplifyConditionalCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public SimplifyConditionalCodeFixProvider()
{
}
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(IDEDiagnosticIds.SimplifyConditionalExpressionDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory
=> CodeFixCategory.CodeQuality;
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected sealed override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var generator = SyntaxGenerator.GetGenerator(document);
var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>();
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var expr = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken);
syntaxFacts.GetPartsOfConditionalExpression(expr, out var condition, out var whenTrue, out var whenFalse);
if (diagnostic.Properties.ContainsKey(Negate))
condition = generator.Negate(generatorInternal, condition, semanticModel, cancellationToken);
var replacement = condition;
if (diagnostic.Properties.ContainsKey(Or))
{
var right = diagnostic.Properties.ContainsKey(WhenTrue) ? whenTrue : whenFalse;
replacement = generator.LogicalOrExpression(condition, right);
}
else if (diagnostic.Properties.ContainsKey(And))
{
var right = diagnostic.Properties.ContainsKey(WhenTrue) ? whenTrue : whenFalse;
replacement = generator.LogicalAndExpression(condition, right);
}
editor.ReplaceNode(
expr, generatorInternal.AddParentheses(replacement.WithTriviaFrom(expr)));
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Simplify_conditional_expression, createChangedDocument, AnalyzersResources.Simplify_conditional_expression)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.SimplifyBooleanExpression
{
using static SimplifyBooleanExpressionConstants;
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.SimplifyConditionalExpression), Shared]
internal sealed class SimplifyConditionalCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public SimplifyConditionalCodeFixProvider()
{
}
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(IDEDiagnosticIds.SimplifyConditionalExpressionDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory
=> CodeFixCategory.CodeQuality;
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected sealed override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var generator = SyntaxGenerator.GetGenerator(document);
var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>();
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var expr = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken);
syntaxFacts.GetPartsOfConditionalExpression(expr, out var condition, out var whenTrue, out var whenFalse);
if (diagnostic.Properties.ContainsKey(Negate))
condition = generator.Negate(generatorInternal, condition, semanticModel, cancellationToken);
var replacement = condition;
if (diagnostic.Properties.ContainsKey(Or))
{
var right = diagnostic.Properties.ContainsKey(WhenTrue) ? whenTrue : whenFalse;
replacement = generator.LogicalOrExpression(condition, right);
}
else if (diagnostic.Properties.ContainsKey(And))
{
var right = diagnostic.Properties.ContainsKey(WhenTrue) ? whenTrue : whenFalse;
replacement = generator.LogicalAndExpression(condition, right);
}
editor.ReplaceNode(
expr, generatorInternal.AddParentheses(replacement.WithTriviaFrom(expr)));
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Simplify_conditional_expression, createChangedDocument, AnalyzersResources.Simplify_conditional_expression)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/Server/VBCSCompilerTests/NamedPipeTestUtil.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.Diagnostics;
using System.IO.Pipes;
using System.Reflection;
using System.Net.Sockets;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
/// <summary>
/// This is a HACK that allows you to get at the underlying Socket for a given NamedPipeServerStream
/// instance. It is very useful it proactively diagnosing bugs in the server code by letting us inspect
/// the socket to see if it's disposed, not available, etc ... vs. experiencing flaky bugs that are
/// incredibly difficult to track down.
///
/// Do NOT check this into production, it's a unit test utility only
/// </summary>
internal static class NamedPipeTestUtil
{
private static IDictionary GetSharedServersDictionary()
{
var sharedServerFullName = typeof(NamedPipeServerStream).FullName + "+SharedServer";
var sharedServerType = typeof(NamedPipeServerStream).Assembly.GetType(sharedServerFullName);
var serversField = sharedServerType?.GetField("s_servers", BindingFlags.NonPublic | BindingFlags.Static);
var servers = (IDictionary?)serversField?.GetValue(null);
if (servers is null)
{
throw new Exception("Cannot locate the SharedServer dictionary");
}
return servers;
}
private static Socket GetSocket(object sharedServer)
{
var listeningSocketProperty = sharedServer!.GetType()?.GetProperty("ListeningSocket", BindingFlags.NonPublic | BindingFlags.Instance);
var socket = (Socket?)listeningSocketProperty?.GetValue(sharedServer, null);
if (socket is null)
{
throw new Exception("Socket is unexpectedly null");
}
return socket;
}
private static Socket? GetSocketForPipeName(string pipeName)
{
if (!ExecutionConditionUtil.IsUnix || !ExecutionConditionUtil.IsCoreClr)
{
return null;
}
pipeName = "/tmp/" + pipeName;
var servers = GetSharedServersDictionary();
lock (servers)
{
if (!servers.Contains(pipeName))
{
return null;
}
var sharedServer = servers[pipeName];
Debug.Assert(sharedServer is object);
return GetSocket(sharedServer);
}
}
internal static bool IsPipeFullyClosed(string pipeName) => GetSocketForPipeName(pipeName) is null;
internal static void DisposeAll()
{
if (!ExecutionConditionUtil.IsUnix || !ExecutionConditionUtil.IsCoreClr)
{
return;
}
var servers = GetSharedServersDictionary();
lock (servers)
{
var e = servers.GetEnumerator();
while (e.MoveNext())
{
var sharedServer = e.Value!;
var socket = GetSocket(sharedServer);
socket.Dispose();
}
servers.Clear();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Pipes;
using System.Reflection;
using System.Net.Sockets;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
/// <summary>
/// This is a HACK that allows you to get at the underlying Socket for a given NamedPipeServerStream
/// instance. It is very useful it proactively diagnosing bugs in the server code by letting us inspect
/// the socket to see if it's disposed, not available, etc ... vs. experiencing flaky bugs that are
/// incredibly difficult to track down.
///
/// Do NOT check this into production, it's a unit test utility only
/// </summary>
internal static class NamedPipeTestUtil
{
private static IDictionary GetSharedServersDictionary()
{
var sharedServerFullName = typeof(NamedPipeServerStream).FullName + "+SharedServer";
var sharedServerType = typeof(NamedPipeServerStream).Assembly.GetType(sharedServerFullName);
var serversField = sharedServerType?.GetField("s_servers", BindingFlags.NonPublic | BindingFlags.Static);
var servers = (IDictionary?)serversField?.GetValue(null);
if (servers is null)
{
throw new Exception("Cannot locate the SharedServer dictionary");
}
return servers;
}
private static Socket GetSocket(object sharedServer)
{
var listeningSocketProperty = sharedServer!.GetType()?.GetProperty("ListeningSocket", BindingFlags.NonPublic | BindingFlags.Instance);
var socket = (Socket?)listeningSocketProperty?.GetValue(sharedServer, null);
if (socket is null)
{
throw new Exception("Socket is unexpectedly null");
}
return socket;
}
private static Socket? GetSocketForPipeName(string pipeName)
{
if (!ExecutionConditionUtil.IsUnix || !ExecutionConditionUtil.IsCoreClr)
{
return null;
}
pipeName = "/tmp/" + pipeName;
var servers = GetSharedServersDictionary();
lock (servers)
{
if (!servers.Contains(pipeName))
{
return null;
}
var sharedServer = servers[pipeName];
Debug.Assert(sharedServer is object);
return GetSocket(sharedServer);
}
}
internal static bool IsPipeFullyClosed(string pipeName) => GetSocketForPipeName(pipeName) is null;
internal static void DisposeAll()
{
if (!ExecutionConditionUtil.IsUnix || !ExecutionConditionUtil.IsCoreClr)
{
return;
}
var servers = GetSharedServersDictionary();
lock (servers)
{
var e = servers.GetEnumerator();
while (e.MoveNext())
{
var sharedServer = e.Value!;
var socket = GetSocket(sharedServer);
socket.Dispose();
}
servers.Clear();
}
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.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.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class BlockSyntaxStructureProvider : AbstractSyntaxNodeStructureProvider<BlockSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
BlockSyntax node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
var parentKind = node.Parent.Kind();
// For most types of statements, just consider the block 'attached' to the
// parent node. That means we'll show the parent node header when doing
// things like hovering over the indent guide.
//
// This also works nicely as the close brace for these constructs will always
// align with the start of these statements.
if (IsNonBlockStatement(node.Parent) ||
parentKind == SyntaxKind.ElseClause)
{
var type = GetType(node.Parent);
if (type != null)
{
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: GetTextSpan(node),
hintSpan: GetHintSpan(node),
type: type,
autoCollapse: parentKind == SyntaxKind.LocalFunctionStatement && node.Parent.IsParentKind(SyntaxKind.GlobalStatement)));
}
}
// Nested blocks aren't attached to anything. Just collapse them as is.
// Switch sections are also special. Say you have the following:
//
// case 0:
// {
//
// }
//
// We don't want to consider the block parented by the case, because
// that would cause us to draw the following:
//
// case 0:
// | {
// |
// | }
//
// Which would obviously be wonky. So in this case, we just use the
// spanof the block alone, without consideration for the case clause.
if (parentKind == SyntaxKind.Block || parentKind == SyntaxKind.SwitchSection)
{
var type = GetType(node.Parent);
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: node.Span,
hintSpan: node.Span,
type: type));
}
}
private static bool IsNonBlockStatement(SyntaxNode node)
=> node is StatementSyntax && !node.IsKind(SyntaxKind.Block);
private static TextSpan GetHintSpan(BlockSyntax node)
{
var parent = node.Parent;
if (parent.IsKind(SyntaxKind.IfStatement) && parent.IsParentKind(SyntaxKind.ElseClause))
{
parent = parent.Parent;
}
var start = parent.Span.Start;
var end = GetEnd(node);
return TextSpan.FromBounds(start, end);
}
private static TextSpan GetTextSpan(BlockSyntax node)
{
var previousToken = node.GetFirstToken().GetPreviousToken();
if (previousToken.IsKind(SyntaxKind.None))
{
return node.Span;
}
return TextSpan.FromBounds(previousToken.Span.End, GetEnd(node));
}
private static int GetEnd(BlockSyntax node)
{
if (node.Parent.IsKind(SyntaxKind.IfStatement))
{
// For an if-statement, just collapse up to the end of the block.
// We don't want collapse the whole statement just for the 'true'
// portion. Also, while outlining might be ok, the Indent-Guide
// would look very strange for nodes like:
//
// if (goo)
// {
// }
// else
// return a ||
// b;
return node.Span.End;
}
else
{
// For all other constructs, we collapse up to the end of the parent
// construct.
return node.Parent.Span.End;
}
}
private static string GetType(SyntaxNode parent)
{
switch (parent.Kind())
{
case SyntaxKind.ForStatement: return BlockTypes.Loop;
case SyntaxKind.ForEachStatement: return BlockTypes.Loop;
case SyntaxKind.ForEachVariableStatement: return BlockTypes.Loop;
case SyntaxKind.WhileStatement: return BlockTypes.Loop;
case SyntaxKind.DoStatement: return BlockTypes.Loop;
case SyntaxKind.TryStatement: return BlockTypes.Statement;
case SyntaxKind.CatchClause: return BlockTypes.Statement;
case SyntaxKind.FinallyClause: return BlockTypes.Statement;
case SyntaxKind.UnsafeStatement: return BlockTypes.Statement;
case SyntaxKind.FixedStatement: return BlockTypes.Statement;
case SyntaxKind.LockStatement: return BlockTypes.Statement;
case SyntaxKind.UsingStatement: return BlockTypes.Statement;
case SyntaxKind.IfStatement: return BlockTypes.Conditional;
case SyntaxKind.ElseClause: return BlockTypes.Conditional;
case SyntaxKind.SwitchSection: return BlockTypes.Conditional;
case SyntaxKind.Block: return BlockTypes.Statement;
case SyntaxKind.LocalFunctionStatement: return BlockTypes.Statement;
}
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class BlockSyntaxStructureProvider : AbstractSyntaxNodeStructureProvider<BlockSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
BlockSyntax node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
var parentKind = node.Parent.Kind();
// For most types of statements, just consider the block 'attached' to the
// parent node. That means we'll show the parent node header when doing
// things like hovering over the indent guide.
//
// This also works nicely as the close brace for these constructs will always
// align with the start of these statements.
if (IsNonBlockStatement(node.Parent) ||
parentKind == SyntaxKind.ElseClause)
{
var type = GetType(node.Parent);
if (type != null)
{
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: GetTextSpan(node),
hintSpan: GetHintSpan(node),
type: type,
autoCollapse: parentKind == SyntaxKind.LocalFunctionStatement && node.Parent.IsParentKind(SyntaxKind.GlobalStatement)));
}
}
// Nested blocks aren't attached to anything. Just collapse them as is.
// Switch sections are also special. Say you have the following:
//
// case 0:
// {
//
// }
//
// We don't want to consider the block parented by the case, because
// that would cause us to draw the following:
//
// case 0:
// | {
// |
// | }
//
// Which would obviously be wonky. So in this case, we just use the
// spanof the block alone, without consideration for the case clause.
if (parentKind == SyntaxKind.Block || parentKind == SyntaxKind.SwitchSection)
{
var type = GetType(node.Parent);
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: node.Span,
hintSpan: node.Span,
type: type));
}
}
private static bool IsNonBlockStatement(SyntaxNode node)
=> node is StatementSyntax && !node.IsKind(SyntaxKind.Block);
private static TextSpan GetHintSpan(BlockSyntax node)
{
var parent = node.Parent;
if (parent.IsKind(SyntaxKind.IfStatement) && parent.IsParentKind(SyntaxKind.ElseClause))
{
parent = parent.Parent;
}
var start = parent.Span.Start;
var end = GetEnd(node);
return TextSpan.FromBounds(start, end);
}
private static TextSpan GetTextSpan(BlockSyntax node)
{
var previousToken = node.GetFirstToken().GetPreviousToken();
if (previousToken.IsKind(SyntaxKind.None))
{
return node.Span;
}
return TextSpan.FromBounds(previousToken.Span.End, GetEnd(node));
}
private static int GetEnd(BlockSyntax node)
{
if (node.Parent.IsKind(SyntaxKind.IfStatement))
{
// For an if-statement, just collapse up to the end of the block.
// We don't want collapse the whole statement just for the 'true'
// portion. Also, while outlining might be ok, the Indent-Guide
// would look very strange for nodes like:
//
// if (goo)
// {
// }
// else
// return a ||
// b;
return node.Span.End;
}
else
{
// For all other constructs, we collapse up to the end of the parent
// construct.
return node.Parent.Span.End;
}
}
private static string GetType(SyntaxNode parent)
{
switch (parent.Kind())
{
case SyntaxKind.ForStatement: return BlockTypes.Loop;
case SyntaxKind.ForEachStatement: return BlockTypes.Loop;
case SyntaxKind.ForEachVariableStatement: return BlockTypes.Loop;
case SyntaxKind.WhileStatement: return BlockTypes.Loop;
case SyntaxKind.DoStatement: return BlockTypes.Loop;
case SyntaxKind.TryStatement: return BlockTypes.Statement;
case SyntaxKind.CatchClause: return BlockTypes.Statement;
case SyntaxKind.FinallyClause: return BlockTypes.Statement;
case SyntaxKind.UnsafeStatement: return BlockTypes.Statement;
case SyntaxKind.FixedStatement: return BlockTypes.Statement;
case SyntaxKind.LockStatement: return BlockTypes.Statement;
case SyntaxKind.UsingStatement: return BlockTypes.Statement;
case SyntaxKind.IfStatement: return BlockTypes.Conditional;
case SyntaxKind.ElseClause: return BlockTypes.Conditional;
case SyntaxKind.SwitchSection: return BlockTypes.Conditional;
case SyntaxKind.Block: return BlockTypes.Statement;
case SyntaxKind.LocalFunctionStatement: return BlockTypes.Statement;
}
return null;
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/Core/Portable/ExtractMethod/InsertionPoint.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal class InsertionPoint
{
private readonly SyntaxAnnotation _annotation;
private readonly Lazy<SyntaxNode?> _context;
public static async Task<InsertionPoint> CreateAsync(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
{
var root = document.Root;
var annotation = new SyntaxAnnotation();
var newRoot = root.AddAnnotations(SpecializedCollections.SingletonEnumerable(Tuple.Create(node, annotation)));
return new InsertionPoint(await document.WithSyntaxRootAsync(newRoot, cancellationToken).ConfigureAwait(false), annotation);
}
private InsertionPoint(SemanticDocument document, SyntaxAnnotation annotation)
{
Contract.ThrowIfNull(document);
Contract.ThrowIfNull(annotation);
SemanticDocument = document;
_annotation = annotation;
_context = CreateLazyContextNode();
}
public SemanticDocument SemanticDocument { get; }
public SyntaxNode GetRoot()
=> SemanticDocument.Root;
public SyntaxNode? GetContext()
=> _context.Value;
public InsertionPoint With(SemanticDocument document)
=> new(document, _annotation);
private Lazy<SyntaxNode?> CreateLazyContextNode()
=> new(ComputeContextNode, isThreadSafe: true);
private SyntaxNode? ComputeContextNode()
{
var root = SemanticDocument.Root;
return root.GetAnnotatedNodesAndTokens(_annotation).SingleOrDefault().AsNode();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal class InsertionPoint
{
private readonly SyntaxAnnotation _annotation;
private readonly Lazy<SyntaxNode?> _context;
public static async Task<InsertionPoint> CreateAsync(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
{
var root = document.Root;
var annotation = new SyntaxAnnotation();
var newRoot = root.AddAnnotations(SpecializedCollections.SingletonEnumerable(Tuple.Create(node, annotation)));
return new InsertionPoint(await document.WithSyntaxRootAsync(newRoot, cancellationToken).ConfigureAwait(false), annotation);
}
private InsertionPoint(SemanticDocument document, SyntaxAnnotation annotation)
{
Contract.ThrowIfNull(document);
Contract.ThrowIfNull(annotation);
SemanticDocument = document;
_annotation = annotation;
_context = CreateLazyContextNode();
}
public SemanticDocument SemanticDocument { get; }
public SyntaxNode GetRoot()
=> SemanticDocument.Root;
public SyntaxNode? GetContext()
=> _context.Value;
public InsertionPoint With(SemanticDocument document)
=> new(document, _annotation);
private Lazy<SyntaxNode?> CreateLazyContextNode()
=> new(ComputeContextNode, isThreadSafe: true);
private SyntaxNode? ComputeContextNode()
{
var root = SemanticDocument.Root;
return root.GetAnnotatedNodesAndTokens(_annotation).SingleOrDefault().AsNode();
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/EditorFeatures/Core.Wpf/NavigateTo/NavigateToItemProvider.Callback.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.NavigateTo;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Microsoft.VisualStudio.Text.PatternMatching;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
internal partial class NavigateToItemProvider
{
private class NavigateToItemProviderCallback : INavigateToSearchCallback
{
private readonly INavigateToItemDisplayFactory _displayFactory;
private readonly INavigateToCallback _callback;
public NavigateToItemProviderCallback(INavigateToItemDisplayFactory displayFactory, INavigateToCallback callback)
{
_displayFactory = displayFactory;
_callback = callback;
}
public void Done(bool isFullyLoaded)
{
if (!isFullyLoaded && _callback is INavigateToCallback2 callback2)
{
callback2.Done(IncompleteReason.SolutionLoading);
}
else
{
_callback.Done();
}
}
public Task AddItemAsync(Project project, INavigateToSearchResult result, CancellationToken cancellationToken)
{
ReportMatchResult(project, result);
return Task.CompletedTask;
}
public void ReportProgress(int current, int maximum)
{
_callback.ReportProgress(current, maximum);
}
private void ReportMatchResult(Project project, INavigateToSearchResult result)
{
var matchedSpans = result.NameMatchSpans.SelectAsArray(t => t.ToSpan());
var patternMatch = new PatternMatch(
GetPatternMatchKind(result.MatchKind),
punctuationStripped: false,
result.IsCaseSensitive,
matchedSpans);
var navigateToItem = new NavigateToItem(
result.Name,
result.Kind,
GetNavigateToLanguage(project.Language),
result.SecondarySort,
result,
patternMatch,
_displayFactory);
_callback.AddItem(navigateToItem);
}
private static PatternMatchKind GetPatternMatchKind(NavigateToMatchKind matchKind)
=> matchKind switch
{
NavigateToMatchKind.Exact => PatternMatchKind.Exact,
NavigateToMatchKind.Prefix => PatternMatchKind.Prefix,
NavigateToMatchKind.Substring => PatternMatchKind.Substring,
NavigateToMatchKind.Regular => PatternMatchKind.Fuzzy,
NavigateToMatchKind.None => PatternMatchKind.Fuzzy,
NavigateToMatchKind.CamelCaseExact => PatternMatchKind.CamelCaseExact,
NavigateToMatchKind.CamelCasePrefix => PatternMatchKind.CamelCasePrefix,
NavigateToMatchKind.CamelCaseNonContiguousPrefix => PatternMatchKind.CamelCaseNonContiguousPrefix,
NavigateToMatchKind.CamelCaseSubstring => PatternMatchKind.CamelCaseSubstring,
NavigateToMatchKind.CamelCaseNonContiguousSubstring => PatternMatchKind.CamelCaseNonContiguousSubstring,
NavigateToMatchKind.Fuzzy => PatternMatchKind.Fuzzy,
_ => throw ExceptionUtilities.UnexpectedValue(matchKind),
};
/// <summary>
/// Returns the name for the language used by the old Navigate To providers.
/// </summary>
/// <remarks> It turns out this string is used for sorting and for some SQM data, so it's best
/// to keep it unchanged.</remarks>
private static string GetNavigateToLanguage(string languageName)
=> languageName switch
{
LanguageNames.CSharp => "csharp",
LanguageNames.VisualBasic => "vb",
_ => languageName,
};
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.NavigateTo;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Microsoft.VisualStudio.Text.PatternMatching;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
internal partial class NavigateToItemProvider
{
private class NavigateToItemProviderCallback : INavigateToSearchCallback
{
private readonly INavigateToItemDisplayFactory _displayFactory;
private readonly INavigateToCallback _callback;
public NavigateToItemProviderCallback(INavigateToItemDisplayFactory displayFactory, INavigateToCallback callback)
{
_displayFactory = displayFactory;
_callback = callback;
}
public void Done(bool isFullyLoaded)
{
if (!isFullyLoaded && _callback is INavigateToCallback2 callback2)
{
callback2.Done(IncompleteReason.SolutionLoading);
}
else
{
_callback.Done();
}
}
public Task AddItemAsync(Project project, INavigateToSearchResult result, CancellationToken cancellationToken)
{
ReportMatchResult(project, result);
return Task.CompletedTask;
}
public void ReportProgress(int current, int maximum)
{
_callback.ReportProgress(current, maximum);
}
private void ReportMatchResult(Project project, INavigateToSearchResult result)
{
var matchedSpans = result.NameMatchSpans.SelectAsArray(t => t.ToSpan());
var patternMatch = new PatternMatch(
GetPatternMatchKind(result.MatchKind),
punctuationStripped: false,
result.IsCaseSensitive,
matchedSpans);
var navigateToItem = new NavigateToItem(
result.Name,
result.Kind,
GetNavigateToLanguage(project.Language),
result.SecondarySort,
result,
patternMatch,
_displayFactory);
_callback.AddItem(navigateToItem);
}
private static PatternMatchKind GetPatternMatchKind(NavigateToMatchKind matchKind)
=> matchKind switch
{
NavigateToMatchKind.Exact => PatternMatchKind.Exact,
NavigateToMatchKind.Prefix => PatternMatchKind.Prefix,
NavigateToMatchKind.Substring => PatternMatchKind.Substring,
NavigateToMatchKind.Regular => PatternMatchKind.Fuzzy,
NavigateToMatchKind.None => PatternMatchKind.Fuzzy,
NavigateToMatchKind.CamelCaseExact => PatternMatchKind.CamelCaseExact,
NavigateToMatchKind.CamelCasePrefix => PatternMatchKind.CamelCasePrefix,
NavigateToMatchKind.CamelCaseNonContiguousPrefix => PatternMatchKind.CamelCaseNonContiguousPrefix,
NavigateToMatchKind.CamelCaseSubstring => PatternMatchKind.CamelCaseSubstring,
NavigateToMatchKind.CamelCaseNonContiguousSubstring => PatternMatchKind.CamelCaseNonContiguousSubstring,
NavigateToMatchKind.Fuzzy => PatternMatchKind.Fuzzy,
_ => throw ExceptionUtilities.UnexpectedValue(matchKind),
};
/// <summary>
/// Returns the name for the language used by the old Navigate To providers.
/// </summary>
/// <remarks> It turns out this string is used for sorting and for some SQM data, so it's best
/// to keep it unchanged.</remarks>
private static string GetNavigateToLanguage(string languageName)
=> languageName switch
{
LanguageNames.CSharp => "csharp",
LanguageNames.VisualBasic => "vb",
_ => languageName,
};
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/CSharp/Portable/Syntax/GenericNameSyntax.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.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class GenericNameSyntax
{
public bool IsUnboundGenericName
{
get
{
return this.TypeArgumentList.Arguments.Any(SyntaxKind.OmittedTypeArgument);
}
}
internal override string ErrorDisplayName()
{
var pb = PooledStringBuilder.GetInstance();
pb.Builder.Append(Identifier.ValueText).Append("<").Append(',', Arity - 1).Append(">");
return pb.ToStringAndFree();
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class GenericNameSyntax
{
public bool IsUnboundGenericName
{
get
{
return this.TypeArgumentList.Arguments.Any(SyntaxKind.OmittedTypeArgument);
}
}
internal override string ErrorDisplayName()
{
var pb = PooledStringBuilder.GetInstance();
pb.Builder.Append(Identifier.ValueText).Append("<").Append(',', Arity - 1).Append(">");
return pb.ToStringAndFree();
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/Core/CodeAnalysisTest/Text/StringTextTest.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.Text;
using Xunit;
using System.Text;
using System.IO;
using Roslyn.Test.Utilities;
using System.Security.Cryptography;
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UnitTests
{
/// <summary>
/// This is a test class for StringTextTest and is intended
/// to contain all StringTextTest Unit Tests
/// </summary>
public class StringTextTest
{
internal static string ChecksumToHexQuads(ImmutableArray<byte> checksum)
{
var builder = new StringBuilder();
for (int i = 0; i < checksum.Length; i++)
{
if (i > 0 && ((i % 4) == 0))
{
builder.Append(' ');
}
byte b = checksum[i];
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
[Fact]
public void FromString()
{
var data = SourceText.From("goo", Encoding.UTF8);
Assert.Equal(1, data.Lines.Count);
Assert.Equal(3, data.Lines[0].Span.Length);
}
[Fact]
public void FromString_DefaultEncoding()
{
var data = SourceText.From("goo");
Assert.Null(data.Encoding);
}
[Fact]
public void FromStringEmpty()
{
var data = SourceText.From(string.Empty);
Assert.Equal(1, data.Lines.Count);
Assert.Equal(0, data.Lines[0].Span.Length);
}
[Fact]
public void FromString_Errors()
{
Assert.Throws<ArgumentNullException>(() => SourceText.From((string)null, Encoding.UTF8));
}
[Fact]
public void FromStream_Errors()
{
Assert.Throws<ArgumentNullException>(() => SourceText.From((Stream)null, Encoding.UTF8));
Assert.Throws<ArgumentException>(() => SourceText.From(new TestStream(canRead: false, canSeek: true), Encoding.UTF8));
Assert.Throws<NotImplementedException>(() => SourceText.From(new TestStream(canRead: true, canSeek: false), Encoding.UTF8));
}
[Fact]
public void Indexer1()
{
var data = SourceText.From(string.Empty, Encoding.UTF8);
Assert.Throws<IndexOutOfRangeException>(
() => { var value = data[-1]; });
}
private void CheckEqualLine(TextLine first, TextLine second)
{
Assert.Equal(first, second);
#if false
// We do not guarantee either identity or Equals!
Assert.Equal(first.Extent, second.Extent);
Assert.Equal(first.ExtentIncludingLineBreak, second.ExtentIncludingLineBreak);
#endif
}
private void CheckNotEqualLine(TextLine first, TextLine second)
{
Assert.NotEqual(first, second);
#if false
Assert.NotEqual(first, second);
Assert.NotEqual(first.Extent, second.Extent);
Assert.NotEqual(first.ExtentIncludingLineBreak, second.ExtentIncludingLineBreak);
#endif
}
private void CheckLine(SourceText text, int lineNumber, int start, int length, int newlineLength, string lineText)
{
var textLine = text.Lines[lineNumber];
Assert.Equal(start, textLine.Start);
Assert.Equal(start + length, textLine.End);
Assert.Equal(start + length + newlineLength, textLine.EndIncludingLineBreak);
Assert.Equal(start, textLine.Span.Start);
Assert.Equal(length, textLine.Span.Length);
Assert.Equal(start, textLine.SpanIncludingLineBreak.Start);
Assert.Equal(length + newlineLength, textLine.SpanIncludingLineBreak.Length);
Assert.Equal(lineNumber, textLine.LineNumber);
Assert.Equal(lineText, textLine.ToString());
Assert.Equal(text.ToString().Substring(start, length), textLine.ToString());
CheckEqualLine(textLine, text.Lines[lineNumber]);
for (int p = textLine.Start; p < textLine.EndIncludingLineBreak; ++p)
{
CheckEqualLine(textLine, text.Lines.GetLineFromPosition(p));
Assert.Equal(lineNumber, text.Lines.IndexOf(p));
Assert.Equal(lineNumber, text.Lines.GetLinePosition(p).Line);
Assert.Equal(p - start, text.Lines.GetLinePosition(p).Character);
}
if (start != 0)
{
CheckNotEqualLine(textLine, text.Lines.GetLineFromPosition(start - 1));
Assert.Equal(lineNumber - 1, text.Lines.IndexOf(start - 1));
Assert.Equal(lineNumber - 1, text.Lines.GetLinePosition(start - 1).Line);
}
int nextPosition = start + length + newlineLength;
if (nextPosition < text.Length)
{
CheckNotEqualLine(textLine, text.Lines.GetLineFromPosition(nextPosition));
Assert.Equal(lineNumber + 1, text.Lines.IndexOf(nextPosition));
Assert.Equal(lineNumber + 1, text.Lines.GetLinePosition(nextPosition).Line);
}
}
[Fact]
public void NewLines1()
{
string newLine = Environment.NewLine;
var data = SourceText.From("goo" + newLine + " bar");
Assert.Equal(2, data.Lines.Count);
CheckLine(data, lineNumber: 0, start: 0, length: 3, newlineLength: newLine.Length, lineText: "goo");
CheckLine(data, lineNumber: 1, start: 3 + newLine.Length, length: 4, newlineLength: 0, lineText: " bar");
}
[Fact]
public void NewLines2()
{
var text =
@"goo
bar
baz";
var data = SourceText.From(text);
Assert.Equal(3, data.Lines.Count);
var newlineLength = Environment.NewLine.Length;
CheckLine(data, lineNumber: 0, start: 0, length: 3, newlineLength: newlineLength, lineText: "goo");
CheckLine(data, lineNumber: 1, start: 3 + newlineLength, length: 3, newlineLength: newlineLength, lineText: "bar");
CheckLine(data, lineNumber: 2, start: 2 * (3 + newlineLength), length: 3, newlineLength: 0, lineText: "baz");
}
[Fact]
public void NewLines3()
{
var data = SourceText.From("goo\r\nbar");
Assert.Equal(2, data.Lines.Count);
CheckLine(data, lineNumber: 0, start: 0, length: 3, newlineLength: 2, lineText: "goo");
CheckLine(data, lineNumber: 1, start: 5, length: 3, newlineLength: 0, lineText: "bar");
}
[Fact]
public void NewLines4()
{
var data = SourceText.From("goo\n\rbar\u2028");
Assert.Equal(4, data.Lines.Count);
CheckLine(data, lineNumber: 0, start: 0, length: 3, newlineLength: 1, lineText: "goo");
CheckLine(data, lineNumber: 1, start: 4, length: 0, newlineLength: 1, lineText: "");
CheckLine(data, lineNumber: 2, start: 5, length: 3, newlineLength: 1, lineText: "bar");
CheckLine(data, lineNumber: 3, start: 9, length: 0, newlineLength: 0, lineText: "");
}
[Fact]
public void Empty()
{
var data = SourceText.From("");
Assert.Equal(1, data.Lines.Count);
CheckLine(data, lineNumber: 0, start: 0, length: 0, newlineLength: 0, lineText: "");
}
[Fact]
public void LinesGetText1()
{
var text =
@"goo
bar baz";
var data = SourceText.From(text);
Assert.Equal(2, data.Lines.Count);
Assert.Equal("goo", data.Lines[0].ToString());
Assert.Equal("bar baz", data.Lines[1].ToString());
}
[Fact]
public void LinesGetText2()
{
var text = "goo";
var data = SourceText.From(text);
Assert.Equal("goo", data.Lines[0].ToString());
}
[Fact]
public void CheckSum_Utf8_BOM()
{
var data = SourceText.From("The quick brown fox jumps over the lazy dog", Encoding.UTF8);
var checksum = data.GetChecksum();
Assert.Equal("88d3ed78 9b0bae8b ced8e348 91133516 b79ba9fb", ChecksumToHexQuads(checksum));
}
[Fact]
public void FromStream_CheckSum_BOM()
{
var bytes = new byte[] { 0xef, 0xbb, 0xbf, 0x61, 0x62, 0x63 };
var source = SourceText.From(new MemoryStream(bytes), Encoding.ASCII);
Assert.Equal("abc", source.ToString());
var checksum = source.GetChecksum();
AssertEx.Equal(CryptographicHashProvider.ComputeSha1(bytes), checksum);
}
[Fact]
public void FromStream_CheckSum_NoBOM()
{
// Note: The 0x95 is outside the ASCII range, so a question mark will
// be substituted in decoded text. Note, however, that the checksum
// should be derived from the original input.
var bytes = new byte[] { 0x61, 0x62, 0x95 };
var source = SourceText.From(new MemoryStream(bytes), Encoding.ASCII);
Assert.Equal("ab?", source.ToString());
var checksum = source.GetChecksum();
AssertEx.Equal(CryptographicHashProvider.ComputeSha1(bytes), checksum);
}
[Fact]
public void FromStream_CheckSum_DefaultEncoding()
{
var bytes = Encoding.UTF8.GetBytes("\u1234");
var source = SourceText.From(new MemoryStream(bytes));
Assert.Equal("\u1234", source.ToString());
var checksum = source.GetChecksum();
AssertEx.Equal(CryptographicHashProvider.ComputeSha1(bytes), checksum);
}
[Fact]
public void FromStream_CheckSum_SeekToBeginning()
{
var bytes = new byte[] { 0xef, 0xbb, 0xbf, 0x61, 0x62, 0x63 };
var stream = new MemoryStream(bytes);
stream.Seek(3, SeekOrigin.Begin);
var source = SourceText.From(stream, Encoding.ASCII);
Assert.Equal("abc", source.ToString());
var checksum = source.GetChecksum();
AssertEx.Equal(CryptographicHashProvider.ComputeSha1(bytes), checksum);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Text;
using Xunit;
using System.Text;
using System.IO;
using Roslyn.Test.Utilities;
using System.Security.Cryptography;
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UnitTests
{
/// <summary>
/// This is a test class for StringTextTest and is intended
/// to contain all StringTextTest Unit Tests
/// </summary>
public class StringTextTest
{
internal static string ChecksumToHexQuads(ImmutableArray<byte> checksum)
{
var builder = new StringBuilder();
for (int i = 0; i < checksum.Length; i++)
{
if (i > 0 && ((i % 4) == 0))
{
builder.Append(' ');
}
byte b = checksum[i];
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
[Fact]
public void FromString()
{
var data = SourceText.From("goo", Encoding.UTF8);
Assert.Equal(1, data.Lines.Count);
Assert.Equal(3, data.Lines[0].Span.Length);
}
[Fact]
public void FromString_DefaultEncoding()
{
var data = SourceText.From("goo");
Assert.Null(data.Encoding);
}
[Fact]
public void FromStringEmpty()
{
var data = SourceText.From(string.Empty);
Assert.Equal(1, data.Lines.Count);
Assert.Equal(0, data.Lines[0].Span.Length);
}
[Fact]
public void FromString_Errors()
{
Assert.Throws<ArgumentNullException>(() => SourceText.From((string)null, Encoding.UTF8));
}
[Fact]
public void FromStream_Errors()
{
Assert.Throws<ArgumentNullException>(() => SourceText.From((Stream)null, Encoding.UTF8));
Assert.Throws<ArgumentException>(() => SourceText.From(new TestStream(canRead: false, canSeek: true), Encoding.UTF8));
Assert.Throws<NotImplementedException>(() => SourceText.From(new TestStream(canRead: true, canSeek: false), Encoding.UTF8));
}
[Fact]
public void Indexer1()
{
var data = SourceText.From(string.Empty, Encoding.UTF8);
Assert.Throws<IndexOutOfRangeException>(
() => { var value = data[-1]; });
}
private void CheckEqualLine(TextLine first, TextLine second)
{
Assert.Equal(first, second);
#if false
// We do not guarantee either identity or Equals!
Assert.Equal(first.Extent, second.Extent);
Assert.Equal(first.ExtentIncludingLineBreak, second.ExtentIncludingLineBreak);
#endif
}
private void CheckNotEqualLine(TextLine first, TextLine second)
{
Assert.NotEqual(first, second);
#if false
Assert.NotEqual(first, second);
Assert.NotEqual(first.Extent, second.Extent);
Assert.NotEqual(first.ExtentIncludingLineBreak, second.ExtentIncludingLineBreak);
#endif
}
private void CheckLine(SourceText text, int lineNumber, int start, int length, int newlineLength, string lineText)
{
var textLine = text.Lines[lineNumber];
Assert.Equal(start, textLine.Start);
Assert.Equal(start + length, textLine.End);
Assert.Equal(start + length + newlineLength, textLine.EndIncludingLineBreak);
Assert.Equal(start, textLine.Span.Start);
Assert.Equal(length, textLine.Span.Length);
Assert.Equal(start, textLine.SpanIncludingLineBreak.Start);
Assert.Equal(length + newlineLength, textLine.SpanIncludingLineBreak.Length);
Assert.Equal(lineNumber, textLine.LineNumber);
Assert.Equal(lineText, textLine.ToString());
Assert.Equal(text.ToString().Substring(start, length), textLine.ToString());
CheckEqualLine(textLine, text.Lines[lineNumber]);
for (int p = textLine.Start; p < textLine.EndIncludingLineBreak; ++p)
{
CheckEqualLine(textLine, text.Lines.GetLineFromPosition(p));
Assert.Equal(lineNumber, text.Lines.IndexOf(p));
Assert.Equal(lineNumber, text.Lines.GetLinePosition(p).Line);
Assert.Equal(p - start, text.Lines.GetLinePosition(p).Character);
}
if (start != 0)
{
CheckNotEqualLine(textLine, text.Lines.GetLineFromPosition(start - 1));
Assert.Equal(lineNumber - 1, text.Lines.IndexOf(start - 1));
Assert.Equal(lineNumber - 1, text.Lines.GetLinePosition(start - 1).Line);
}
int nextPosition = start + length + newlineLength;
if (nextPosition < text.Length)
{
CheckNotEqualLine(textLine, text.Lines.GetLineFromPosition(nextPosition));
Assert.Equal(lineNumber + 1, text.Lines.IndexOf(nextPosition));
Assert.Equal(lineNumber + 1, text.Lines.GetLinePosition(nextPosition).Line);
}
}
[Fact]
public void NewLines1()
{
string newLine = Environment.NewLine;
var data = SourceText.From("goo" + newLine + " bar");
Assert.Equal(2, data.Lines.Count);
CheckLine(data, lineNumber: 0, start: 0, length: 3, newlineLength: newLine.Length, lineText: "goo");
CheckLine(data, lineNumber: 1, start: 3 + newLine.Length, length: 4, newlineLength: 0, lineText: " bar");
}
[Fact]
public void NewLines2()
{
var text =
@"goo
bar
baz";
var data = SourceText.From(text);
Assert.Equal(3, data.Lines.Count);
var newlineLength = Environment.NewLine.Length;
CheckLine(data, lineNumber: 0, start: 0, length: 3, newlineLength: newlineLength, lineText: "goo");
CheckLine(data, lineNumber: 1, start: 3 + newlineLength, length: 3, newlineLength: newlineLength, lineText: "bar");
CheckLine(data, lineNumber: 2, start: 2 * (3 + newlineLength), length: 3, newlineLength: 0, lineText: "baz");
}
[Fact]
public void NewLines3()
{
var data = SourceText.From("goo\r\nbar");
Assert.Equal(2, data.Lines.Count);
CheckLine(data, lineNumber: 0, start: 0, length: 3, newlineLength: 2, lineText: "goo");
CheckLine(data, lineNumber: 1, start: 5, length: 3, newlineLength: 0, lineText: "bar");
}
[Fact]
public void NewLines4()
{
var data = SourceText.From("goo\n\rbar\u2028");
Assert.Equal(4, data.Lines.Count);
CheckLine(data, lineNumber: 0, start: 0, length: 3, newlineLength: 1, lineText: "goo");
CheckLine(data, lineNumber: 1, start: 4, length: 0, newlineLength: 1, lineText: "");
CheckLine(data, lineNumber: 2, start: 5, length: 3, newlineLength: 1, lineText: "bar");
CheckLine(data, lineNumber: 3, start: 9, length: 0, newlineLength: 0, lineText: "");
}
[Fact]
public void Empty()
{
var data = SourceText.From("");
Assert.Equal(1, data.Lines.Count);
CheckLine(data, lineNumber: 0, start: 0, length: 0, newlineLength: 0, lineText: "");
}
[Fact]
public void LinesGetText1()
{
var text =
@"goo
bar baz";
var data = SourceText.From(text);
Assert.Equal(2, data.Lines.Count);
Assert.Equal("goo", data.Lines[0].ToString());
Assert.Equal("bar baz", data.Lines[1].ToString());
}
[Fact]
public void LinesGetText2()
{
var text = "goo";
var data = SourceText.From(text);
Assert.Equal("goo", data.Lines[0].ToString());
}
[Fact]
public void CheckSum_Utf8_BOM()
{
var data = SourceText.From("The quick brown fox jumps over the lazy dog", Encoding.UTF8);
var checksum = data.GetChecksum();
Assert.Equal("88d3ed78 9b0bae8b ced8e348 91133516 b79ba9fb", ChecksumToHexQuads(checksum));
}
[Fact]
public void FromStream_CheckSum_BOM()
{
var bytes = new byte[] { 0xef, 0xbb, 0xbf, 0x61, 0x62, 0x63 };
var source = SourceText.From(new MemoryStream(bytes), Encoding.ASCII);
Assert.Equal("abc", source.ToString());
var checksum = source.GetChecksum();
AssertEx.Equal(CryptographicHashProvider.ComputeSha1(bytes), checksum);
}
[Fact]
public void FromStream_CheckSum_NoBOM()
{
// Note: The 0x95 is outside the ASCII range, so a question mark will
// be substituted in decoded text. Note, however, that the checksum
// should be derived from the original input.
var bytes = new byte[] { 0x61, 0x62, 0x95 };
var source = SourceText.From(new MemoryStream(bytes), Encoding.ASCII);
Assert.Equal("ab?", source.ToString());
var checksum = source.GetChecksum();
AssertEx.Equal(CryptographicHashProvider.ComputeSha1(bytes), checksum);
}
[Fact]
public void FromStream_CheckSum_DefaultEncoding()
{
var bytes = Encoding.UTF8.GetBytes("\u1234");
var source = SourceText.From(new MemoryStream(bytes));
Assert.Equal("\u1234", source.ToString());
var checksum = source.GetChecksum();
AssertEx.Equal(CryptographicHashProvider.ComputeSha1(bytes), checksum);
}
[Fact]
public void FromStream_CheckSum_SeekToBeginning()
{
var bytes = new byte[] { 0xef, 0xbb, 0xbf, 0x61, 0x62, 0x63 };
var stream = new MemoryStream(bytes);
stream.Seek(3, SeekOrigin.Begin);
var source = SourceText.From(stream, Encoding.ASCII);
Assert.Equal("abc", source.ToString());
var checksum = source.GetChecksum();
AssertEx.Equal(CryptographicHashProvider.ComputeSha1(bytes), checksum);
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Tools/ExternalAccess/FSharp/Structure/IFSharpBlockStructureService.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 System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Structure
{
internal interface IFSharpBlockStructureService
{
Task<FSharpBlockStructure> GetBlockStructureAsync(Document document, 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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Structure
{
internal interface IFSharpBlockStructureService
{
Task<FSharpBlockStructure> GetBlockStructureAsync(Document document, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_FindReferences_Current.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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
// This file contains the current FindReferences APIs. The current APIs allow for OOP
// implementation and will defer to the oop server if it is available. If not, it will
// compute the results in process.
public static partial class SymbolFinder
{
internal static async Task FindReferencesAsync(
ISymbol symbol,
Solution solution,
IStreamingFindReferencesProgress progress,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference, cancellationToken))
{
if (SerializableSymbolAndProjectId.TryCreate(symbol, solution, cancellationToken, out var serializedSymbol))
{
var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false);
if (client != null)
{
// Create a callback that we can pass to the server process to hear about the
// results as it finds them. When we hear about results we'll forward them to
// the 'progress' parameter which will then update the UI.
var serverCallback = new FindReferencesServerCallback(solution, progress);
var documentIds = documents?.SelectAsArray(d => d.Id) ?? default;
await client.TryInvokeAsync<IRemoteSymbolFinderService>(
solution,
(service, solutionInfo, callbackId, cancellationToken) => service.FindReferencesAsync(solutionInfo, callbackId, serializedSymbol, documentIds, options, cancellationToken),
serverCallback,
cancellationToken).ConfigureAwait(false);
return;
}
}
// Couldn't effectively search in OOP. Perform the search in-proc.
await FindReferencesInCurrentProcessAsync(
symbol, solution, progress,
documents, options, cancellationToken).ConfigureAwait(false);
}
}
internal static Task FindReferencesInCurrentProcessAsync(
ISymbol symbol,
Solution solution,
IStreamingFindReferencesProgress progress,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var finders = ReferenceFinders.DefaultReferenceFinders;
progress ??= NoOpStreamingFindReferencesProgress.Instance;
var engine = new FindReferencesSearchEngine(
solution, documents, finders, progress, options);
return engine.FindReferencesAsync(symbol, 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
// This file contains the current FindReferences APIs. The current APIs allow for OOP
// implementation and will defer to the oop server if it is available. If not, it will
// compute the results in process.
public static partial class SymbolFinder
{
internal static async Task FindReferencesAsync(
ISymbol symbol,
Solution solution,
IStreamingFindReferencesProgress progress,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference, cancellationToken))
{
if (SerializableSymbolAndProjectId.TryCreate(symbol, solution, cancellationToken, out var serializedSymbol))
{
var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false);
if (client != null)
{
// Create a callback that we can pass to the server process to hear about the
// results as it finds them. When we hear about results we'll forward them to
// the 'progress' parameter which will then update the UI.
var serverCallback = new FindReferencesServerCallback(solution, progress);
var documentIds = documents?.SelectAsArray(d => d.Id) ?? default;
await client.TryInvokeAsync<IRemoteSymbolFinderService>(
solution,
(service, solutionInfo, callbackId, cancellationToken) => service.FindReferencesAsync(solutionInfo, callbackId, serializedSymbol, documentIds, options, cancellationToken),
serverCallback,
cancellationToken).ConfigureAwait(false);
return;
}
}
// Couldn't effectively search in OOP. Perform the search in-proc.
await FindReferencesInCurrentProcessAsync(
symbol, solution, progress,
documents, options, cancellationToken).ConfigureAwait(false);
}
}
internal static Task FindReferencesInCurrentProcessAsync(
ISymbol symbol,
Solution solution,
IStreamingFindReferencesProgress progress,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var finders = ReferenceFinders.DefaultReferenceFinders;
progress ??= NoOpStreamingFindReferencesProgress.Instance;
var engine = new FindReferencesSearchEngine(
solution, documents, finders, progress, options);
return engine.FindReferencesAsync(symbol, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.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 System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Symbol
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' Changes to the public interface of this class should remain synchronized with the C# version of Symbol.
' Do not make any changes to the public interface without making the corresponding change
' to the C# version.
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
''' <summary>
''' Gets the attributes on this symbol. Returns an empty ImmutableArray if there are
''' no attributes.
''' </summary>
Public Overridable Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Return ImmutableArray(Of VisualBasicAttributeData).Empty
End Function
''' <summary>
''' Build and add synthesized attributes for this symbol.
''' </summary>
Friend Overridable Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
End Sub
''' <summary>
''' Convenience helper called by subclasses to add a synthesized attribute to a collection of attributes.
''' </summary>
Friend Shared Sub AddSynthesizedAttribute(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData), attribute As SynthesizedAttributeData)
If attribute IsNot Nothing Then
If attributes Is Nothing Then
attributes = ArrayBuilder(Of SynthesizedAttributeData).GetInstance(4)
End If
attributes.Add(attribute)
End If
End Sub
''' <summary>
''' Returns the appropriate AttributeTarget for a symbol. This is used to validate attribute usage when
''' applying an attribute to a symbol. For any symbol that does not support the application of custom
''' attributes 0 is returned.
''' </summary>
''' <returns>The attribute target flag for this symbol or 0 if none apply.</returns>
''' <remarks></remarks>
Friend Function GetAttributeTarget() As AttributeTargets
Select Case Kind
Case SymbolKind.Assembly
Return AttributeTargets.Assembly
Case SymbolKind.Event
Return AttributeTargets.Event
Case SymbolKind.Field
Return AttributeTargets.Field
Case SymbolKind.Method
Dim method = DirectCast(Me, MethodSymbol)
Select Case method.MethodKind
Case MethodKind.Constructor,
MethodKind.SharedConstructor
Return AttributeTargets.Constructor
Case MethodKind.Ordinary,
MethodKind.DeclareMethod,
MethodKind.UserDefinedOperator,
MethodKind.Conversion,
MethodKind.PropertyGet,
MethodKind.PropertySet,
MethodKind.EventAdd,
MethodKind.EventRaise,
MethodKind.EventRemove,
MethodKind.DelegateInvoke
Return AttributeTargets.Method
End Select
Case SymbolKind.Property
Return AttributeTargets.Property
Case SymbolKind.NamedType
Dim namedType = DirectCast(Me, NamedTypeSymbol)
Select Case namedType.TypeKind
Case TypeKind.Class,
TypeKind.Module
Return AttributeTargets.Class
Case TypeKind.Structure
Return AttributeTargets.Struct
Case TypeKind.Interface
Return AttributeTargets.Interface
Case TypeKind.Enum
Return AttributeTargets.Enum Or AttributeTargets.Struct
Case TypeKind.Delegate
Return AttributeTargets.Delegate
Case TypeKind.Submission
' attributes can't be applied on a submission type
Throw ExceptionUtilities.UnexpectedValue(namedType.TypeKind)
End Select
Case SymbolKind.NetModule
Return AttributeTargets.Module
Case SymbolKind.Parameter
Return AttributeTargets.Parameter
Case SymbolKind.TypeParameter
Return AttributeTargets.GenericParameter
End Select
Return 0
End Function
''' <summary>
''' Method to early decode applied well-known attribute which can be queried by the binder.
''' This method is called during attribute binding after we have bound the attribute types for all attributes,
''' but haven't yet bound the attribute arguments/attribute constructor.
''' Early decoding certain well-known attributes enables the binder to use this decoded information on this symbol
''' when binding the attribute arguments/attribute constructor without causing attribute binding cycle.
''' </summary>
Friend Overridable Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData
Return Nothing
End Function
Friend Function EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(
ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation),
<Out> ByRef boundAttribute As VisualBasicAttributeData,
<Out> ByRef obsoleteData As ObsoleteAttributeData
) As Boolean
Dim type = arguments.AttributeType
Dim syntax = arguments.AttributeSyntax
Dim kind As ObsoleteAttributeKind
If VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.ObsoleteAttribute) Then
kind = ObsoleteAttributeKind.Obsolete
ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.DeprecatedAttribute) Then
kind = ObsoleteAttributeKind.Deprecated
ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.ExperimentalAttribute) Then
kind = ObsoleteAttributeKind.Experimental
Else
boundAttribute = Nothing
obsoleteData = Nothing
Return False
End If
Dim hasAnyDiagnostics As Boolean = False
boundAttribute = arguments.Binder.GetAttribute(syntax, type, hasAnyDiagnostics)
If Not boundAttribute.HasErrors Then
obsoleteData = boundAttribute.DecodeObsoleteAttribute(kind)
If hasAnyDiagnostics Then
boundAttribute = Nothing
End If
Else
obsoleteData = Nothing
boundAttribute = Nothing
End If
Return True
End Function
''' <summary>
''' This method is called by the binder when it is finished binding a set of attributes on the symbol so that
''' the symbol can extract data from the attribute arguments and potentially perform validation specific to
''' some well known attributes.
''' </summary>
''' <remarks>
''' <para>
''' Symbol types should override this if they want to handle a specific well-known attribute.
''' If the attribute is of a type that the symbol does not wish to handle, it should delegate back to
''' this (base) method.
''' </para>
''' </remarks>
Friend Overridable Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation))
Dim compilation = Me.DeclaringCompilation
MarkEmbeddedAttributeTypeReference(arguments.Attribute, arguments.AttributeSyntaxOpt, compilation)
ReportExtensionAttributeUseSiteInfo(arguments.Attribute, arguments.AttributeSyntaxOpt, compilation, DirectCast(arguments.Diagnostics, BindingDiagnosticBag))
If arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.SkipLocalsInitAttribute) Then
DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.WRN_AttributeNotSupportedInVB, arguments.AttributeSyntaxOpt.Location, AttributeDescription.SkipLocalsInitAttribute.FullName)
End If
End Sub
''' <summary>
''' Called to report attribute related diagnostics after all attributes have been bound and decoded.
''' Called even if there are no attributes.
''' </summary>
''' <remarks>
''' This method is called by the binder from <see cref="LoadAndValidateAttributes"/> after it has finished binding attributes on the symbol,
''' has executed <see cref="DecodeWellKnownAttribute"/> for attributes applied on the symbol and has stored the decoded data in the
''' lazyCustomAttributesBag on the symbol. Bound attributes haven't been stored on the bag yet.
'''
''' Post-validation for attributes that is dependent on other attributes can be done here.
'''
''' This method should not have any side effects on the symbol, i.e. it SHOULD NOT change the symbol state.
''' </remarks>
''' <param name="boundAttributes">Bound attributes.</param>
''' <param name="allAttributeSyntaxNodes">Syntax nodes of attributes in order they are specified in source.</param>
''' <param name="diagnostics">Diagnostic bag.</param>
''' <param name="symbolPart">Specific part of the symbol to which the attributes apply, or <see cref="AttributeLocation.None"/> if the attributes apply to the symbol itself.</param>
''' <param name="decodedData">Decoded well known attribute data.</param>
Friend Overridable Sub PostDecodeWellKnownAttributes(boundAttributes As ImmutableArray(Of VisualBasicAttributeData),
allAttributeSyntaxNodes As ImmutableArray(Of AttributeSyntax),
diagnostics As BindingDiagnosticBag,
symbolPart As AttributeLocation,
decodedData As WellKnownAttributeData)
End Sub
''' <summary>
''' This method does the following set of operations in the specified order:
''' (1) GetAttributesToBind: Merge the given attributeBlockSyntaxList into a single list of attributes to bind.
''' (2) GetAttributes: Bind the attributes (attribute type, arguments and constructor).
''' (3) DecodeWellKnownAttributes: Decode and validate bound well-known attributes.
''' (4) ValidateAttributes: Perform some additional attribute validations, such as
''' 1) Duplicate attributes,
''' 2) Attribute usage target validation, etc.
''' (5) Store the bound attributes and decoded well-known attribute data in lazyCustomAttributesBag in a thread safe manner.
''' </summary>
Friend Sub LoadAndValidateAttributes(attributeBlockSyntaxList As OneOrMany(Of SyntaxList(Of AttributeListSyntax)),
ByRef lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData),
Optional symbolPart As AttributeLocation = 0)
Dim diagnostics = BindingDiagnosticBag.GetInstance()
Dim sourceAssembly = DirectCast(If(Me.Kind = SymbolKind.Assembly, Me, Me.ContainingAssembly), SourceAssemblySymbol)
Dim sourceModule = sourceAssembly.SourceModule
Dim compilation = sourceAssembly.DeclaringCompilation
Dim binders As ImmutableArray(Of Binder) = Nothing
Dim attributesToBind = GetAttributesToBind(attributeBlockSyntaxList, symbolPart, compilation, binders)
Dim boundAttributes As ImmutableArray(Of VisualBasicAttributeData)
Dim wellKnownAttrData As WellKnownAttributeData
If attributesToBind.Any() Then
Debug.Assert(attributesToBind.Any())
Debug.Assert(binders.Any())
Debug.Assert(attributesToBind.Length = binders.Length)
' Initialize the bag so that data decoded from early attributes can be stored onto it.
If (lazyCustomAttributesBag Is Nothing) Then
Interlocked.CompareExchange(lazyCustomAttributesBag, New CustomAttributesBag(Of VisualBasicAttributeData)(), Nothing)
End If
Dim boundAttributeTypes As ImmutableArray(Of NamedTypeSymbol) = Binder.BindAttributeTypes(binders, attributesToBind, Me, diagnostics)
Dim attributeBuilder = New VisualBasicAttributeData(boundAttributeTypes.Length - 1) {}
' Early bind and decode some well-known attributes.
Dim earlyData As EarlyWellKnownAttributeData = Me.EarlyDecodeWellKnownAttributes(binders, boundAttributeTypes, attributesToBind, attributeBuilder, symbolPart)
' Store data decoded from early bound well-known attributes.
lazyCustomAttributesBag.SetEarlyDecodedWellKnownAttributeData(earlyData)
' Bind attributes.
Binder.GetAttributes(binders, attributesToBind, boundAttributeTypes, attributeBuilder, Me, diagnostics)
boundAttributes = attributeBuilder.AsImmutableOrNull
' Validate attribute usage and Decode remaining well-known attributes.
wellKnownAttrData = Me.ValidateAttributeUsageAndDecodeWellKnownAttributes(binders, attributesToBind, boundAttributes, diagnostics, symbolPart)
' Store data decoded from remaining well-known attributes.
lazyCustomAttributesBag.SetDecodedWellKnownAttributeData(wellKnownAttrData)
Else
boundAttributes = ImmutableArray(Of VisualBasicAttributeData).Empty
wellKnownAttrData = Nothing
Interlocked.CompareExchange(lazyCustomAttributesBag, CustomAttributesBag(Of VisualBasicAttributeData).WithEmptyData(), Nothing)
End If
Me.PostDecodeWellKnownAttributes(boundAttributes, attributesToBind, diagnostics, symbolPart, wellKnownAttrData)
' Store attributes into the bag.
sourceModule.AtomicStoreAttributesAndDiagnostics(lazyCustomAttributesBag, boundAttributes, diagnostics)
diagnostics.Free()
Debug.Assert(lazyCustomAttributesBag.IsSealed)
End Sub
Private Function GetAttributesToBind(attributeDeclarationSyntaxLists As OneOrMany(Of SyntaxList(Of AttributeListSyntax)),
symbolPart As AttributeLocation,
compilation As VisualBasicCompilation,
<Out> ByRef binders As ImmutableArray(Of Binder)) As ImmutableArray(Of AttributeSyntax)
Dim attributeTarget = DirectCast(Me, IAttributeTargetSymbol)
Dim sourceModule = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim syntaxBuilder As ArrayBuilder(Of AttributeSyntax) = Nothing
Dim bindersBuilder As ArrayBuilder(Of Binder) = Nothing
Dim attributesToBindCount As Integer = 0
For listIndex = 0 To attributeDeclarationSyntaxLists.Count - 1
Dim attributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) = attributeDeclarationSyntaxLists(listIndex)
If attributeDeclarationSyntaxList.Any() Then
Dim prevCount As Integer = attributesToBindCount
For Each attributeDeclarationSyntax In attributeDeclarationSyntaxList
For Each attributeSyntax In attributeDeclarationSyntax.Attributes
If MatchAttributeTarget(attributeTarget, symbolPart, attributeSyntax.Target) Then
If syntaxBuilder Is Nothing Then
syntaxBuilder = New ArrayBuilder(Of AttributeSyntax)()
bindersBuilder = New ArrayBuilder(Of Binder)()
End If
syntaxBuilder.Add(attributeSyntax)
attributesToBindCount += 1
End If
Next
Next
If attributesToBindCount <> prevCount Then
Debug.Assert(attributeDeclarationSyntaxList.Node IsNot Nothing)
Debug.Assert(bindersBuilder IsNot Nothing)
Dim binder = GetAttributeBinder(attributeDeclarationSyntaxList, sourceModule)
For i = 0 To attributesToBindCount - prevCount - 1
bindersBuilder.Add(binder)
Next
End If
End If
Next
If syntaxBuilder IsNot Nothing Then
binders = bindersBuilder.ToImmutableAndFree()
Return syntaxBuilder.ToImmutableAndFree()
Else
binders = ImmutableArray(Of Binder).Empty
Return ImmutableArray(Of AttributeSyntax).Empty
End If
End Function
Friend Function GetAttributeBinder(syntaxList As SyntaxList(Of AttributeListSyntax), sourceModule As SourceModuleSymbol) As Binder
Dim syntaxTree = syntaxList.Node.SyntaxTree
Dim parent = syntaxList.Node.Parent
If parent.IsKind(SyntaxKind.AttributesStatement) AndAlso parent.Parent.IsKind(SyntaxKind.CompilationUnit) Then
' Create a binder for the file-level attributes. To avoid infinite recursion, the bound file information
' must be fully computed prior to trying to bind the file attributes.
Return BinderBuilder.CreateBinderForProjectLevelNamespace(sourceModule, syntaxTree)
Else
Return BinderBuilder.CreateBinderForAttribute(sourceModule, syntaxTree, Me)
End If
End Function
Private Shared Function MatchAttributeTarget(attributeTarget As IAttributeTargetSymbol, symbolPart As AttributeLocation, targetOpt As AttributeTargetSyntax) As Boolean
If targetOpt Is Nothing Then
Return True
End If
Dim explicitTarget As AttributeLocation
' Parser ensures that an error is reported for anything other than "assembly" or
' "module". Only assembly and module keywords can get here.
Select Case targetOpt.AttributeModifier.Kind
Case SyntaxKind.AssemblyKeyword
explicitTarget = AttributeLocation.Assembly
Case SyntaxKind.ModuleKeyword
explicitTarget = AttributeLocation.Module
Case Else
Throw ExceptionUtilities.UnexpectedValue(targetOpt.AttributeModifier.Kind)
End Select
If symbolPart = 0 Then
Return explicitTarget = attributeTarget.DefaultAttributeLocation
Else
Return explicitTarget = symbolPart
End If
End Function
Private Shared Function GetAttributesToBind(attributeBlockSyntaxList As SyntaxList(Of AttributeListSyntax)) As ImmutableArray(Of AttributeSyntax)
Dim attributeSyntaxBuilder As ArrayBuilder(Of AttributeSyntax) = Nothing
GetAttributesToBind(attributeBlockSyntaxList, attributeSyntaxBuilder)
Return If(attributeSyntaxBuilder IsNot Nothing, attributeSyntaxBuilder.ToImmutableAndFree(), ImmutableArray(Of AttributeSyntax).Empty)
End Function
Friend Shared Sub GetAttributesToBind(attributeBlockSyntaxList As SyntaxList(Of AttributeListSyntax), ByRef attributeSyntaxBuilder As ArrayBuilder(Of AttributeSyntax))
If attributeBlockSyntaxList.Count > 0 Then
If attributeSyntaxBuilder Is Nothing Then
attributeSyntaxBuilder = ArrayBuilder(Of AttributeSyntax).GetInstance()
End If
For Each attributeBlock In attributeBlockSyntaxList
attributeSyntaxBuilder.AddRange(attributeBlock.Attributes)
Next
End If
End Sub
''' <summary>
''' Method to early decode certain well-known attributes which can be queried by the binder.
''' This method is called during attribute binding after we have bound the attribute types for all attributes,
''' but haven't yet bound the attribute arguments/attribute constructor.
''' Early decoding certain well-known attributes enables the binder to use this decoded information on this symbol
''' when binding the attribute arguments/attribute constructor without causing attribute binding cycle.
''' </summary>
Private Function EarlyDecodeWellKnownAttributes(binders As ImmutableArray(Of Binder),
boundAttributeTypes As ImmutableArray(Of NamedTypeSymbol),
attributesToBind As ImmutableArray(Of AttributeSyntax),
attributeBuilder As VisualBasicAttributeData(),
symbolPart As AttributeLocation) As EarlyWellKnownAttributeData
Debug.Assert(boundAttributeTypes.Any())
Debug.Assert(attributesToBind.Any())
Dim arguments = New EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)()
arguments.SymbolPart = symbolPart
For i = 0 To boundAttributeTypes.Length - 1
Dim attributeType As NamedTypeSymbol = boundAttributeTypes(i)
If Not attributeType.IsErrorType() Then
arguments.Binder = New EarlyWellKnownAttributeBinder(Me, binders(i))
arguments.AttributeType = attributeType
arguments.AttributeSyntax = attributesToBind(i)
attributeBuilder(i) = Me.EarlyDecodeWellKnownAttribute(arguments)
End If
Next
Return If(arguments.HasDecodedData, arguments.DecodedData, Nothing)
End Function
''' <summary>
''' This method validates attribute usage for each bound attribute and calls <see cref="DecodeWellKnownAttribute"/>
''' on attributes with valid attribute usage.
''' This method is called by the binder when it is finished binding a set of attributes on the symbol so that
''' the symbol can extract data from the attribute arguments and potentially perform validation specific to
''' some well known attributes.
''' </summary>
Friend Function ValidateAttributeUsageAndDecodeWellKnownAttributes(
binders As ImmutableArray(Of Binder),
attributeSyntaxList As ImmutableArray(Of AttributeSyntax),
boundAttributes As ImmutableArray(Of VisualBasicAttributeData),
diagnostics As BindingDiagnosticBag,
symbolPart As AttributeLocation) As WellKnownAttributeData
Debug.Assert(binders.Any())
Debug.Assert(attributeSyntaxList.Any())
Debug.Assert(boundAttributes.Any())
Debug.Assert(binders.Length = boundAttributes.Length)
Debug.Assert(attributeSyntaxList.Length = boundAttributes.Length)
Dim totalAttributesCount As Integer = boundAttributes.Length
Dim uniqueAttributeTypes = New HashSet(Of NamedTypeSymbol)
Dim arguments = New DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)()
arguments.AttributesCount = totalAttributesCount
arguments.Diagnostics = diagnostics
arguments.SymbolPart = symbolPart
For i = 0 To totalAttributesCount - 1
Dim boundAttribute As VisualBasicAttributeData = boundAttributes(i)
Dim attributeSyntax As AttributeSyntax = attributeSyntaxList(i)
Dim binder As Binder = binders(i)
If Not boundAttribute.HasErrors AndAlso ValidateAttributeUsage(boundAttribute, attributeSyntax, binder.Compilation, symbolPart, diagnostics, uniqueAttributeTypes) Then
arguments.Attribute = boundAttribute
arguments.AttributeSyntaxOpt = attributeSyntax
arguments.Index = i
Me.DecodeWellKnownAttribute(arguments)
End If
Next
Return If(arguments.HasDecodedData, arguments.DecodedData, Nothing)
End Function
''' <summary>
''' Validate attribute usage target and duplicate attributes.
''' </summary>
''' <param name="attribute">Bound attribute</param>
''' <param name="node">Syntax node for attribute specification</param>
''' <param name="compilation">Compilation</param>
''' <param name="symbolPart">Symbol part to which the attribute has been applied</param>
''' <param name="diagnostics">Diagnostics</param>
''' <param name="uniqueAttributeTypes">Set of unique attribute types applied to the symbol</param>
Private Function ValidateAttributeUsage(
attribute As VisualBasicAttributeData,
node As AttributeSyntax,
compilation As VisualBasicCompilation,
symbolPart As AttributeLocation,
diagnostics As BindingDiagnosticBag,
uniqueAttributeTypes As HashSet(Of NamedTypeSymbol)) As Boolean
Dim attributeType As NamedTypeSymbol = attribute.AttributeClass
Debug.Assert(attributeType IsNot Nothing)
Debug.Assert(Not attributeType.IsErrorType())
Debug.Assert(attributeType.IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, compilation, CompoundUseSiteInfo(Of AssemblySymbol).Discarded))
' Get attribute usage for this attribute
Dim attributeUsage As AttributeUsageInfo = attributeType.GetAttributeUsageInfo()
Debug.Assert(Not attributeUsage.IsNull)
' check if this attribute was used multiple times and attributeUsage.AllowMultiple is False.
If Not uniqueAttributeTypes.Add(attributeType) AndAlso Not attributeUsage.AllowMultiple Then
diagnostics.Add(ERRID.ERR_InvalidMultipleAttributeUsage1, node.GetLocation(), CustomSymbolDisplayFormatter.ShortErrorName(attributeType))
Return False
End If
Dim attributeTarget As AttributeTargets
If symbolPart = AttributeLocation.Return Then
Debug.Assert(Me.Kind = SymbolKind.Method OrElse Me.Kind = SymbolKind.Property)
attributeTarget = AttributeTargets.ReturnValue
Else
attributeTarget = Me.GetAttributeTarget()
End If
' VB allows NonSerialized on events even though the NonSerialized does not have this attribute usage specified.
' See Dev 10 Bindable::VerifyCustomAttributesOnSymbol
Dim applicationIsValid As Boolean
If attributeType Is compilation.GetWellKnownType(WellKnownType.System_NonSerializedAttribute) AndAlso
Me.Kind = SymbolKind.Event AndAlso DirectCast(Me, SourceEventSymbol).AssociatedField IsNot Nothing Then
applicationIsValid = True
Else
Dim validOn = attributeUsage.ValidTargets
applicationIsValid = attributeTarget <> 0 AndAlso (validOn And attributeTarget) <> 0
End If
If Not applicationIsValid Then
Select Case attributeTarget
Case AttributeTargets.Assembly
diagnostics.Add(ERRID.ERR_InvalidAssemblyAttribute1, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType))
Case AttributeTargets.Module
diagnostics.Add(ERRID.ERR_InvalidModuleAttribute1, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType))
Case AttributeTargets.Method
If Me.Kind = SymbolKind.Method Then
Dim method = DirectCast(Me, SourceMethodSymbol)
Dim accessorName = TryGetAccessorDisplayName(method.MethodKind)
If accessorName IsNot Nothing Then
Debug.Assert(method.AssociatedSymbol IsNot Nothing)
diagnostics.Add(ERRID.ERR_InvalidAttributeUsageOnAccessor, node.Name.GetLocation,
CustomSymbolDisplayFormatter.ShortErrorName(attributeType), accessorName, CustomSymbolDisplayFormatter.ShortErrorName(method.AssociatedSymbol))
Exit Select
End If
End If
diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation,
CustomSymbolDisplayFormatter.ShortErrorName(attributeType), CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString())
Case AttributeTargets.Field
Dim withEventsBackingField = TryCast(Me, SourceWithEventsBackingFieldSymbol)
Dim ownerName As String
If withEventsBackingField IsNot Nothing Then
ownerName = CustomSymbolDisplayFormatter.ShortErrorName(withEventsBackingField.AssociatedSymbol).ToString()
Else
ownerName = CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString()
End If
diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), ownerName)
Case AttributeTargets.ReturnValue
diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType),
New LocalizableErrorArgument(ERRID.IDS_FunctionReturnType))
Case Else
diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType),
CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString())
End Select
Return False
End If
If attribute.IsSecurityAttribute(compilation) Then
Select Case Me.Kind
Case SymbolKind.Assembly, SymbolKind.NamedType, SymbolKind.Method
Exit Select
Case Else
' BC36979: Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.
diagnostics.Add(ERRID.ERR_SecurityAttributeInvalidTarget, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType))
Return False
End Select
End If
Return True
End Function
Private Sub ReportExtensionAttributeUseSiteInfo(attribute As VisualBasicAttributeData, nodeOpt As AttributeSyntax, compilation As VisualBasicCompilation, diagnostics As BindingDiagnosticBag)
' report issues with a custom extension attribute everywhere, where the attribute is used in source
' (we will not report in location where it's implicitly used (like the containing module or assembly of extension methods)
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing
If attribute.AttributeConstructor IsNot Nothing AndAlso
attribute.AttributeConstructor Is compilation.GetExtensionAttributeConstructor(useSiteInfo) Then
diagnostics.Add(useSiteInfo, If(nodeOpt IsNot Nothing, nodeOpt.GetLocation(), NoLocation.Singleton))
End If
End Sub
Private Sub MarkEmbeddedAttributeTypeReference(attribute As VisualBasicAttributeData, nodeOpt As AttributeSyntax, compilation As VisualBasicCompilation)
Debug.Assert(Not attribute.HasErrors)
' Mark embedded attribute type reference only if the owner is itself not
' embedded and the attribute syntax is actually from the current compilation.
If Not Me.IsEmbedded AndAlso
attribute.AttributeClass.IsEmbedded AndAlso
nodeOpt IsNot Nothing AndAlso
compilation.ContainsSyntaxTree(nodeOpt.SyntaxTree) Then
' Note that none of embedded symbols from referenced
' assemblies or compilations should be found/referenced.
Debug.Assert(attribute.AttributeClass.ContainingAssembly Is compilation.Assembly)
compilation.EmbeddedSymbolManager.MarkSymbolAsReferenced(attribute.AttributeClass)
End If
End Sub
''' <summary>
''' Ensure that attributes are bound and the ObsoleteState of this symbol is known.
''' </summary>
Friend Sub ForceCompleteObsoleteAttribute()
If Me.ObsoleteState = ThreeState.Unknown Then
Me.GetAttributes()
End If
Debug.Assert(Me.ObsoleteState <> ThreeState.Unknown, "ObsoleteState should be true or false now.")
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Symbol
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' Changes to the public interface of this class should remain synchronized with the C# version of Symbol.
' Do not make any changes to the public interface without making the corresponding change
' to the C# version.
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
''' <summary>
''' Gets the attributes on this symbol. Returns an empty ImmutableArray if there are
''' no attributes.
''' </summary>
Public Overridable Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Return ImmutableArray(Of VisualBasicAttributeData).Empty
End Function
''' <summary>
''' Build and add synthesized attributes for this symbol.
''' </summary>
Friend Overridable Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
End Sub
''' <summary>
''' Convenience helper called by subclasses to add a synthesized attribute to a collection of attributes.
''' </summary>
Friend Shared Sub AddSynthesizedAttribute(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData), attribute As SynthesizedAttributeData)
If attribute IsNot Nothing Then
If attributes Is Nothing Then
attributes = ArrayBuilder(Of SynthesizedAttributeData).GetInstance(4)
End If
attributes.Add(attribute)
End If
End Sub
''' <summary>
''' Returns the appropriate AttributeTarget for a symbol. This is used to validate attribute usage when
''' applying an attribute to a symbol. For any symbol that does not support the application of custom
''' attributes 0 is returned.
''' </summary>
''' <returns>The attribute target flag for this symbol or 0 if none apply.</returns>
''' <remarks></remarks>
Friend Function GetAttributeTarget() As AttributeTargets
Select Case Kind
Case SymbolKind.Assembly
Return AttributeTargets.Assembly
Case SymbolKind.Event
Return AttributeTargets.Event
Case SymbolKind.Field
Return AttributeTargets.Field
Case SymbolKind.Method
Dim method = DirectCast(Me, MethodSymbol)
Select Case method.MethodKind
Case MethodKind.Constructor,
MethodKind.SharedConstructor
Return AttributeTargets.Constructor
Case MethodKind.Ordinary,
MethodKind.DeclareMethod,
MethodKind.UserDefinedOperator,
MethodKind.Conversion,
MethodKind.PropertyGet,
MethodKind.PropertySet,
MethodKind.EventAdd,
MethodKind.EventRaise,
MethodKind.EventRemove,
MethodKind.DelegateInvoke
Return AttributeTargets.Method
End Select
Case SymbolKind.Property
Return AttributeTargets.Property
Case SymbolKind.NamedType
Dim namedType = DirectCast(Me, NamedTypeSymbol)
Select Case namedType.TypeKind
Case TypeKind.Class,
TypeKind.Module
Return AttributeTargets.Class
Case TypeKind.Structure
Return AttributeTargets.Struct
Case TypeKind.Interface
Return AttributeTargets.Interface
Case TypeKind.Enum
Return AttributeTargets.Enum Or AttributeTargets.Struct
Case TypeKind.Delegate
Return AttributeTargets.Delegate
Case TypeKind.Submission
' attributes can't be applied on a submission type
Throw ExceptionUtilities.UnexpectedValue(namedType.TypeKind)
End Select
Case SymbolKind.NetModule
Return AttributeTargets.Module
Case SymbolKind.Parameter
Return AttributeTargets.Parameter
Case SymbolKind.TypeParameter
Return AttributeTargets.GenericParameter
End Select
Return 0
End Function
''' <summary>
''' Method to early decode applied well-known attribute which can be queried by the binder.
''' This method is called during attribute binding after we have bound the attribute types for all attributes,
''' but haven't yet bound the attribute arguments/attribute constructor.
''' Early decoding certain well-known attributes enables the binder to use this decoded information on this symbol
''' when binding the attribute arguments/attribute constructor without causing attribute binding cycle.
''' </summary>
Friend Overridable Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData
Return Nothing
End Function
Friend Function EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(
ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation),
<Out> ByRef boundAttribute As VisualBasicAttributeData,
<Out> ByRef obsoleteData As ObsoleteAttributeData
) As Boolean
Dim type = arguments.AttributeType
Dim syntax = arguments.AttributeSyntax
Dim kind As ObsoleteAttributeKind
If VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.ObsoleteAttribute) Then
kind = ObsoleteAttributeKind.Obsolete
ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.DeprecatedAttribute) Then
kind = ObsoleteAttributeKind.Deprecated
ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.ExperimentalAttribute) Then
kind = ObsoleteAttributeKind.Experimental
Else
boundAttribute = Nothing
obsoleteData = Nothing
Return False
End If
Dim hasAnyDiagnostics As Boolean = False
boundAttribute = arguments.Binder.GetAttribute(syntax, type, hasAnyDiagnostics)
If Not boundAttribute.HasErrors Then
obsoleteData = boundAttribute.DecodeObsoleteAttribute(kind)
If hasAnyDiagnostics Then
boundAttribute = Nothing
End If
Else
obsoleteData = Nothing
boundAttribute = Nothing
End If
Return True
End Function
''' <summary>
''' This method is called by the binder when it is finished binding a set of attributes on the symbol so that
''' the symbol can extract data from the attribute arguments and potentially perform validation specific to
''' some well known attributes.
''' </summary>
''' <remarks>
''' <para>
''' Symbol types should override this if they want to handle a specific well-known attribute.
''' If the attribute is of a type that the symbol does not wish to handle, it should delegate back to
''' this (base) method.
''' </para>
''' </remarks>
Friend Overridable Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation))
Dim compilation = Me.DeclaringCompilation
MarkEmbeddedAttributeTypeReference(arguments.Attribute, arguments.AttributeSyntaxOpt, compilation)
ReportExtensionAttributeUseSiteInfo(arguments.Attribute, arguments.AttributeSyntaxOpt, compilation, DirectCast(arguments.Diagnostics, BindingDiagnosticBag))
If arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.SkipLocalsInitAttribute) Then
DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.WRN_AttributeNotSupportedInVB, arguments.AttributeSyntaxOpt.Location, AttributeDescription.SkipLocalsInitAttribute.FullName)
End If
End Sub
''' <summary>
''' Called to report attribute related diagnostics after all attributes have been bound and decoded.
''' Called even if there are no attributes.
''' </summary>
''' <remarks>
''' This method is called by the binder from <see cref="LoadAndValidateAttributes"/> after it has finished binding attributes on the symbol,
''' has executed <see cref="DecodeWellKnownAttribute"/> for attributes applied on the symbol and has stored the decoded data in the
''' lazyCustomAttributesBag on the symbol. Bound attributes haven't been stored on the bag yet.
'''
''' Post-validation for attributes that is dependent on other attributes can be done here.
'''
''' This method should not have any side effects on the symbol, i.e. it SHOULD NOT change the symbol state.
''' </remarks>
''' <param name="boundAttributes">Bound attributes.</param>
''' <param name="allAttributeSyntaxNodes">Syntax nodes of attributes in order they are specified in source.</param>
''' <param name="diagnostics">Diagnostic bag.</param>
''' <param name="symbolPart">Specific part of the symbol to which the attributes apply, or <see cref="AttributeLocation.None"/> if the attributes apply to the symbol itself.</param>
''' <param name="decodedData">Decoded well known attribute data.</param>
Friend Overridable Sub PostDecodeWellKnownAttributes(boundAttributes As ImmutableArray(Of VisualBasicAttributeData),
allAttributeSyntaxNodes As ImmutableArray(Of AttributeSyntax),
diagnostics As BindingDiagnosticBag,
symbolPart As AttributeLocation,
decodedData As WellKnownAttributeData)
End Sub
''' <summary>
''' This method does the following set of operations in the specified order:
''' (1) GetAttributesToBind: Merge the given attributeBlockSyntaxList into a single list of attributes to bind.
''' (2) GetAttributes: Bind the attributes (attribute type, arguments and constructor).
''' (3) DecodeWellKnownAttributes: Decode and validate bound well-known attributes.
''' (4) ValidateAttributes: Perform some additional attribute validations, such as
''' 1) Duplicate attributes,
''' 2) Attribute usage target validation, etc.
''' (5) Store the bound attributes and decoded well-known attribute data in lazyCustomAttributesBag in a thread safe manner.
''' </summary>
Friend Sub LoadAndValidateAttributes(attributeBlockSyntaxList As OneOrMany(Of SyntaxList(Of AttributeListSyntax)),
ByRef lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData),
Optional symbolPart As AttributeLocation = 0)
Dim diagnostics = BindingDiagnosticBag.GetInstance()
Dim sourceAssembly = DirectCast(If(Me.Kind = SymbolKind.Assembly, Me, Me.ContainingAssembly), SourceAssemblySymbol)
Dim sourceModule = sourceAssembly.SourceModule
Dim compilation = sourceAssembly.DeclaringCompilation
Dim binders As ImmutableArray(Of Binder) = Nothing
Dim attributesToBind = GetAttributesToBind(attributeBlockSyntaxList, symbolPart, compilation, binders)
Dim boundAttributes As ImmutableArray(Of VisualBasicAttributeData)
Dim wellKnownAttrData As WellKnownAttributeData
If attributesToBind.Any() Then
Debug.Assert(attributesToBind.Any())
Debug.Assert(binders.Any())
Debug.Assert(attributesToBind.Length = binders.Length)
' Initialize the bag so that data decoded from early attributes can be stored onto it.
If (lazyCustomAttributesBag Is Nothing) Then
Interlocked.CompareExchange(lazyCustomAttributesBag, New CustomAttributesBag(Of VisualBasicAttributeData)(), Nothing)
End If
Dim boundAttributeTypes As ImmutableArray(Of NamedTypeSymbol) = Binder.BindAttributeTypes(binders, attributesToBind, Me, diagnostics)
Dim attributeBuilder = New VisualBasicAttributeData(boundAttributeTypes.Length - 1) {}
' Early bind and decode some well-known attributes.
Dim earlyData As EarlyWellKnownAttributeData = Me.EarlyDecodeWellKnownAttributes(binders, boundAttributeTypes, attributesToBind, attributeBuilder, symbolPart)
' Store data decoded from early bound well-known attributes.
lazyCustomAttributesBag.SetEarlyDecodedWellKnownAttributeData(earlyData)
' Bind attributes.
Binder.GetAttributes(binders, attributesToBind, boundAttributeTypes, attributeBuilder, Me, diagnostics)
boundAttributes = attributeBuilder.AsImmutableOrNull
' Validate attribute usage and Decode remaining well-known attributes.
wellKnownAttrData = Me.ValidateAttributeUsageAndDecodeWellKnownAttributes(binders, attributesToBind, boundAttributes, diagnostics, symbolPart)
' Store data decoded from remaining well-known attributes.
lazyCustomAttributesBag.SetDecodedWellKnownAttributeData(wellKnownAttrData)
Else
boundAttributes = ImmutableArray(Of VisualBasicAttributeData).Empty
wellKnownAttrData = Nothing
Interlocked.CompareExchange(lazyCustomAttributesBag, CustomAttributesBag(Of VisualBasicAttributeData).WithEmptyData(), Nothing)
End If
Me.PostDecodeWellKnownAttributes(boundAttributes, attributesToBind, diagnostics, symbolPart, wellKnownAttrData)
' Store attributes into the bag.
sourceModule.AtomicStoreAttributesAndDiagnostics(lazyCustomAttributesBag, boundAttributes, diagnostics)
diagnostics.Free()
Debug.Assert(lazyCustomAttributesBag.IsSealed)
End Sub
Private Function GetAttributesToBind(attributeDeclarationSyntaxLists As OneOrMany(Of SyntaxList(Of AttributeListSyntax)),
symbolPart As AttributeLocation,
compilation As VisualBasicCompilation,
<Out> ByRef binders As ImmutableArray(Of Binder)) As ImmutableArray(Of AttributeSyntax)
Dim attributeTarget = DirectCast(Me, IAttributeTargetSymbol)
Dim sourceModule = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim syntaxBuilder As ArrayBuilder(Of AttributeSyntax) = Nothing
Dim bindersBuilder As ArrayBuilder(Of Binder) = Nothing
Dim attributesToBindCount As Integer = 0
For listIndex = 0 To attributeDeclarationSyntaxLists.Count - 1
Dim attributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) = attributeDeclarationSyntaxLists(listIndex)
If attributeDeclarationSyntaxList.Any() Then
Dim prevCount As Integer = attributesToBindCount
For Each attributeDeclarationSyntax In attributeDeclarationSyntaxList
For Each attributeSyntax In attributeDeclarationSyntax.Attributes
If MatchAttributeTarget(attributeTarget, symbolPart, attributeSyntax.Target) Then
If syntaxBuilder Is Nothing Then
syntaxBuilder = New ArrayBuilder(Of AttributeSyntax)()
bindersBuilder = New ArrayBuilder(Of Binder)()
End If
syntaxBuilder.Add(attributeSyntax)
attributesToBindCount += 1
End If
Next
Next
If attributesToBindCount <> prevCount Then
Debug.Assert(attributeDeclarationSyntaxList.Node IsNot Nothing)
Debug.Assert(bindersBuilder IsNot Nothing)
Dim binder = GetAttributeBinder(attributeDeclarationSyntaxList, sourceModule)
For i = 0 To attributesToBindCount - prevCount - 1
bindersBuilder.Add(binder)
Next
End If
End If
Next
If syntaxBuilder IsNot Nothing Then
binders = bindersBuilder.ToImmutableAndFree()
Return syntaxBuilder.ToImmutableAndFree()
Else
binders = ImmutableArray(Of Binder).Empty
Return ImmutableArray(Of AttributeSyntax).Empty
End If
End Function
Friend Function GetAttributeBinder(syntaxList As SyntaxList(Of AttributeListSyntax), sourceModule As SourceModuleSymbol) As Binder
Dim syntaxTree = syntaxList.Node.SyntaxTree
Dim parent = syntaxList.Node.Parent
If parent.IsKind(SyntaxKind.AttributesStatement) AndAlso parent.Parent.IsKind(SyntaxKind.CompilationUnit) Then
' Create a binder for the file-level attributes. To avoid infinite recursion, the bound file information
' must be fully computed prior to trying to bind the file attributes.
Return BinderBuilder.CreateBinderForProjectLevelNamespace(sourceModule, syntaxTree)
Else
Return BinderBuilder.CreateBinderForAttribute(sourceModule, syntaxTree, Me)
End If
End Function
Private Shared Function MatchAttributeTarget(attributeTarget As IAttributeTargetSymbol, symbolPart As AttributeLocation, targetOpt As AttributeTargetSyntax) As Boolean
If targetOpt Is Nothing Then
Return True
End If
Dim explicitTarget As AttributeLocation
' Parser ensures that an error is reported for anything other than "assembly" or
' "module". Only assembly and module keywords can get here.
Select Case targetOpt.AttributeModifier.Kind
Case SyntaxKind.AssemblyKeyword
explicitTarget = AttributeLocation.Assembly
Case SyntaxKind.ModuleKeyword
explicitTarget = AttributeLocation.Module
Case Else
Throw ExceptionUtilities.UnexpectedValue(targetOpt.AttributeModifier.Kind)
End Select
If symbolPart = 0 Then
Return explicitTarget = attributeTarget.DefaultAttributeLocation
Else
Return explicitTarget = symbolPart
End If
End Function
Private Shared Function GetAttributesToBind(attributeBlockSyntaxList As SyntaxList(Of AttributeListSyntax)) As ImmutableArray(Of AttributeSyntax)
Dim attributeSyntaxBuilder As ArrayBuilder(Of AttributeSyntax) = Nothing
GetAttributesToBind(attributeBlockSyntaxList, attributeSyntaxBuilder)
Return If(attributeSyntaxBuilder IsNot Nothing, attributeSyntaxBuilder.ToImmutableAndFree(), ImmutableArray(Of AttributeSyntax).Empty)
End Function
Friend Shared Sub GetAttributesToBind(attributeBlockSyntaxList As SyntaxList(Of AttributeListSyntax), ByRef attributeSyntaxBuilder As ArrayBuilder(Of AttributeSyntax))
If attributeBlockSyntaxList.Count > 0 Then
If attributeSyntaxBuilder Is Nothing Then
attributeSyntaxBuilder = ArrayBuilder(Of AttributeSyntax).GetInstance()
End If
For Each attributeBlock In attributeBlockSyntaxList
attributeSyntaxBuilder.AddRange(attributeBlock.Attributes)
Next
End If
End Sub
''' <summary>
''' Method to early decode certain well-known attributes which can be queried by the binder.
''' This method is called during attribute binding after we have bound the attribute types for all attributes,
''' but haven't yet bound the attribute arguments/attribute constructor.
''' Early decoding certain well-known attributes enables the binder to use this decoded information on this symbol
''' when binding the attribute arguments/attribute constructor without causing attribute binding cycle.
''' </summary>
Private Function EarlyDecodeWellKnownAttributes(binders As ImmutableArray(Of Binder),
boundAttributeTypes As ImmutableArray(Of NamedTypeSymbol),
attributesToBind As ImmutableArray(Of AttributeSyntax),
attributeBuilder As VisualBasicAttributeData(),
symbolPart As AttributeLocation) As EarlyWellKnownAttributeData
Debug.Assert(boundAttributeTypes.Any())
Debug.Assert(attributesToBind.Any())
Dim arguments = New EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)()
arguments.SymbolPart = symbolPart
For i = 0 To boundAttributeTypes.Length - 1
Dim attributeType As NamedTypeSymbol = boundAttributeTypes(i)
If Not attributeType.IsErrorType() Then
arguments.Binder = New EarlyWellKnownAttributeBinder(Me, binders(i))
arguments.AttributeType = attributeType
arguments.AttributeSyntax = attributesToBind(i)
attributeBuilder(i) = Me.EarlyDecodeWellKnownAttribute(arguments)
End If
Next
Return If(arguments.HasDecodedData, arguments.DecodedData, Nothing)
End Function
''' <summary>
''' This method validates attribute usage for each bound attribute and calls <see cref="DecodeWellKnownAttribute"/>
''' on attributes with valid attribute usage.
''' This method is called by the binder when it is finished binding a set of attributes on the symbol so that
''' the symbol can extract data from the attribute arguments and potentially perform validation specific to
''' some well known attributes.
''' </summary>
Friend Function ValidateAttributeUsageAndDecodeWellKnownAttributes(
binders As ImmutableArray(Of Binder),
attributeSyntaxList As ImmutableArray(Of AttributeSyntax),
boundAttributes As ImmutableArray(Of VisualBasicAttributeData),
diagnostics As BindingDiagnosticBag,
symbolPart As AttributeLocation) As WellKnownAttributeData
Debug.Assert(binders.Any())
Debug.Assert(attributeSyntaxList.Any())
Debug.Assert(boundAttributes.Any())
Debug.Assert(binders.Length = boundAttributes.Length)
Debug.Assert(attributeSyntaxList.Length = boundAttributes.Length)
Dim totalAttributesCount As Integer = boundAttributes.Length
Dim uniqueAttributeTypes = New HashSet(Of NamedTypeSymbol)
Dim arguments = New DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)()
arguments.AttributesCount = totalAttributesCount
arguments.Diagnostics = diagnostics
arguments.SymbolPart = symbolPart
For i = 0 To totalAttributesCount - 1
Dim boundAttribute As VisualBasicAttributeData = boundAttributes(i)
Dim attributeSyntax As AttributeSyntax = attributeSyntaxList(i)
Dim binder As Binder = binders(i)
If Not boundAttribute.HasErrors AndAlso ValidateAttributeUsage(boundAttribute, attributeSyntax, binder.Compilation, symbolPart, diagnostics, uniqueAttributeTypes) Then
arguments.Attribute = boundAttribute
arguments.AttributeSyntaxOpt = attributeSyntax
arguments.Index = i
Me.DecodeWellKnownAttribute(arguments)
End If
Next
Return If(arguments.HasDecodedData, arguments.DecodedData, Nothing)
End Function
''' <summary>
''' Validate attribute usage target and duplicate attributes.
''' </summary>
''' <param name="attribute">Bound attribute</param>
''' <param name="node">Syntax node for attribute specification</param>
''' <param name="compilation">Compilation</param>
''' <param name="symbolPart">Symbol part to which the attribute has been applied</param>
''' <param name="diagnostics">Diagnostics</param>
''' <param name="uniqueAttributeTypes">Set of unique attribute types applied to the symbol</param>
Private Function ValidateAttributeUsage(
attribute As VisualBasicAttributeData,
node As AttributeSyntax,
compilation As VisualBasicCompilation,
symbolPart As AttributeLocation,
diagnostics As BindingDiagnosticBag,
uniqueAttributeTypes As HashSet(Of NamedTypeSymbol)) As Boolean
Dim attributeType As NamedTypeSymbol = attribute.AttributeClass
Debug.Assert(attributeType IsNot Nothing)
Debug.Assert(Not attributeType.IsErrorType())
Debug.Assert(attributeType.IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, compilation, CompoundUseSiteInfo(Of AssemblySymbol).Discarded))
' Get attribute usage for this attribute
Dim attributeUsage As AttributeUsageInfo = attributeType.GetAttributeUsageInfo()
Debug.Assert(Not attributeUsage.IsNull)
' check if this attribute was used multiple times and attributeUsage.AllowMultiple is False.
If Not uniqueAttributeTypes.Add(attributeType) AndAlso Not attributeUsage.AllowMultiple Then
diagnostics.Add(ERRID.ERR_InvalidMultipleAttributeUsage1, node.GetLocation(), CustomSymbolDisplayFormatter.ShortErrorName(attributeType))
Return False
End If
Dim attributeTarget As AttributeTargets
If symbolPart = AttributeLocation.Return Then
Debug.Assert(Me.Kind = SymbolKind.Method OrElse Me.Kind = SymbolKind.Property)
attributeTarget = AttributeTargets.ReturnValue
Else
attributeTarget = Me.GetAttributeTarget()
End If
' VB allows NonSerialized on events even though the NonSerialized does not have this attribute usage specified.
' See Dev 10 Bindable::VerifyCustomAttributesOnSymbol
Dim applicationIsValid As Boolean
If attributeType Is compilation.GetWellKnownType(WellKnownType.System_NonSerializedAttribute) AndAlso
Me.Kind = SymbolKind.Event AndAlso DirectCast(Me, SourceEventSymbol).AssociatedField IsNot Nothing Then
applicationIsValid = True
Else
Dim validOn = attributeUsage.ValidTargets
applicationIsValid = attributeTarget <> 0 AndAlso (validOn And attributeTarget) <> 0
End If
If Not applicationIsValid Then
Select Case attributeTarget
Case AttributeTargets.Assembly
diagnostics.Add(ERRID.ERR_InvalidAssemblyAttribute1, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType))
Case AttributeTargets.Module
diagnostics.Add(ERRID.ERR_InvalidModuleAttribute1, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType))
Case AttributeTargets.Method
If Me.Kind = SymbolKind.Method Then
Dim method = DirectCast(Me, SourceMethodSymbol)
Dim accessorName = TryGetAccessorDisplayName(method.MethodKind)
If accessorName IsNot Nothing Then
Debug.Assert(method.AssociatedSymbol IsNot Nothing)
diagnostics.Add(ERRID.ERR_InvalidAttributeUsageOnAccessor, node.Name.GetLocation,
CustomSymbolDisplayFormatter.ShortErrorName(attributeType), accessorName, CustomSymbolDisplayFormatter.ShortErrorName(method.AssociatedSymbol))
Exit Select
End If
End If
diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation,
CustomSymbolDisplayFormatter.ShortErrorName(attributeType), CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString())
Case AttributeTargets.Field
Dim withEventsBackingField = TryCast(Me, SourceWithEventsBackingFieldSymbol)
Dim ownerName As String
If withEventsBackingField IsNot Nothing Then
ownerName = CustomSymbolDisplayFormatter.ShortErrorName(withEventsBackingField.AssociatedSymbol).ToString()
Else
ownerName = CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString()
End If
diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), ownerName)
Case AttributeTargets.ReturnValue
diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType),
New LocalizableErrorArgument(ERRID.IDS_FunctionReturnType))
Case Else
diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType),
CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString())
End Select
Return False
End If
If attribute.IsSecurityAttribute(compilation) Then
Select Case Me.Kind
Case SymbolKind.Assembly, SymbolKind.NamedType, SymbolKind.Method
Exit Select
Case Else
' BC36979: Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.
diagnostics.Add(ERRID.ERR_SecurityAttributeInvalidTarget, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType))
Return False
End Select
End If
Return True
End Function
Private Sub ReportExtensionAttributeUseSiteInfo(attribute As VisualBasicAttributeData, nodeOpt As AttributeSyntax, compilation As VisualBasicCompilation, diagnostics As BindingDiagnosticBag)
' report issues with a custom extension attribute everywhere, where the attribute is used in source
' (we will not report in location where it's implicitly used (like the containing module or assembly of extension methods)
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing
If attribute.AttributeConstructor IsNot Nothing AndAlso
attribute.AttributeConstructor Is compilation.GetExtensionAttributeConstructor(useSiteInfo) Then
diagnostics.Add(useSiteInfo, If(nodeOpt IsNot Nothing, nodeOpt.GetLocation(), NoLocation.Singleton))
End If
End Sub
Private Sub MarkEmbeddedAttributeTypeReference(attribute As VisualBasicAttributeData, nodeOpt As AttributeSyntax, compilation As VisualBasicCompilation)
Debug.Assert(Not attribute.HasErrors)
' Mark embedded attribute type reference only if the owner is itself not
' embedded and the attribute syntax is actually from the current compilation.
If Not Me.IsEmbedded AndAlso
attribute.AttributeClass.IsEmbedded AndAlso
nodeOpt IsNot Nothing AndAlso
compilation.ContainsSyntaxTree(nodeOpt.SyntaxTree) Then
' Note that none of embedded symbols from referenced
' assemblies or compilations should be found/referenced.
Debug.Assert(attribute.AttributeClass.ContainingAssembly Is compilation.Assembly)
compilation.EmbeddedSymbolManager.MarkSymbolAsReferenced(attribute.AttributeClass)
End If
End Sub
''' <summary>
''' Ensure that attributes are bound and the ObsoleteState of this symbol is known.
''' </summary>
Friend Sub ForceCompleteObsoleteAttribute()
If Me.ObsoleteState = ThreeState.Unknown Then
Me.GetAttributes()
End If
Debug.Assert(Me.ObsoleteState <> ThreeState.Unknown, "ObsoleteState should be true or false now.")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMarginViewModel.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.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph
{
internal class InheritanceMarginViewModel
{
/// <summary>
/// ImageMoniker used for the margin.
/// </summary>
public ImageMoniker ImageMoniker { get; }
/// <summary>
/// Tooltip for the margin.
/// </summary>
public TextBlock ToolTipTextBlock { get; }
/// <summary>
/// Text used for automation.
/// </summary>
public string AutomationName { get; }
/// <summary>
/// ViewModels for the context menu items.
/// </summary>
public ImmutableArray<InheritanceMenuItemViewModel> MenuItemViewModels { get; }
/// <summary>
/// Scale factor for the margin.
/// </summary>
public double ScaleFactor { get; }
// Internal for testing purpose
internal InheritanceMarginViewModel(
ImageMoniker imageMoniker,
TextBlock toolTipTextBlock,
string automationName,
double scaleFactor,
ImmutableArray<InheritanceMenuItemViewModel> menuItemViewModels)
{
ImageMoniker = imageMoniker;
ToolTipTextBlock = toolTipTextBlock;
AutomationName = automationName;
MenuItemViewModels = menuItemViewModels;
ScaleFactor = scaleFactor;
}
public static InheritanceMarginViewModel Create(
ClassificationTypeMap classificationTypeMap,
IClassificationFormatMap classificationFormatMap,
InheritanceMarginTag tag,
double zoomLevel)
{
var members = tag.MembersOnLine;
// ZoomLevel is 100 based. (e.g. 150%, 100%)
// ScaleFactor is 1 based. (e.g. 1.5, 1)
var scaleFactor = zoomLevel / 100;
if (members.Length == 1)
{
var member = tag.MembersOnLine[0];
// Here we want to show a classified text with loc text,
// e.g. 'Bar' is inherited.
// But the classified text are inlines, so can't directly use string.format to generate the string
var inlines = member.DisplayTexts.ToInlines(classificationFormatMap, classificationTypeMap);
var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf("{0}", StringComparison.Ordinal);
var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder];
var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + "{0}".Length)..];
inlines.Insert(0, new Run(prefixString));
inlines.Add(new Run(suffixString));
var toolTipTextBlock = inlines.ToTextBlock(classificationFormatMap);
toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight;
var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText());
var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems);
return new InheritanceMarginViewModel(tag.Moniker, toolTipTextBlock, automationName, scaleFactor, menuItemViewModels);
}
else
{
var textBlock = new TextBlock
{
Text = ServicesVSResources.Multiple_members_are_inherited
};
// Same automation name can't be set for control for accessibility purpose. So add the line number info.
var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber);
var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine);
return new InheritanceMarginViewModel(tag.Moniker, textBlock, automationName, scaleFactor, menuItemViewModels);
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph
{
internal class InheritanceMarginViewModel
{
/// <summary>
/// ImageMoniker used for the margin.
/// </summary>
public ImageMoniker ImageMoniker { get; }
/// <summary>
/// Tooltip for the margin.
/// </summary>
public TextBlock ToolTipTextBlock { get; }
/// <summary>
/// Text used for automation.
/// </summary>
public string AutomationName { get; }
/// <summary>
/// ViewModels for the context menu items.
/// </summary>
public ImmutableArray<InheritanceMenuItemViewModel> MenuItemViewModels { get; }
/// <summary>
/// Scale factor for the margin.
/// </summary>
public double ScaleFactor { get; }
// Internal for testing purpose
internal InheritanceMarginViewModel(
ImageMoniker imageMoniker,
TextBlock toolTipTextBlock,
string automationName,
double scaleFactor,
ImmutableArray<InheritanceMenuItemViewModel> menuItemViewModels)
{
ImageMoniker = imageMoniker;
ToolTipTextBlock = toolTipTextBlock;
AutomationName = automationName;
MenuItemViewModels = menuItemViewModels;
ScaleFactor = scaleFactor;
}
public static InheritanceMarginViewModel Create(
ClassificationTypeMap classificationTypeMap,
IClassificationFormatMap classificationFormatMap,
InheritanceMarginTag tag,
double zoomLevel)
{
var members = tag.MembersOnLine;
// ZoomLevel is 100 based. (e.g. 150%, 100%)
// ScaleFactor is 1 based. (e.g. 1.5, 1)
var scaleFactor = zoomLevel / 100;
if (members.Length == 1)
{
var member = tag.MembersOnLine[0];
// Here we want to show a classified text with loc text,
// e.g. 'Bar' is inherited.
// But the classified text are inlines, so can't directly use string.format to generate the string
var inlines = member.DisplayTexts.ToInlines(classificationFormatMap, classificationTypeMap);
var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf("{0}", StringComparison.Ordinal);
var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder];
var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + "{0}".Length)..];
inlines.Insert(0, new Run(prefixString));
inlines.Add(new Run(suffixString));
var toolTipTextBlock = inlines.ToTextBlock(classificationFormatMap);
toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight;
var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText());
var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems);
return new InheritanceMarginViewModel(tag.Moniker, toolTipTextBlock, automationName, scaleFactor, menuItemViewModels);
}
else
{
var textBlock = new TextBlock
{
Text = ServicesVSResources.Multiple_members_are_inherited
};
// Same automation name can't be set for control for accessibility purpose. So add the line number info.
var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber);
var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine);
return new InheritanceMarginViewModel(tag.Moniker, textBlock, automationName, scaleFactor, menuItemViewModels);
}
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./eng/common/templates/steps/build-reason.yml | # build-reason.yml
# Description: runs steps if build.reason condition is valid. conditions is a string of valid build reasons
# to include steps (',' separated).
parameters:
conditions: ''
steps: []
steps:
- ${{ if and( not(startsWith(parameters.conditions, 'not')), contains(parameters.conditions, variables['build.reason'])) }}:
- ${{ parameters.steps }}
- ${{ if and( startsWith(parameters.conditions, 'not'), not(contains(parameters.conditions, variables['build.reason']))) }}:
- ${{ parameters.steps }}
| # build-reason.yml
# Description: runs steps if build.reason condition is valid. conditions is a string of valid build reasons
# to include steps (',' separated).
parameters:
conditions: ''
steps: []
steps:
- ${{ if and( not(startsWith(parameters.conditions, 'not')), contains(parameters.conditions, variables['build.reason'])) }}:
- ${{ parameters.steps }}
- ${{ if and( startsWith(parameters.conditions, 'not'), not(contains(parameters.conditions, variables['build.reason']))) }}:
- ${{ parameters.steps }}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Tools/ExternalAccess/FSharp/Internal/Diagnostics/FSharpUnusedOpensDiagnosticAnalyzer.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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Diagnostics
{
[Shared]
[ExportLanguageService(typeof(FSharpUnusedOpensDiagnosticAnalyzerService), LanguageNames.FSharp)]
internal class FSharpUnusedOpensDiagnosticAnalyzerService : ILanguageService
{
private readonly IFSharpUnusedOpensDiagnosticAnalyzer _analyzer;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpUnusedOpensDiagnosticAnalyzerService(IFSharpUnusedOpensDiagnosticAnalyzer analyzer)
{
_analyzer = analyzer;
}
public Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken)
{
return _analyzer.AnalyzeSemanticsAsync(descriptor, document, cancellationToken);
}
}
[DiagnosticAnalyzer(LanguageNames.FSharp)]
internal class FSharpUnusedOpensDeclarationsDiagnosticAnalyzer : DocumentDiagnosticAnalyzer
{
private readonly DiagnosticDescriptor _descriptor =
new DiagnosticDescriptor(
IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId,
ExternalAccessFSharpResources.RemoveUnusedOpens,
ExternalAccessFSharpResources.UnusedOpens,
DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: FSharpDiagnosticCustomTags.Unnecessary);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_descriptor);
public override int Priority => 90; // Default = 50
public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken)
{
var analyzer = document.Project.LanguageServices.GetService<FSharpUnusedOpensDiagnosticAnalyzerService>();
if (analyzer == null)
{
return Task.FromResult(ImmutableArray<Diagnostic>.Empty);
}
return analyzer.AnalyzeSemanticsAsync(_descriptor, document, cancellationToken);
}
public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
return Task.FromResult(ImmutableArray<Diagnostic>.Empty);
}
public DiagnosticAnalyzerCategory GetAnalyzerCategory()
{
return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis;
}
public bool OpenFileOnly(Workspace workspace)
{
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Diagnostics
{
[Shared]
[ExportLanguageService(typeof(FSharpUnusedOpensDiagnosticAnalyzerService), LanguageNames.FSharp)]
internal class FSharpUnusedOpensDiagnosticAnalyzerService : ILanguageService
{
private readonly IFSharpUnusedOpensDiagnosticAnalyzer _analyzer;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpUnusedOpensDiagnosticAnalyzerService(IFSharpUnusedOpensDiagnosticAnalyzer analyzer)
{
_analyzer = analyzer;
}
public Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken)
{
return _analyzer.AnalyzeSemanticsAsync(descriptor, document, cancellationToken);
}
}
[DiagnosticAnalyzer(LanguageNames.FSharp)]
internal class FSharpUnusedOpensDeclarationsDiagnosticAnalyzer : DocumentDiagnosticAnalyzer
{
private readonly DiagnosticDescriptor _descriptor =
new DiagnosticDescriptor(
IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId,
ExternalAccessFSharpResources.RemoveUnusedOpens,
ExternalAccessFSharpResources.UnusedOpens,
DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: FSharpDiagnosticCustomTags.Unnecessary);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_descriptor);
public override int Priority => 90; // Default = 50
public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken)
{
var analyzer = document.Project.LanguageServices.GetService<FSharpUnusedOpensDiagnosticAnalyzerService>();
if (analyzer == null)
{
return Task.FromResult(ImmutableArray<Diagnostic>.Empty);
}
return analyzer.AnalyzeSemanticsAsync(_descriptor, document, cancellationToken);
}
public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
return Task.FromResult(ImmutableArray<Diagnostic>.Empty);
}
public DiagnosticAnalyzerCategory GetAnalyzerCategory()
{
return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis;
}
public bool OpenFileOnly(Workspace workspace)
{
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/Core/Portable/Operations/BasicBlock.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
/// <summary>
/// Represents a basic block in a <see cref="ControlFlowGraph"/> with a sequence of <see cref="Operations"/>.
/// Once a basic block is entered, all operations in it are always executed.
/// Optional <see cref="BranchValue"/>, if non-null, is evaluated after the <see cref="Operations"/>.
/// Control flow leaves the basic block by taking either the <see cref="ConditionalSuccessor"/> branch or
/// the <see cref="FallThroughSuccessor"/> branch.
/// </summary>
public sealed class BasicBlock
{
#if DEBUG
private bool _successorsAreSealed;
private bool _predecessorsAreSealed;
#endif
private ControlFlowBranch? _lazySuccessor;
private ControlFlowBranch? _lazyConditionalSuccessor;
private ImmutableArray<ControlFlowBranch> _lazyPredecessors;
internal BasicBlock(
BasicBlockKind kind,
ImmutableArray<IOperation> operations,
IOperation? branchValue,
ControlFlowConditionKind conditionKind,
int ordinal,
bool isReachable,
ControlFlowRegion region)
{
Kind = kind;
Operations = operations;
BranchValue = branchValue;
ConditionKind = conditionKind;
Ordinal = ordinal;
IsReachable = isReachable;
EnclosingRegion = region;
}
/// <summary>
/// Basic block kind (entry, block, or exit).
/// </summary>
public BasicBlockKind Kind { get; }
/// <summary>
/// Sequence of operations in the basic block.
/// </summary>
public ImmutableArray<IOperation> Operations { get; }
/// <summary>
/// Optional branch value, which if non-null, is evaluated after <see cref="Operations"/>.
/// For conditional branches, this value is used to represent the condition which determines if
/// <see cref="ConditionalSuccessor"/> is taken or not.
/// For non-conditional branches, this value is used to represent the return or throw value associated
/// with the <see cref="FallThroughSuccessor"/>.
/// </summary>
public IOperation? BranchValue { get; }
/// <summary>
/// Indicates the condition kind for the branch out of the basic block.
/// </summary>
public ControlFlowConditionKind ConditionKind { get; }
/// <summary>
/// Optional fall through branch executed at the end of the basic block.
/// This branch is null for exit block, and non-null for all other basic blocks.
/// </summary>
public ControlFlowBranch? FallThroughSuccessor
{
get
{
#if DEBUG
Debug.Assert(_successorsAreSealed);
#endif
return _lazySuccessor;
}
}
/// <summary>
/// Optional conditional branch out of the basic block.
/// If non-null, this branch may be taken at the end of the basic block based
/// on the <see cref="ConditionKind"/> and <see cref="BranchValue"/>.
/// </summary>
public ControlFlowBranch? ConditionalSuccessor
{
get
{
#if DEBUG
Debug.Assert(_successorsAreSealed);
#endif
return _lazyConditionalSuccessor;
}
}
/// <summary>
/// List of basic blocks which have a control flow branch (<see cref="FallThroughSuccessor"/> or <see cref="ConditionalSuccessor"/>)
/// into this basic block.
/// </summary>
public ImmutableArray<ControlFlowBranch> Predecessors
{
get
{
#if DEBUG
Debug.Assert(_predecessorsAreSealed);
#endif
return _lazyPredecessors;
}
}
/// <summary>
/// Unique ordinal for each basic block in a <see cref="ControlFlowGraph"/>,
/// which can be used to index into <see cref="ControlFlowGraph.Blocks"/> array.
/// </summary>
public int Ordinal { get; }
/// <summary>
/// Indicates if control flow can reach this basic block from the entry block of the graph.
/// </summary>
public bool IsReachable { get; }
/// <summary>
/// Enclosing region.
/// </summary>
public ControlFlowRegion EnclosingRegion { get; }
internal void SetSuccessors(ControlFlowBranch? successor, ControlFlowBranch? conditionalSuccessor)
{
#if DEBUG
Debug.Assert(!_successorsAreSealed);
Debug.Assert(_lazySuccessor == null);
Debug.Assert(_lazyConditionalSuccessor == null);
#endif
_lazySuccessor = successor;
_lazyConditionalSuccessor = conditionalSuccessor;
#if DEBUG
_successorsAreSealed = true;
#endif
}
internal void SetPredecessors(ImmutableArray<ControlFlowBranch> predecessors)
{
#if DEBUG
Debug.Assert(!_predecessorsAreSealed);
Debug.Assert(_lazyPredecessors.IsDefault);
Debug.Assert(!predecessors.IsDefault);
#endif
_lazyPredecessors = predecessors;
#if DEBUG
_predecessorsAreSealed = true;
#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.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
/// <summary>
/// Represents a basic block in a <see cref="ControlFlowGraph"/> with a sequence of <see cref="Operations"/>.
/// Once a basic block is entered, all operations in it are always executed.
/// Optional <see cref="BranchValue"/>, if non-null, is evaluated after the <see cref="Operations"/>.
/// Control flow leaves the basic block by taking either the <see cref="ConditionalSuccessor"/> branch or
/// the <see cref="FallThroughSuccessor"/> branch.
/// </summary>
public sealed class BasicBlock
{
#if DEBUG
private bool _successorsAreSealed;
private bool _predecessorsAreSealed;
#endif
private ControlFlowBranch? _lazySuccessor;
private ControlFlowBranch? _lazyConditionalSuccessor;
private ImmutableArray<ControlFlowBranch> _lazyPredecessors;
internal BasicBlock(
BasicBlockKind kind,
ImmutableArray<IOperation> operations,
IOperation? branchValue,
ControlFlowConditionKind conditionKind,
int ordinal,
bool isReachable,
ControlFlowRegion region)
{
Kind = kind;
Operations = operations;
BranchValue = branchValue;
ConditionKind = conditionKind;
Ordinal = ordinal;
IsReachable = isReachable;
EnclosingRegion = region;
}
/// <summary>
/// Basic block kind (entry, block, or exit).
/// </summary>
public BasicBlockKind Kind { get; }
/// <summary>
/// Sequence of operations in the basic block.
/// </summary>
public ImmutableArray<IOperation> Operations { get; }
/// <summary>
/// Optional branch value, which if non-null, is evaluated after <see cref="Operations"/>.
/// For conditional branches, this value is used to represent the condition which determines if
/// <see cref="ConditionalSuccessor"/> is taken or not.
/// For non-conditional branches, this value is used to represent the return or throw value associated
/// with the <see cref="FallThroughSuccessor"/>.
/// </summary>
public IOperation? BranchValue { get; }
/// <summary>
/// Indicates the condition kind for the branch out of the basic block.
/// </summary>
public ControlFlowConditionKind ConditionKind { get; }
/// <summary>
/// Optional fall through branch executed at the end of the basic block.
/// This branch is null for exit block, and non-null for all other basic blocks.
/// </summary>
public ControlFlowBranch? FallThroughSuccessor
{
get
{
#if DEBUG
Debug.Assert(_successorsAreSealed);
#endif
return _lazySuccessor;
}
}
/// <summary>
/// Optional conditional branch out of the basic block.
/// If non-null, this branch may be taken at the end of the basic block based
/// on the <see cref="ConditionKind"/> and <see cref="BranchValue"/>.
/// </summary>
public ControlFlowBranch? ConditionalSuccessor
{
get
{
#if DEBUG
Debug.Assert(_successorsAreSealed);
#endif
return _lazyConditionalSuccessor;
}
}
/// <summary>
/// List of basic blocks which have a control flow branch (<see cref="FallThroughSuccessor"/> or <see cref="ConditionalSuccessor"/>)
/// into this basic block.
/// </summary>
public ImmutableArray<ControlFlowBranch> Predecessors
{
get
{
#if DEBUG
Debug.Assert(_predecessorsAreSealed);
#endif
return _lazyPredecessors;
}
}
/// <summary>
/// Unique ordinal for each basic block in a <see cref="ControlFlowGraph"/>,
/// which can be used to index into <see cref="ControlFlowGraph.Blocks"/> array.
/// </summary>
public int Ordinal { get; }
/// <summary>
/// Indicates if control flow can reach this basic block from the entry block of the graph.
/// </summary>
public bool IsReachable { get; }
/// <summary>
/// Enclosing region.
/// </summary>
public ControlFlowRegion EnclosingRegion { get; }
internal void SetSuccessors(ControlFlowBranch? successor, ControlFlowBranch? conditionalSuccessor)
{
#if DEBUG
Debug.Assert(!_successorsAreSealed);
Debug.Assert(_lazySuccessor == null);
Debug.Assert(_lazyConditionalSuccessor == null);
#endif
_lazySuccessor = successor;
_lazyConditionalSuccessor = conditionalSuccessor;
#if DEBUG
_successorsAreSealed = true;
#endif
}
internal void SetPredecessors(ImmutableArray<ControlFlowBranch> predecessors)
{
#if DEBUG
Debug.Assert(!_predecessorsAreSealed);
Debug.Assert(_lazyPredecessors.IsDefault);
Debug.Assert(!predecessors.IsDefault);
#endif
_lazyPredecessors = predecessors;
#if DEBUG
_predecessorsAreSealed = true;
#endif
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TreeData.Debug.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;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract partial class TreeData
{
private class Debug : NodeAndText
{
private readonly TreeData _debugNodeData;
public Debug(SyntaxNode root, SourceText text)
: base(root, text)
{
_debugNodeData = new Node(root);
}
public override string GetTextBetween(SyntaxToken token1, SyntaxToken token2)
{
var text = base.GetTextBetween(token1, token2);
Contract.ThrowIfFalse(text == _debugNodeData.GetTextBetween(token1, token2));
return text;
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract partial class TreeData
{
private class Debug : NodeAndText
{
private readonly TreeData _debugNodeData;
public Debug(SyntaxNode root, SourceText text)
: base(root, text)
{
_debugNodeData = new Node(root);
}
public override string GetTextBetween(SyntaxToken token1, SyntaxToken token2)
{
var text = base.GetTextBetween(token1, token2);
Contract.ThrowIfFalse(text == _debugNodeData.GetTextBetween(token1, token2));
return text;
}
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
internal sealed class RenameTrackingTestState : IDisposable
{
private readonly ITagger<RenameTrackingTag> _tagger;
public readonly TestWorkspace Workspace;
private readonly IWpfTextView _view;
private readonly ITextUndoHistoryRegistry _historyRegistry;
private string _notificationMessage = null;
private readonly TestHostDocument _hostDocument;
public TestHostDocument HostDocument { get { return _hostDocument; } }
private readonly IEditorOperations _editorOperations;
public IEditorOperations EditorOperations { get { return _editorOperations; } }
private readonly MockRefactorNotifyService _mockRefactorNotifyService;
public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } }
private readonly RenameTrackingCodeRefactoringProvider _codeRefactoringProvider;
private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler();
public static RenameTrackingTestState Create(
string markup,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = CreateTestWorkspace(markup, languageName);
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public static RenameTrackingTestState CreateFromWorkspaceXml(
string workspaceXml,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = CreateTestWorkspace(workspaceXml);
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public RenameTrackingTestState(
TestWorkspace workspace,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
this.Workspace = workspace;
_hostDocument = Workspace.Documents.First();
_view = _hostDocument.GetTextView();
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value));
_editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view);
_historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value;
_mockRefactorNotifyService = new MockRefactorNotifyService
{
OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue,
OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue
};
// Mock the action taken by the workspace INotificationService
var notificationService = (INotificationServiceCallback)Workspace.Services.GetRequiredService<INotificationService>();
var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message);
notificationService.NotificationCallback = callback;
var tracker = new RenameTrackingTaggerProvider(
Workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
Workspace.ExportProvider.GetExport<IInlineRenameService>().Value,
Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value,
Workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>());
_tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer());
if (languageName == LanguageNames.CSharp ||
languageName == LanguageNames.VisualBasic)
{
_codeRefactoringProvider = new RenameTrackingCodeRefactoringProvider(
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else
{
throw new ArgumentException("Invalid language name: " + languageName, nameof(languageName));
}
}
private static TestWorkspace CreateTestWorkspace(string code, string languageName)
{
return CreateTestWorkspace(string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document>{1}</Document>
</Project>
</Workspace>", languageName, code));
}
private static TestWorkspace CreateTestWorkspace(string xml)
{
return TestWorkspace.Create(xml, composition: EditorTestCompositions.EditorFeaturesWpf);
}
public void SendEscape()
=> _commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), TestCommandExecutionContext.Create());
public void MoveCaret(int delta)
{
var position = _view.Caret.Position.BufferPosition.Position;
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta));
}
public void Undo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Undo(count);
}
public void Redo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Redo(count);
}
public async Task AssertNoTag()
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
Assert.Equal(0, tags.Count());
}
/// <param name="textSpan">If <see langword="null"/> the current caret position will be used.</param>
public async Task<CodeAction> TryGetCodeActionAsync(TextSpan? textSpan = null)
{
var span = textSpan ?? new TextSpan(_view.Caret.Position.BufferPosition, 0);
var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var actions = new List<CodeAction>();
var context = new CodeRefactoringContext(
document, span, actions.Add, CancellationToken.None);
await _codeRefactoringProvider.ComputeRefactoringsAsync(context);
return actions.SingleOrDefault();
}
public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false)
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
// There should only ever be one tag
Assert.Equal(1, tags.Count());
var tag = tags.Single();
// There should only be one code action for the tag
var codeAction = await TryGetCodeActionAsync(tag.Span.Span.ToTextSpan());
Assert.NotNull(codeAction);
Assert.Equal(string.Format(EditorFeaturesResources.Rename_0_to_1, expectedFromName, expectedToName), codeAction.Title);
if (invokeAction)
{
var operations = (await codeAction.GetOperationsAsync(CancellationToken.None)).ToArray();
Assert.Equal(1, operations.Length);
operations[0].TryApply(this.Workspace, new ProgressTracker(), CancellationToken.None);
}
}
public void AssertNoNotificationMessage()
=> Assert.Null(_notificationMessage);
public void AssertNotificationMessage()
=> Assert.NotNull(_notificationMessage);
private async Task WaitForAsyncOperationsAsync()
{
var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>();
await provider.WaitAllDispatcherOperationAndTasksAsync(
Workspace,
FeatureAttribute.RenameTracking,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.Workspace,
FeatureAttribute.EventHookup);
}
public void Dispose()
=> Workspace.Dispose();
}
}
| // Licensed to the .NET Foundation under one or more 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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
internal sealed class RenameTrackingTestState : IDisposable
{
private readonly ITagger<RenameTrackingTag> _tagger;
public readonly TestWorkspace Workspace;
private readonly IWpfTextView _view;
private readonly ITextUndoHistoryRegistry _historyRegistry;
private string _notificationMessage = null;
private readonly TestHostDocument _hostDocument;
public TestHostDocument HostDocument { get { return _hostDocument; } }
private readonly IEditorOperations _editorOperations;
public IEditorOperations EditorOperations { get { return _editorOperations; } }
private readonly MockRefactorNotifyService _mockRefactorNotifyService;
public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } }
private readonly RenameTrackingCodeRefactoringProvider _codeRefactoringProvider;
private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler();
public static RenameTrackingTestState Create(
string markup,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = CreateTestWorkspace(markup, languageName);
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public static RenameTrackingTestState CreateFromWorkspaceXml(
string workspaceXml,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = CreateTestWorkspace(workspaceXml);
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public RenameTrackingTestState(
TestWorkspace workspace,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
this.Workspace = workspace;
_hostDocument = Workspace.Documents.First();
_view = _hostDocument.GetTextView();
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value));
_editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view);
_historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value;
_mockRefactorNotifyService = new MockRefactorNotifyService
{
OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue,
OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue
};
// Mock the action taken by the workspace INotificationService
var notificationService = (INotificationServiceCallback)Workspace.Services.GetRequiredService<INotificationService>();
var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message);
notificationService.NotificationCallback = callback;
var tracker = new RenameTrackingTaggerProvider(
Workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
Workspace.ExportProvider.GetExport<IInlineRenameService>().Value,
Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value,
Workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>());
_tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer());
if (languageName == LanguageNames.CSharp ||
languageName == LanguageNames.VisualBasic)
{
_codeRefactoringProvider = new RenameTrackingCodeRefactoringProvider(
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else
{
throw new ArgumentException("Invalid language name: " + languageName, nameof(languageName));
}
}
private static TestWorkspace CreateTestWorkspace(string code, string languageName)
{
return CreateTestWorkspace(string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document>{1}</Document>
</Project>
</Workspace>", languageName, code));
}
private static TestWorkspace CreateTestWorkspace(string xml)
{
return TestWorkspace.Create(xml, composition: EditorTestCompositions.EditorFeaturesWpf);
}
public void SendEscape()
=> _commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), TestCommandExecutionContext.Create());
public void MoveCaret(int delta)
{
var position = _view.Caret.Position.BufferPosition.Position;
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta));
}
public void Undo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Undo(count);
}
public void Redo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Redo(count);
}
public async Task AssertNoTag()
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
Assert.Equal(0, tags.Count());
}
/// <param name="textSpan">If <see langword="null"/> the current caret position will be used.</param>
public async Task<CodeAction> TryGetCodeActionAsync(TextSpan? textSpan = null)
{
var span = textSpan ?? new TextSpan(_view.Caret.Position.BufferPosition, 0);
var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var actions = new List<CodeAction>();
var context = new CodeRefactoringContext(
document, span, actions.Add, CancellationToken.None);
await _codeRefactoringProvider.ComputeRefactoringsAsync(context);
return actions.SingleOrDefault();
}
public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false)
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
// There should only ever be one tag
Assert.Equal(1, tags.Count());
var tag = tags.Single();
// There should only be one code action for the tag
var codeAction = await TryGetCodeActionAsync(tag.Span.Span.ToTextSpan());
Assert.NotNull(codeAction);
Assert.Equal(string.Format(EditorFeaturesResources.Rename_0_to_1, expectedFromName, expectedToName), codeAction.Title);
if (invokeAction)
{
var operations = (await codeAction.GetOperationsAsync(CancellationToken.None)).ToArray();
Assert.Equal(1, operations.Length);
operations[0].TryApply(this.Workspace, new ProgressTracker(), CancellationToken.None);
}
}
public void AssertNoNotificationMessage()
=> Assert.Null(_notificationMessage);
public void AssertNotificationMessage()
=> Assert.NotNull(_notificationMessage);
private async Task WaitForAsyncOperationsAsync()
{
var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>();
await provider.WaitAllDispatcherOperationAndTasksAsync(
Workspace,
FeatureAttribute.RenameTracking,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.Workspace,
FeatureAttribute.EventHookup);
}
public void Dispose()
=> Workspace.Dispose();
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/Core/Portable/Text/SourceText.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.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// An abstraction of source text.
/// </summary>
public abstract class SourceText
{
private const int CharBufferSize = 32 * 1024;
private const int CharBufferCount = 5;
internal const int LargeObjectHeapLimitInChars = 40 * 1024; // 40KB
private static readonly ObjectPool<char[]> s_charArrayPool = new ObjectPool<char[]>(() => new char[CharBufferSize], CharBufferCount);
private readonly SourceHashAlgorithm _checksumAlgorithm;
private SourceTextContainer? _lazyContainer;
private TextLineCollection? _lazyLineInfo;
private ImmutableArray<byte> _lazyChecksum;
private ImmutableArray<byte> _precomputedEmbeddedTextBlob;
private static readonly Encoding s_utf8EncodingWithNoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false);
protected SourceText(ImmutableArray<byte> checksum = default(ImmutableArray<byte>), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, SourceTextContainer? container = null)
{
ValidateChecksumAlgorithm(checksumAlgorithm);
if (!checksum.IsDefault && checksum.Length != CryptographicHashProvider.GetHashSize(checksumAlgorithm))
{
throw new ArgumentException(CodeAnalysisResources.InvalidHash, nameof(checksum));
}
_checksumAlgorithm = checksumAlgorithm;
_lazyChecksum = checksum;
_lazyContainer = container;
}
internal SourceText(ImmutableArray<byte> checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray<byte> embeddedTextBlob)
: this(checksum, checksumAlgorithm, container: null)
{
// We should never have precomputed the embedded text blob without precomputing the checksum.
Debug.Assert(embeddedTextBlob.IsDefault || !checksum.IsDefault);
if (!checksum.IsDefault && embeddedTextBlob.IsDefault)
{
// We can't compute the embedded text blob lazily if we're given a precomputed checksum.
// This happens when source bytes/stream were given, but canBeEmbedded=true was not passed.
_precomputedEmbeddedTextBlob = ImmutableArray<byte>.Empty;
}
else
{
_precomputedEmbeddedTextBlob = embeddedTextBlob;
}
}
internal static void ValidateChecksumAlgorithm(SourceHashAlgorithm checksumAlgorithm)
{
if (!SourceHashAlgorithms.IsSupportedAlgorithm(checksumAlgorithm))
{
throw new ArgumentException(CodeAnalysisResources.UnsupportedHashAlgorithm, nameof(checksumAlgorithm));
}
}
/// <summary>
/// Constructs a <see cref="SourceText"/> from text in a string.
/// </summary>
/// <param name="text">Text.</param>
/// <param name="encoding">
/// Encoding of the file that the <paramref name="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 resulting <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="ArgumentNullException"><paramref name="text"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public static SourceText From(string text, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
return new StringText(text, encoding, checksumAlgorithm: checksumAlgorithm);
}
/// <summary>
/// Constructs a <see cref="SourceText"/> from text in a string.
/// </summary>
/// <param name="reader">TextReader</param>
/// <param name="length">length of content from <paramref name="reader"/></param>
/// <param name="encoding">
/// Encoding of the file that the <paramref name="reader"/> 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 resulting <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="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public static SourceText From(
TextReader reader,
int length,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
// If the resulting string would end up on the large object heap, then use LargeEncodedText.
if (length >= LargeObjectHeapLimitInChars)
{
return LargeText.Decode(reader, length, encoding, checksumAlgorithm);
}
string text = reader.ReadToEnd();
return From(text, encoding, checksumAlgorithm);
}
// 1.0 BACKCOMPAT OVERLOAD - DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static SourceText From(Stream stream, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
=> From(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded: false);
/// <summary>
/// Constructs a <see cref="SourceText"/> from stream content.
/// </summary>
/// <param name="stream">Stream. The stream must be seekable.</param>
/// <param name="encoding">
/// Data encoding to use if the stream doesn't start with Byte Order Mark specifying the encoding.
/// <see cref="Encoding.UTF8"/> if not specified.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <param name="throwIfBinaryDetected">If the decoded text contains at least two consecutive NUL
/// characters, then an <see cref="InvalidDataException"/> is thrown.</param>
/// <param name="canBeEmbedded">True if the text can be passed to <see cref="EmbeddedText.FromSource"/> and be embedded in a PDB.</param>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> doesn't support reading or seeking.
/// <paramref name="checksumAlgorithm"/> is not supported.
/// </exception>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
/// <exception cref="InvalidDataException">Two consecutive NUL characters were detected in the decoded text and <paramref name="throwIfBinaryDetected"/> was true.</exception>
/// <exception cref="IOException">An I/O error occurs.</exception>
/// <remarks>Reads from the beginning of the stream. Leaves the stream open.</remarks>
public static SourceText From(
Stream stream,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,
bool throwIfBinaryDetected = false,
bool canBeEmbedded = false)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(stream));
}
ValidateChecksumAlgorithm(checksumAlgorithm);
encoding = encoding ?? s_utf8EncodingWithNoBOM;
if (stream.CanSeek)
{
// If the resulting string would end up on the large object heap, then use LargeEncodedText.
if (encoding.GetMaxCharCountOrThrowIfHuge(stream) >= LargeObjectHeapLimitInChars)
{
return LargeText.Decode(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
}
}
string text = Decode(stream, encoding, out encoding);
if (throwIfBinaryDetected && IsBinary(text))
{
throw new InvalidDataException();
}
// We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
// We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
var checksum = CalculateChecksum(stream, checksumAlgorithm);
var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(stream) : default(ImmutableArray<byte>);
return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob);
}
// 1.0 BACKCOMPAT OVERLOAD - DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static SourceText From(byte[] buffer, int length, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
=> From(buffer, length, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded: false);
/// <summary>
/// Constructs a <see cref="SourceText"/> from a byte array.
/// </summary>
/// <param name="buffer">The encoded source buffer.</param>
/// <param name="length">The number of bytes to read from the buffer.</param>
/// <param name="encoding">
/// Data encoding to use if the encoded buffer doesn't start with Byte Order Mark.
/// <see cref="Encoding.UTF8"/> if not specified.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <param name="throwIfBinaryDetected">If the decoded text contains at least two consecutive NUL
/// characters, then an <see cref="InvalidDataException"/> is thrown.</param>
/// <returns>The decoded text.</returns>
/// <param name="canBeEmbedded">True if the text can be passed to <see cref="EmbeddedText.FromSource"/> and be embedded in a PDB.</param>
/// <exception cref="ArgumentNullException">The <paramref name="buffer"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="length"/> is negative or longer than the <paramref name="buffer"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
/// <exception cref="InvalidDataException">Two consecutive NUL characters were detected in the decoded text and <paramref name="throwIfBinaryDetected"/> was true.</exception>
public static SourceText From(
byte[] buffer,
int length,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,
bool throwIfBinaryDetected = false,
bool canBeEmbedded = false)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (length < 0 || length > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
ValidateChecksumAlgorithm(checksumAlgorithm);
string text = Decode(buffer, length, encoding ?? s_utf8EncodingWithNoBOM, out encoding);
if (throwIfBinaryDetected && IsBinary(text))
{
throw new InvalidDataException();
}
// We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
// We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
var checksum = CalculateChecksum(buffer, 0, length, checksumAlgorithm);
var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(new ArraySegment<byte>(buffer, 0, length)) : default(ImmutableArray<byte>);
return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob);
}
/// <summary>
/// Decode text from a stream.
/// </summary>
/// <param name="stream">The stream containing encoded text.</param>
/// <param name="encoding">The encoding to use if an encoding cannot be determined from the byte order mark.</param>
/// <param name="actualEncoding">The actual encoding used.</param>
/// <returns>The decoded text.</returns>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
private static string Decode(Stream stream, Encoding encoding, out Encoding actualEncoding)
{
RoslynDebug.Assert(stream != null);
RoslynDebug.Assert(encoding != null);
const int maxBufferSize = 4096;
int bufferSize = maxBufferSize;
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
int length = (int)stream.Length;
if (length == 0)
{
actualEncoding = encoding;
return string.Empty;
}
bufferSize = Math.Min(maxBufferSize, length);
}
// Note: We are setting the buffer size to 4KB instead of the default 1KB. That's
// because we can reach this code path for FileStreams and, to avoid FileStream
// buffer allocations for small files, we may intentionally be using a FileStream
// with a very small (1 byte) buffer. Using 4KB here matches the default buffer
// size for FileStream and means we'll still be doing file I/O in 4KB chunks.
using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: bufferSize, leaveOpen: true))
{
string text = reader.ReadToEnd();
actualEncoding = reader.CurrentEncoding;
return text;
}
}
/// <summary>
/// Decode text from a byte array.
/// </summary>
/// <param name="buffer">The byte array containing encoded text.</param>
/// <param name="length">The count of valid bytes in <paramref name="buffer"/>.</param>
/// <param name="encoding">The encoding to use if an encoding cannot be determined from the byte order mark.</param>
/// <param name="actualEncoding">The actual encoding used.</param>
/// <returns>The decoded text.</returns>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
private static string Decode(byte[] buffer, int length, Encoding encoding, out Encoding actualEncoding)
{
RoslynDebug.Assert(buffer != null);
RoslynDebug.Assert(encoding != null);
int preambleLength;
actualEncoding = TryReadByteOrderMark(buffer, length, out preambleLength) ?? encoding;
return actualEncoding.GetString(buffer, preambleLength, length - preambleLength);
}
/// <summary>
/// Check for occurrence of two consecutive NUL (U+0000) characters.
/// This is unlikely to appear in genuine text, so it's a good heuristic
/// to detect binary files.
/// </summary>
/// <remarks>
/// internal for unit testing
/// </remarks>
internal static bool IsBinary(string text)
{
// PERF: We can advance two chars at a time unless we find a NUL.
for (int i = 1; i < text.Length;)
{
if (text[i] == '\0')
{
if (text[i - 1] == '\0')
{
return true;
}
i += 1;
}
else
{
i += 2;
}
}
return false;
}
/// <summary>
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </summary>
public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm;
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// If the encoding is not specified the source 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.
/// </remarks>
public abstract Encoding? Encoding { get; }
/// <summary>
/// The length of the text in characters.
/// </summary>
public abstract int Length { get; }
/// <summary>
/// The size of the storage representation of the text (in characters).
/// This can differ from length when storage buffers are reused to represent fragments/subtext.
/// </summary>
internal virtual int StorageSize
{
get { return this.Length; }
}
internal virtual ImmutableArray<SourceText> Segments
{
get { return ImmutableArray<SourceText>.Empty; }
}
internal virtual SourceText StorageKey
{
get { return this; }
}
/// <summary>
/// Indicates whether this source text can be embedded in the PDB.
/// </summary>
/// <remarks>
/// If this text was constructed via <see cref="From(byte[], int, Encoding, SourceHashAlgorithm, bool, bool)"/> or
/// <see cref="From(Stream, Encoding, SourceHashAlgorithm, bool, bool)"/>, then the canBeEmbedded arg must have
/// been true.
///
/// Otherwise, <see cref="Encoding" /> must be non-null.
/// </remarks>
public bool CanBeEmbedded
{
get
{
if (_precomputedEmbeddedTextBlob.IsDefault)
{
// If we didn't precompute the embedded text blob from bytes/stream,
// we can only support embedding if we have an encoding with which
// to encode the text in the PDB.
return Encoding != null;
}
// We use a sentinel empty blob to indicate that embedding has been disallowed.
return !_precomputedEmbeddedTextBlob.IsEmpty;
}
}
/// <summary>
/// If the text was created from a stream or byte[] and canBeEmbedded argument was true,
/// this provides the embedded text blob that was precomputed using the original stream
/// or byte[]. The precomputation was required in that case so that the bytes written to
/// the PDB match the original bytes exactly (and match the checksum of the original
/// bytes).
/// </summary>
internal ImmutableArray<byte> PrecomputedEmbeddedTextBlob => _precomputedEmbeddedTextBlob;
/// <summary>
/// Returns a character at given position.
/// </summary>
/// <param name="position">The position to get the character from.</param>
/// <returns>The character.</returns>
/// <exception cref="ArgumentOutOfRangeException">When position is negative or
/// greater than <see cref="Length"/>.</exception>
public abstract char this[int position] { get; }
/// <summary>
/// Copy a range of characters from this SourceText to a destination array.
/// </summary>
public abstract void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
/// <summary>
/// The container of this <see cref="SourceText"/>.
/// </summary>
public virtual SourceTextContainer Container
{
get
{
if (_lazyContainer == null)
{
Interlocked.CompareExchange(ref _lazyContainer, new StaticContainer(this), null);
}
return _lazyContainer;
}
}
internal void CheckSubSpan(TextSpan span)
{
Debug.Assert(0 <= span.Start && span.Start <= span.End);
if (span.End > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(span));
}
}
/// <summary>
/// Gets a <see cref="SourceText"/> that contains the characters in the specified span of this text.
/// </summary>
public virtual SourceText GetSubText(TextSpan span)
{
CheckSubSpan(span);
int spanLength = span.Length;
if (spanLength == 0)
{
return SourceText.From(string.Empty, this.Encoding, this.ChecksumAlgorithm);
}
else if (spanLength == this.Length && span.Start == 0)
{
return this;
}
else
{
return new SubText(this, span);
}
}
/// <summary>
/// Returns a <see cref="SourceText"/> that has the contents of this text including and after the start position.
/// </summary>
public SourceText GetSubText(int start)
{
if (start < 0 || start > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(start));
}
if (start == 0)
{
return this;
}
else
{
return this.GetSubText(new TextSpan(start, this.Length - start));
}
}
/// <summary>
/// Write this <see cref="SourceText"/> to a text writer.
/// </summary>
public void Write(TextWriter textWriter, CancellationToken cancellationToken = default(CancellationToken))
{
this.Write(textWriter, new TextSpan(0, this.Length), cancellationToken);
}
/// <summary>
/// Write a span of text to a text writer.
/// </summary>
public virtual void Write(TextWriter writer, TextSpan span, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSubSpan(span);
var buffer = s_charArrayPool.Allocate();
try
{
int offset = span.Start;
int end = span.End;
while (offset < end)
{
cancellationToken.ThrowIfCancellationRequested();
int count = Math.Min(buffer.Length, end - offset);
this.CopyTo(offset, buffer, 0, count);
writer.Write(buffer, 0, count);
offset += count;
}
}
finally
{
s_charArrayPool.Free(buffer);
}
}
public ImmutableArray<byte> GetChecksum()
{
if (_lazyChecksum.IsDefault)
{
using (var stream = new SourceTextStream(this, useDefaultEncodingIfNull: true))
{
ImmutableInterlocked.InterlockedInitialize(ref _lazyChecksum, CalculateChecksum(stream, _checksumAlgorithm));
}
}
return _lazyChecksum;
}
internal static ImmutableArray<byte> CalculateChecksum(byte[] buffer, int offset, int count, SourceHashAlgorithm algorithmId)
{
using (var algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
{
RoslynDebug.Assert(algorithm != null);
return ImmutableArray.Create(algorithm.ComputeHash(buffer, offset, count));
}
}
internal static ImmutableArray<byte> CalculateChecksum(Stream stream, SourceHashAlgorithm algorithmId)
{
using (var algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
{
RoslynDebug.Assert(algorithm != null);
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
return ImmutableArray.Create(algorithm.ComputeHash(stream));
}
}
/// <summary>
/// Provides a string representation of the SourceText.
/// </summary>
public override string ToString()
{
return ToString(new TextSpan(0, this.Length));
}
/// <summary>
/// Gets a string containing the characters in specified span.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception>
public virtual string ToString(TextSpan span)
{
CheckSubSpan(span);
// default implementation constructs text using CopyTo
var builder = new StringBuilder();
var buffer = new char[Math.Min(span.Length, 1024)];
int position = Math.Max(Math.Min(span.Start, this.Length), 0);
int length = Math.Min(span.End, this.Length) - position;
while (position < this.Length && length > 0)
{
int copyLength = Math.Min(buffer.Length, length);
this.CopyTo(position, buffer, 0, copyLength);
builder.Append(buffer, 0, copyLength);
length -= copyLength;
position += copyLength;
}
return builder.ToString();
}
#region Changes
/// <summary>
/// Constructs a new SourceText from this text with the specified changes.
/// </summary>
public virtual SourceText WithChanges(IEnumerable<TextChange> changes)
{
if (changes == null)
{
throw new ArgumentNullException(nameof(changes));
}
if (!changes.Any())
{
return this;
}
var segments = ArrayBuilder<SourceText>.GetInstance();
var changeRanges = ArrayBuilder<TextChangeRange>.GetInstance();
try
{
int position = 0;
foreach (var change in changes)
{
if (change.Span.End > this.Length)
throw new ArgumentException(CodeAnalysisResources.ChangesMustBeWithinBoundsOfSourceText, nameof(changes));
// there can be no overlapping changes
if (change.Span.Start < position)
{
// Handle the case of unordered changes by sorting the input and retrying. This is inefficient, but
// downstream consumers have been known to hit this case in the past and we want to avoid crashes.
// https://github.com/dotnet/roslyn/pull/26339
if (change.Span.End <= changeRanges.Last().Span.Start)
{
changes = (from c in changes
where !c.Span.IsEmpty || c.NewText?.Length > 0
orderby c.Span
select c).ToList();
return WithChanges(changes);
}
throw new ArgumentException(CodeAnalysisResources.ChangesMustNotOverlap, nameof(changes));
}
var newTextLength = change.NewText?.Length ?? 0;
// ignore changes that don't change anything
if (change.Span.Length == 0 && newTextLength == 0)
continue;
// if we've skipped a range, add
if (change.Span.Start > position)
{
var subText = this.GetSubText(new TextSpan(position, change.Span.Start - position));
CompositeText.AddSegments(segments, subText);
}
if (newTextLength > 0)
{
var segment = SourceText.From(change.NewText!, this.Encoding, this.ChecksumAlgorithm);
CompositeText.AddSegments(segments, segment);
}
position = change.Span.End;
changeRanges.Add(new TextChangeRange(change.Span, newTextLength));
}
// no changes actually happened?
if (position == 0 && segments.Count == 0)
{
return this;
}
if (position < this.Length)
{
var subText = this.GetSubText(new TextSpan(position, this.Length - position));
CompositeText.AddSegments(segments, subText);
}
var newText = CompositeText.ToSourceText(segments, this, adjustSegments: true);
if (newText != this)
{
return new ChangedText(this, newText, changeRanges.ToImmutable());
}
else
{
return this;
}
}
finally
{
segments.Free();
changeRanges.Free();
}
}
/// <summary>
/// Constructs a new SourceText from this text with the specified changes.
/// <exception cref="ArgumentException">If any changes are not in bounds of this <see cref="SourceText"/>.</exception>
/// <exception cref="ArgumentException">If any changes overlap other changes.</exception>
/// </summary>
/// <remarks>
/// Changes do not have to be in sorted order. However, <see cref="WithChanges(IEnumerable{TextChange})"/> will
/// perform better if they are.
/// </remarks>
public SourceText WithChanges(params TextChange[] changes)
{
return this.WithChanges((IEnumerable<TextChange>)changes);
}
/// <summary>
/// Returns a new SourceText with the specified span of characters replaced by the new text.
/// </summary>
public SourceText Replace(TextSpan span, string newText)
{
return this.WithChanges(new TextChange(span, newText));
}
/// <summary>
/// Returns a new SourceText with the specified range of characters replaced by the new text.
/// </summary>
public SourceText Replace(int start, int length, string newText)
{
return this.Replace(new TextSpan(start, length), newText);
}
/// <summary>
/// Gets the set of <see cref="TextChangeRange"/> that describe how the text changed
/// between this text an older version. This may be multiple detailed changes
/// or a single change encompassing the entire text.
/// </summary>
public virtual IReadOnlyList<TextChangeRange> GetChangeRanges(SourceText oldText)
{
if (oldText == null)
{
throw new ArgumentNullException(nameof(oldText));
}
if (oldText == this)
{
return TextChangeRange.NoChanges;
}
else
{
return ImmutableArray.Create(new TextChangeRange(new TextSpan(0, oldText.Length), this.Length));
}
}
/// <summary>
/// Gets the set of <see cref="TextChange"/> that describe how the text changed
/// between this text and an older version. This may be multiple detailed changes
/// or a single change encompassing the entire text.
/// </summary>
public virtual IReadOnlyList<TextChange> GetTextChanges(SourceText oldText)
{
int newPosDelta = 0;
var ranges = this.GetChangeRanges(oldText).ToList();
var textChanges = new List<TextChange>(ranges.Count);
foreach (var range in ranges)
{
var newPos = range.Span.Start + newPosDelta;
// determine where in the newText this text exists
string newt;
if (range.NewLength > 0)
{
var span = new TextSpan(newPos, range.NewLength);
newt = this.ToString(span);
}
else
{
newt = string.Empty;
}
textChanges.Add(new TextChange(range.Span, newt));
newPosDelta += range.NewLength - range.Span.Length;
}
return textChanges.ToImmutableArrayOrEmpty();
}
#endregion
#region Lines
/// <summary>
/// The collection of individual text lines.
/// </summary>
public TextLineCollection Lines
{
get
{
var info = _lazyLineInfo;
return info ?? Interlocked.CompareExchange(ref _lazyLineInfo, info = GetLinesCore(), null) ?? info;
}
}
internal bool TryGetLines([NotNullWhen(returnValue: true)] out TextLineCollection? lines)
{
lines = _lazyLineInfo;
return lines != null;
}
/// <summary>
/// Called from <see cref="Lines"/> to initialize the <see cref="TextLineCollection"/>. Thereafter,
/// the collection is cached.
/// </summary>
/// <returns>A new <see cref="TextLineCollection"/> representing the individual text lines.</returns>
protected virtual TextLineCollection GetLinesCore()
{
return new LineInfo(this, ParseLineStarts());
}
internal sealed class LineInfo : TextLineCollection
{
private readonly SourceText _text;
private readonly int[] _lineStarts;
private int _lastLineNumber;
public LineInfo(SourceText text, int[] lineStarts)
{
_text = text;
_lineStarts = lineStarts;
}
public override int Count => _lineStarts.Length;
public override TextLine this[int index]
{
get
{
if (index < 0 || index >= _lineStarts.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
int start = _lineStarts[index];
if (index == _lineStarts.Length - 1)
{
return TextLine.FromSpan(_text, TextSpan.FromBounds(start, _text.Length));
}
else
{
int end = _lineStarts[index + 1];
return TextLine.FromSpan(_text, TextSpan.FromBounds(start, end));
}
}
}
public override int IndexOf(int position)
{
if (position < 0 || position > _text.Length)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
int lineNumber;
// it is common to ask about position on the same line
// as before or on the next couple lines
var lastLineNumber = _lastLineNumber;
if (position >= _lineStarts[lastLineNumber])
{
var limit = Math.Min(_lineStarts.Length, lastLineNumber + 4);
for (int i = lastLineNumber; i < limit; i++)
{
if (position < _lineStarts[i])
{
lineNumber = i - 1;
_lastLineNumber = lineNumber;
return lineNumber;
}
}
}
// Binary search to find the right line
// if no lines start exactly at position, round to the left
// EoF position will map to the last line.
lineNumber = _lineStarts.BinarySearch(position);
if (lineNumber < 0)
{
lineNumber = (~lineNumber) - 1;
}
_lastLineNumber = lineNumber;
return lineNumber;
}
public override TextLine GetLineFromPosition(int position)
{
return this[IndexOf(position)];
}
}
private void EnumerateChars(Action<int, char[], int> action)
{
var position = 0;
var buffer = s_charArrayPool.Allocate();
var length = this.Length;
while (position < length)
{
var contentLength = Math.Min(length - position, buffer.Length);
this.CopyTo(position, buffer, 0, contentLength);
action(position, buffer, contentLength);
position += contentLength;
}
// once more with zero length to signal the end
action(position, buffer, 0);
s_charArrayPool.Free(buffer);
}
private int[] ParseLineStarts()
{
// Corner case check
if (0 == this.Length)
{
return new[] { 0 };
}
var lineStarts = ArrayBuilder<int>.GetInstance();
lineStarts.Add(0); // there is always the first line
var lastWasCR = false;
// The following loop goes through every character in the text. It is highly
// performance critical, and thus inlines knowledge about common line breaks
// and non-line breaks.
EnumerateChars((int position, char[] buffer, int length) =>
{
var index = 0;
if (lastWasCR)
{
if (length > 0 && buffer[0] == '\n')
{
index++;
}
lineStarts.Add(position + index);
lastWasCR = false;
}
while (index < length)
{
char c = buffer[index];
index++;
// Common case - ASCII & not a line break
// if (c > '\r' && c <= 127)
// if (c >= ('\r'+1) && c <= 127)
const uint bias = '\r' + 1;
if (unchecked(c - bias) <= (127 - bias))
{
continue;
}
// Assumes that the only 2-char line break sequence is CR+LF
if (c == '\r')
{
if (index < length && buffer[index] == '\n')
{
index++;
}
else if (index >= length)
{
lastWasCR = true;
continue;
}
}
else if (!TextUtilities.IsAnyLineBreakCharacter(c))
{
continue;
}
// next line starts at index
lineStarts.Add(position + index);
}
});
return lineStarts.ToArrayAndFree();
}
#endregion
/// <summary>
/// Compares the content with content of another <see cref="SourceText"/>.
/// </summary>
public bool ContentEquals(SourceText other)
{
if (ReferenceEquals(this, other))
{
return true;
}
// Checksum may be provided by a subclass, which is thus responsible for passing us a true hash.
ImmutableArray<byte> leftChecksum = _lazyChecksum;
ImmutableArray<byte> rightChecksum = other._lazyChecksum;
if (!leftChecksum.IsDefault && !rightChecksum.IsDefault && this.Encoding == other.Encoding && this.ChecksumAlgorithm == other.ChecksumAlgorithm)
{
return leftChecksum.SequenceEqual(rightChecksum);
}
return ContentEqualsImpl(other);
}
/// <summary>
/// Implements equality comparison of the content of two different instances of <see cref="SourceText"/>.
/// </summary>
protected virtual bool ContentEqualsImpl(SourceText other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (this.Length != other.Length)
{
return false;
}
var buffer1 = s_charArrayPool.Allocate();
var buffer2 = s_charArrayPool.Allocate();
try
{
int position = 0;
while (position < this.Length)
{
int n = Math.Min(this.Length - position, buffer1.Length);
this.CopyTo(position, buffer1, 0, n);
other.CopyTo(position, buffer2, 0, n);
for (int i = 0; i < n; i++)
{
if (buffer1[i] != buffer2[i])
{
return false;
}
}
position += n;
}
return true;
}
finally
{
s_charArrayPool.Free(buffer2);
s_charArrayPool.Free(buffer1);
}
}
/// <summary>
/// Detect an encoding by looking for byte order marks.
/// </summary>
/// <param name="source">A buffer containing the encoded text.</param>
/// <param name="length">The length of valid data in the buffer.</param>
/// <param name="preambleLength">The length of any detected byte order marks.</param>
/// <returns>The detected encoding or null if no recognized byte order mark was present.</returns>
internal static Encoding? TryReadByteOrderMark(byte[] source, int length, out int preambleLength)
{
RoslynDebug.Assert(source != null);
Debug.Assert(length <= source.Length);
if (length >= 2)
{
switch (source[0])
{
case 0xFE:
if (source[1] == 0xFF)
{
preambleLength = 2;
return Encoding.BigEndianUnicode;
}
break;
case 0xFF:
if (source[1] == 0xFE)
{
preambleLength = 2;
return Encoding.Unicode;
}
break;
case 0xEF:
if (source[1] == 0xBB && length >= 3 && source[2] == 0xBF)
{
preambleLength = 3;
return Encoding.UTF8;
}
break;
}
}
preambleLength = 0;
return null;
}
private class StaticContainer : SourceTextContainer
{
private readonly SourceText _text;
public StaticContainer(SourceText text)
{
_text = text;
}
public override SourceText CurrentText => _text;
public override event EventHandler<TextChangeEventArgs> TextChanged
{
add
{
// do nothing
}
remove
{
// do nothing
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// An abstraction of source text.
/// </summary>
public abstract class SourceText
{
private const int CharBufferSize = 32 * 1024;
private const int CharBufferCount = 5;
internal const int LargeObjectHeapLimitInChars = 40 * 1024; // 40KB
private static readonly ObjectPool<char[]> s_charArrayPool = new ObjectPool<char[]>(() => new char[CharBufferSize], CharBufferCount);
private readonly SourceHashAlgorithm _checksumAlgorithm;
private SourceTextContainer? _lazyContainer;
private TextLineCollection? _lazyLineInfo;
private ImmutableArray<byte> _lazyChecksum;
private ImmutableArray<byte> _precomputedEmbeddedTextBlob;
private static readonly Encoding s_utf8EncodingWithNoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false);
protected SourceText(ImmutableArray<byte> checksum = default(ImmutableArray<byte>), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, SourceTextContainer? container = null)
{
ValidateChecksumAlgorithm(checksumAlgorithm);
if (!checksum.IsDefault && checksum.Length != CryptographicHashProvider.GetHashSize(checksumAlgorithm))
{
throw new ArgumentException(CodeAnalysisResources.InvalidHash, nameof(checksum));
}
_checksumAlgorithm = checksumAlgorithm;
_lazyChecksum = checksum;
_lazyContainer = container;
}
internal SourceText(ImmutableArray<byte> checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray<byte> embeddedTextBlob)
: this(checksum, checksumAlgorithm, container: null)
{
// We should never have precomputed the embedded text blob without precomputing the checksum.
Debug.Assert(embeddedTextBlob.IsDefault || !checksum.IsDefault);
if (!checksum.IsDefault && embeddedTextBlob.IsDefault)
{
// We can't compute the embedded text blob lazily if we're given a precomputed checksum.
// This happens when source bytes/stream were given, but canBeEmbedded=true was not passed.
_precomputedEmbeddedTextBlob = ImmutableArray<byte>.Empty;
}
else
{
_precomputedEmbeddedTextBlob = embeddedTextBlob;
}
}
internal static void ValidateChecksumAlgorithm(SourceHashAlgorithm checksumAlgorithm)
{
if (!SourceHashAlgorithms.IsSupportedAlgorithm(checksumAlgorithm))
{
throw new ArgumentException(CodeAnalysisResources.UnsupportedHashAlgorithm, nameof(checksumAlgorithm));
}
}
/// <summary>
/// Constructs a <see cref="SourceText"/> from text in a string.
/// </summary>
/// <param name="text">Text.</param>
/// <param name="encoding">
/// Encoding of the file that the <paramref name="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 resulting <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="ArgumentNullException"><paramref name="text"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public static SourceText From(string text, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
return new StringText(text, encoding, checksumAlgorithm: checksumAlgorithm);
}
/// <summary>
/// Constructs a <see cref="SourceText"/> from text in a string.
/// </summary>
/// <param name="reader">TextReader</param>
/// <param name="length">length of content from <paramref name="reader"/></param>
/// <param name="encoding">
/// Encoding of the file that the <paramref name="reader"/> 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 resulting <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="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public static SourceText From(
TextReader reader,
int length,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
// If the resulting string would end up on the large object heap, then use LargeEncodedText.
if (length >= LargeObjectHeapLimitInChars)
{
return LargeText.Decode(reader, length, encoding, checksumAlgorithm);
}
string text = reader.ReadToEnd();
return From(text, encoding, checksumAlgorithm);
}
// 1.0 BACKCOMPAT OVERLOAD - DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static SourceText From(Stream stream, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
=> From(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded: false);
/// <summary>
/// Constructs a <see cref="SourceText"/> from stream content.
/// </summary>
/// <param name="stream">Stream. The stream must be seekable.</param>
/// <param name="encoding">
/// Data encoding to use if the stream doesn't start with Byte Order Mark specifying the encoding.
/// <see cref="Encoding.UTF8"/> if not specified.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <param name="throwIfBinaryDetected">If the decoded text contains at least two consecutive NUL
/// characters, then an <see cref="InvalidDataException"/> is thrown.</param>
/// <param name="canBeEmbedded">True if the text can be passed to <see cref="EmbeddedText.FromSource"/> and be embedded in a PDB.</param>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> doesn't support reading or seeking.
/// <paramref name="checksumAlgorithm"/> is not supported.
/// </exception>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
/// <exception cref="InvalidDataException">Two consecutive NUL characters were detected in the decoded text and <paramref name="throwIfBinaryDetected"/> was true.</exception>
/// <exception cref="IOException">An I/O error occurs.</exception>
/// <remarks>Reads from the beginning of the stream. Leaves the stream open.</remarks>
public static SourceText From(
Stream stream,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,
bool throwIfBinaryDetected = false,
bool canBeEmbedded = false)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(stream));
}
ValidateChecksumAlgorithm(checksumAlgorithm);
encoding = encoding ?? s_utf8EncodingWithNoBOM;
if (stream.CanSeek)
{
// If the resulting string would end up on the large object heap, then use LargeEncodedText.
if (encoding.GetMaxCharCountOrThrowIfHuge(stream) >= LargeObjectHeapLimitInChars)
{
return LargeText.Decode(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
}
}
string text = Decode(stream, encoding, out encoding);
if (throwIfBinaryDetected && IsBinary(text))
{
throw new InvalidDataException();
}
// We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
// We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
var checksum = CalculateChecksum(stream, checksumAlgorithm);
var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(stream) : default(ImmutableArray<byte>);
return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob);
}
// 1.0 BACKCOMPAT OVERLOAD - DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static SourceText From(byte[] buffer, int length, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
=> From(buffer, length, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded: false);
/// <summary>
/// Constructs a <see cref="SourceText"/> from a byte array.
/// </summary>
/// <param name="buffer">The encoded source buffer.</param>
/// <param name="length">The number of bytes to read from the buffer.</param>
/// <param name="encoding">
/// Data encoding to use if the encoded buffer doesn't start with Byte Order Mark.
/// <see cref="Encoding.UTF8"/> if not specified.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <param name="throwIfBinaryDetected">If the decoded text contains at least two consecutive NUL
/// characters, then an <see cref="InvalidDataException"/> is thrown.</param>
/// <returns>The decoded text.</returns>
/// <param name="canBeEmbedded">True if the text can be passed to <see cref="EmbeddedText.FromSource"/> and be embedded in a PDB.</param>
/// <exception cref="ArgumentNullException">The <paramref name="buffer"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="length"/> is negative or longer than the <paramref name="buffer"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
/// <exception cref="InvalidDataException">Two consecutive NUL characters were detected in the decoded text and <paramref name="throwIfBinaryDetected"/> was true.</exception>
public static SourceText From(
byte[] buffer,
int length,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,
bool throwIfBinaryDetected = false,
bool canBeEmbedded = false)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (length < 0 || length > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
ValidateChecksumAlgorithm(checksumAlgorithm);
string text = Decode(buffer, length, encoding ?? s_utf8EncodingWithNoBOM, out encoding);
if (throwIfBinaryDetected && IsBinary(text))
{
throw new InvalidDataException();
}
// We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
// We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
var checksum = CalculateChecksum(buffer, 0, length, checksumAlgorithm);
var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(new ArraySegment<byte>(buffer, 0, length)) : default(ImmutableArray<byte>);
return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob);
}
/// <summary>
/// Decode text from a stream.
/// </summary>
/// <param name="stream">The stream containing encoded text.</param>
/// <param name="encoding">The encoding to use if an encoding cannot be determined from the byte order mark.</param>
/// <param name="actualEncoding">The actual encoding used.</param>
/// <returns>The decoded text.</returns>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
private static string Decode(Stream stream, Encoding encoding, out Encoding actualEncoding)
{
RoslynDebug.Assert(stream != null);
RoslynDebug.Assert(encoding != null);
const int maxBufferSize = 4096;
int bufferSize = maxBufferSize;
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
int length = (int)stream.Length;
if (length == 0)
{
actualEncoding = encoding;
return string.Empty;
}
bufferSize = Math.Min(maxBufferSize, length);
}
// Note: We are setting the buffer size to 4KB instead of the default 1KB. That's
// because we can reach this code path for FileStreams and, to avoid FileStream
// buffer allocations for small files, we may intentionally be using a FileStream
// with a very small (1 byte) buffer. Using 4KB here matches the default buffer
// size for FileStream and means we'll still be doing file I/O in 4KB chunks.
using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: bufferSize, leaveOpen: true))
{
string text = reader.ReadToEnd();
actualEncoding = reader.CurrentEncoding;
return text;
}
}
/// <summary>
/// Decode text from a byte array.
/// </summary>
/// <param name="buffer">The byte array containing encoded text.</param>
/// <param name="length">The count of valid bytes in <paramref name="buffer"/>.</param>
/// <param name="encoding">The encoding to use if an encoding cannot be determined from the byte order mark.</param>
/// <param name="actualEncoding">The actual encoding used.</param>
/// <returns>The decoded text.</returns>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
private static string Decode(byte[] buffer, int length, Encoding encoding, out Encoding actualEncoding)
{
RoslynDebug.Assert(buffer != null);
RoslynDebug.Assert(encoding != null);
int preambleLength;
actualEncoding = TryReadByteOrderMark(buffer, length, out preambleLength) ?? encoding;
return actualEncoding.GetString(buffer, preambleLength, length - preambleLength);
}
/// <summary>
/// Check for occurrence of two consecutive NUL (U+0000) characters.
/// This is unlikely to appear in genuine text, so it's a good heuristic
/// to detect binary files.
/// </summary>
/// <remarks>
/// internal for unit testing
/// </remarks>
internal static bool IsBinary(string text)
{
// PERF: We can advance two chars at a time unless we find a NUL.
for (int i = 1; i < text.Length;)
{
if (text[i] == '\0')
{
if (text[i - 1] == '\0')
{
return true;
}
i += 1;
}
else
{
i += 2;
}
}
return false;
}
/// <summary>
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </summary>
public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm;
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// If the encoding is not specified the source 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.
/// </remarks>
public abstract Encoding? Encoding { get; }
/// <summary>
/// The length of the text in characters.
/// </summary>
public abstract int Length { get; }
/// <summary>
/// The size of the storage representation of the text (in characters).
/// This can differ from length when storage buffers are reused to represent fragments/subtext.
/// </summary>
internal virtual int StorageSize
{
get { return this.Length; }
}
internal virtual ImmutableArray<SourceText> Segments
{
get { return ImmutableArray<SourceText>.Empty; }
}
internal virtual SourceText StorageKey
{
get { return this; }
}
/// <summary>
/// Indicates whether this source text can be embedded in the PDB.
/// </summary>
/// <remarks>
/// If this text was constructed via <see cref="From(byte[], int, Encoding, SourceHashAlgorithm, bool, bool)"/> or
/// <see cref="From(Stream, Encoding, SourceHashAlgorithm, bool, bool)"/>, then the canBeEmbedded arg must have
/// been true.
///
/// Otherwise, <see cref="Encoding" /> must be non-null.
/// </remarks>
public bool CanBeEmbedded
{
get
{
if (_precomputedEmbeddedTextBlob.IsDefault)
{
// If we didn't precompute the embedded text blob from bytes/stream,
// we can only support embedding if we have an encoding with which
// to encode the text in the PDB.
return Encoding != null;
}
// We use a sentinel empty blob to indicate that embedding has been disallowed.
return !_precomputedEmbeddedTextBlob.IsEmpty;
}
}
/// <summary>
/// If the text was created from a stream or byte[] and canBeEmbedded argument was true,
/// this provides the embedded text blob that was precomputed using the original stream
/// or byte[]. The precomputation was required in that case so that the bytes written to
/// the PDB match the original bytes exactly (and match the checksum of the original
/// bytes).
/// </summary>
internal ImmutableArray<byte> PrecomputedEmbeddedTextBlob => _precomputedEmbeddedTextBlob;
/// <summary>
/// Returns a character at given position.
/// </summary>
/// <param name="position">The position to get the character from.</param>
/// <returns>The character.</returns>
/// <exception cref="ArgumentOutOfRangeException">When position is negative or
/// greater than <see cref="Length"/>.</exception>
public abstract char this[int position] { get; }
/// <summary>
/// Copy a range of characters from this SourceText to a destination array.
/// </summary>
public abstract void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
/// <summary>
/// The container of this <see cref="SourceText"/>.
/// </summary>
public virtual SourceTextContainer Container
{
get
{
if (_lazyContainer == null)
{
Interlocked.CompareExchange(ref _lazyContainer, new StaticContainer(this), null);
}
return _lazyContainer;
}
}
internal void CheckSubSpan(TextSpan span)
{
Debug.Assert(0 <= span.Start && span.Start <= span.End);
if (span.End > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(span));
}
}
/// <summary>
/// Gets a <see cref="SourceText"/> that contains the characters in the specified span of this text.
/// </summary>
public virtual SourceText GetSubText(TextSpan span)
{
CheckSubSpan(span);
int spanLength = span.Length;
if (spanLength == 0)
{
return SourceText.From(string.Empty, this.Encoding, this.ChecksumAlgorithm);
}
else if (spanLength == this.Length && span.Start == 0)
{
return this;
}
else
{
return new SubText(this, span);
}
}
/// <summary>
/// Returns a <see cref="SourceText"/> that has the contents of this text including and after the start position.
/// </summary>
public SourceText GetSubText(int start)
{
if (start < 0 || start > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(start));
}
if (start == 0)
{
return this;
}
else
{
return this.GetSubText(new TextSpan(start, this.Length - start));
}
}
/// <summary>
/// Write this <see cref="SourceText"/> to a text writer.
/// </summary>
public void Write(TextWriter textWriter, CancellationToken cancellationToken = default(CancellationToken))
{
this.Write(textWriter, new TextSpan(0, this.Length), cancellationToken);
}
/// <summary>
/// Write a span of text to a text writer.
/// </summary>
public virtual void Write(TextWriter writer, TextSpan span, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSubSpan(span);
var buffer = s_charArrayPool.Allocate();
try
{
int offset = span.Start;
int end = span.End;
while (offset < end)
{
cancellationToken.ThrowIfCancellationRequested();
int count = Math.Min(buffer.Length, end - offset);
this.CopyTo(offset, buffer, 0, count);
writer.Write(buffer, 0, count);
offset += count;
}
}
finally
{
s_charArrayPool.Free(buffer);
}
}
public ImmutableArray<byte> GetChecksum()
{
if (_lazyChecksum.IsDefault)
{
using (var stream = new SourceTextStream(this, useDefaultEncodingIfNull: true))
{
ImmutableInterlocked.InterlockedInitialize(ref _lazyChecksum, CalculateChecksum(stream, _checksumAlgorithm));
}
}
return _lazyChecksum;
}
internal static ImmutableArray<byte> CalculateChecksum(byte[] buffer, int offset, int count, SourceHashAlgorithm algorithmId)
{
using (var algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
{
RoslynDebug.Assert(algorithm != null);
return ImmutableArray.Create(algorithm.ComputeHash(buffer, offset, count));
}
}
internal static ImmutableArray<byte> CalculateChecksum(Stream stream, SourceHashAlgorithm algorithmId)
{
using (var algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
{
RoslynDebug.Assert(algorithm != null);
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
return ImmutableArray.Create(algorithm.ComputeHash(stream));
}
}
/// <summary>
/// Provides a string representation of the SourceText.
/// </summary>
public override string ToString()
{
return ToString(new TextSpan(0, this.Length));
}
/// <summary>
/// Gets a string containing the characters in specified span.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception>
public virtual string ToString(TextSpan span)
{
CheckSubSpan(span);
// default implementation constructs text using CopyTo
var builder = new StringBuilder();
var buffer = new char[Math.Min(span.Length, 1024)];
int position = Math.Max(Math.Min(span.Start, this.Length), 0);
int length = Math.Min(span.End, this.Length) - position;
while (position < this.Length && length > 0)
{
int copyLength = Math.Min(buffer.Length, length);
this.CopyTo(position, buffer, 0, copyLength);
builder.Append(buffer, 0, copyLength);
length -= copyLength;
position += copyLength;
}
return builder.ToString();
}
#region Changes
/// <summary>
/// Constructs a new SourceText from this text with the specified changes.
/// </summary>
public virtual SourceText WithChanges(IEnumerable<TextChange> changes)
{
if (changes == null)
{
throw new ArgumentNullException(nameof(changes));
}
if (!changes.Any())
{
return this;
}
var segments = ArrayBuilder<SourceText>.GetInstance();
var changeRanges = ArrayBuilder<TextChangeRange>.GetInstance();
try
{
int position = 0;
foreach (var change in changes)
{
if (change.Span.End > this.Length)
throw new ArgumentException(CodeAnalysisResources.ChangesMustBeWithinBoundsOfSourceText, nameof(changes));
// there can be no overlapping changes
if (change.Span.Start < position)
{
// Handle the case of unordered changes by sorting the input and retrying. This is inefficient, but
// downstream consumers have been known to hit this case in the past and we want to avoid crashes.
// https://github.com/dotnet/roslyn/pull/26339
if (change.Span.End <= changeRanges.Last().Span.Start)
{
changes = (from c in changes
where !c.Span.IsEmpty || c.NewText?.Length > 0
orderby c.Span
select c).ToList();
return WithChanges(changes);
}
throw new ArgumentException(CodeAnalysisResources.ChangesMustNotOverlap, nameof(changes));
}
var newTextLength = change.NewText?.Length ?? 0;
// ignore changes that don't change anything
if (change.Span.Length == 0 && newTextLength == 0)
continue;
// if we've skipped a range, add
if (change.Span.Start > position)
{
var subText = this.GetSubText(new TextSpan(position, change.Span.Start - position));
CompositeText.AddSegments(segments, subText);
}
if (newTextLength > 0)
{
var segment = SourceText.From(change.NewText!, this.Encoding, this.ChecksumAlgorithm);
CompositeText.AddSegments(segments, segment);
}
position = change.Span.End;
changeRanges.Add(new TextChangeRange(change.Span, newTextLength));
}
// no changes actually happened?
if (position == 0 && segments.Count == 0)
{
return this;
}
if (position < this.Length)
{
var subText = this.GetSubText(new TextSpan(position, this.Length - position));
CompositeText.AddSegments(segments, subText);
}
var newText = CompositeText.ToSourceText(segments, this, adjustSegments: true);
if (newText != this)
{
return new ChangedText(this, newText, changeRanges.ToImmutable());
}
else
{
return this;
}
}
finally
{
segments.Free();
changeRanges.Free();
}
}
/// <summary>
/// Constructs a new SourceText from this text with the specified changes.
/// <exception cref="ArgumentException">If any changes are not in bounds of this <see cref="SourceText"/>.</exception>
/// <exception cref="ArgumentException">If any changes overlap other changes.</exception>
/// </summary>
/// <remarks>
/// Changes do not have to be in sorted order. However, <see cref="WithChanges(IEnumerable{TextChange})"/> will
/// perform better if they are.
/// </remarks>
public SourceText WithChanges(params TextChange[] changes)
{
return this.WithChanges((IEnumerable<TextChange>)changes);
}
/// <summary>
/// Returns a new SourceText with the specified span of characters replaced by the new text.
/// </summary>
public SourceText Replace(TextSpan span, string newText)
{
return this.WithChanges(new TextChange(span, newText));
}
/// <summary>
/// Returns a new SourceText with the specified range of characters replaced by the new text.
/// </summary>
public SourceText Replace(int start, int length, string newText)
{
return this.Replace(new TextSpan(start, length), newText);
}
/// <summary>
/// Gets the set of <see cref="TextChangeRange"/> that describe how the text changed
/// between this text an older version. This may be multiple detailed changes
/// or a single change encompassing the entire text.
/// </summary>
public virtual IReadOnlyList<TextChangeRange> GetChangeRanges(SourceText oldText)
{
if (oldText == null)
{
throw new ArgumentNullException(nameof(oldText));
}
if (oldText == this)
{
return TextChangeRange.NoChanges;
}
else
{
return ImmutableArray.Create(new TextChangeRange(new TextSpan(0, oldText.Length), this.Length));
}
}
/// <summary>
/// Gets the set of <see cref="TextChange"/> that describe how the text changed
/// between this text and an older version. This may be multiple detailed changes
/// or a single change encompassing the entire text.
/// </summary>
public virtual IReadOnlyList<TextChange> GetTextChanges(SourceText oldText)
{
int newPosDelta = 0;
var ranges = this.GetChangeRanges(oldText).ToList();
var textChanges = new List<TextChange>(ranges.Count);
foreach (var range in ranges)
{
var newPos = range.Span.Start + newPosDelta;
// determine where in the newText this text exists
string newt;
if (range.NewLength > 0)
{
var span = new TextSpan(newPos, range.NewLength);
newt = this.ToString(span);
}
else
{
newt = string.Empty;
}
textChanges.Add(new TextChange(range.Span, newt));
newPosDelta += range.NewLength - range.Span.Length;
}
return textChanges.ToImmutableArrayOrEmpty();
}
#endregion
#region Lines
/// <summary>
/// The collection of individual text lines.
/// </summary>
public TextLineCollection Lines
{
get
{
var info = _lazyLineInfo;
return info ?? Interlocked.CompareExchange(ref _lazyLineInfo, info = GetLinesCore(), null) ?? info;
}
}
internal bool TryGetLines([NotNullWhen(returnValue: true)] out TextLineCollection? lines)
{
lines = _lazyLineInfo;
return lines != null;
}
/// <summary>
/// Called from <see cref="Lines"/> to initialize the <see cref="TextLineCollection"/>. Thereafter,
/// the collection is cached.
/// </summary>
/// <returns>A new <see cref="TextLineCollection"/> representing the individual text lines.</returns>
protected virtual TextLineCollection GetLinesCore()
{
return new LineInfo(this, ParseLineStarts());
}
internal sealed class LineInfo : TextLineCollection
{
private readonly SourceText _text;
private readonly int[] _lineStarts;
private int _lastLineNumber;
public LineInfo(SourceText text, int[] lineStarts)
{
_text = text;
_lineStarts = lineStarts;
}
public override int Count => _lineStarts.Length;
public override TextLine this[int index]
{
get
{
if (index < 0 || index >= _lineStarts.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
int start = _lineStarts[index];
if (index == _lineStarts.Length - 1)
{
return TextLine.FromSpan(_text, TextSpan.FromBounds(start, _text.Length));
}
else
{
int end = _lineStarts[index + 1];
return TextLine.FromSpan(_text, TextSpan.FromBounds(start, end));
}
}
}
public override int IndexOf(int position)
{
if (position < 0 || position > _text.Length)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
int lineNumber;
// it is common to ask about position on the same line
// as before or on the next couple lines
var lastLineNumber = _lastLineNumber;
if (position >= _lineStarts[lastLineNumber])
{
var limit = Math.Min(_lineStarts.Length, lastLineNumber + 4);
for (int i = lastLineNumber; i < limit; i++)
{
if (position < _lineStarts[i])
{
lineNumber = i - 1;
_lastLineNumber = lineNumber;
return lineNumber;
}
}
}
// Binary search to find the right line
// if no lines start exactly at position, round to the left
// EoF position will map to the last line.
lineNumber = _lineStarts.BinarySearch(position);
if (lineNumber < 0)
{
lineNumber = (~lineNumber) - 1;
}
_lastLineNumber = lineNumber;
return lineNumber;
}
public override TextLine GetLineFromPosition(int position)
{
return this[IndexOf(position)];
}
}
private void EnumerateChars(Action<int, char[], int> action)
{
var position = 0;
var buffer = s_charArrayPool.Allocate();
var length = this.Length;
while (position < length)
{
var contentLength = Math.Min(length - position, buffer.Length);
this.CopyTo(position, buffer, 0, contentLength);
action(position, buffer, contentLength);
position += contentLength;
}
// once more with zero length to signal the end
action(position, buffer, 0);
s_charArrayPool.Free(buffer);
}
private int[] ParseLineStarts()
{
// Corner case check
if (0 == this.Length)
{
return new[] { 0 };
}
var lineStarts = ArrayBuilder<int>.GetInstance();
lineStarts.Add(0); // there is always the first line
var lastWasCR = false;
// The following loop goes through every character in the text. It is highly
// performance critical, and thus inlines knowledge about common line breaks
// and non-line breaks.
EnumerateChars((int position, char[] buffer, int length) =>
{
var index = 0;
if (lastWasCR)
{
if (length > 0 && buffer[0] == '\n')
{
index++;
}
lineStarts.Add(position + index);
lastWasCR = false;
}
while (index < length)
{
char c = buffer[index];
index++;
// Common case - ASCII & not a line break
// if (c > '\r' && c <= 127)
// if (c >= ('\r'+1) && c <= 127)
const uint bias = '\r' + 1;
if (unchecked(c - bias) <= (127 - bias))
{
continue;
}
// Assumes that the only 2-char line break sequence is CR+LF
if (c == '\r')
{
if (index < length && buffer[index] == '\n')
{
index++;
}
else if (index >= length)
{
lastWasCR = true;
continue;
}
}
else if (!TextUtilities.IsAnyLineBreakCharacter(c))
{
continue;
}
// next line starts at index
lineStarts.Add(position + index);
}
});
return lineStarts.ToArrayAndFree();
}
#endregion
/// <summary>
/// Compares the content with content of another <see cref="SourceText"/>.
/// </summary>
public bool ContentEquals(SourceText other)
{
if (ReferenceEquals(this, other))
{
return true;
}
// Checksum may be provided by a subclass, which is thus responsible for passing us a true hash.
ImmutableArray<byte> leftChecksum = _lazyChecksum;
ImmutableArray<byte> rightChecksum = other._lazyChecksum;
if (!leftChecksum.IsDefault && !rightChecksum.IsDefault && this.Encoding == other.Encoding && this.ChecksumAlgorithm == other.ChecksumAlgorithm)
{
return leftChecksum.SequenceEqual(rightChecksum);
}
return ContentEqualsImpl(other);
}
/// <summary>
/// Implements equality comparison of the content of two different instances of <see cref="SourceText"/>.
/// </summary>
protected virtual bool ContentEqualsImpl(SourceText other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (this.Length != other.Length)
{
return false;
}
var buffer1 = s_charArrayPool.Allocate();
var buffer2 = s_charArrayPool.Allocate();
try
{
int position = 0;
while (position < this.Length)
{
int n = Math.Min(this.Length - position, buffer1.Length);
this.CopyTo(position, buffer1, 0, n);
other.CopyTo(position, buffer2, 0, n);
for (int i = 0; i < n; i++)
{
if (buffer1[i] != buffer2[i])
{
return false;
}
}
position += n;
}
return true;
}
finally
{
s_charArrayPool.Free(buffer2);
s_charArrayPool.Free(buffer1);
}
}
/// <summary>
/// Detect an encoding by looking for byte order marks.
/// </summary>
/// <param name="source">A buffer containing the encoded text.</param>
/// <param name="length">The length of valid data in the buffer.</param>
/// <param name="preambleLength">The length of any detected byte order marks.</param>
/// <returns>The detected encoding or null if no recognized byte order mark was present.</returns>
internal static Encoding? TryReadByteOrderMark(byte[] source, int length, out int preambleLength)
{
RoslynDebug.Assert(source != null);
Debug.Assert(length <= source.Length);
if (length >= 2)
{
switch (source[0])
{
case 0xFE:
if (source[1] == 0xFF)
{
preambleLength = 2;
return Encoding.BigEndianUnicode;
}
break;
case 0xFF:
if (source[1] == 0xFE)
{
preambleLength = 2;
return Encoding.Unicode;
}
break;
case 0xEF:
if (source[1] == 0xBB && length >= 3 && source[2] == 0xBF)
{
preambleLength = 3;
return Encoding.UTF8;
}
break;
}
}
preambleLength = 0;
return null;
}
private class StaticContainer : SourceTextContainer
{
private readonly SourceText _text;
public StaticContainer(SourceText text)
{
_text = text;
}
public override SourceText CurrentText => _text;
public override event EventHandler<TextChangeEventArgs> TextChanged
{
add
{
// do nothing
}
remove
{
// do nothing
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.IVbEntryPointProvider.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 System.Threading
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
Imports Microsoft.VisualStudio.Shell.Interop
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
Partial Friend Class VisualBasicPackage
Implements IVBEntryPointProvider
Public Function GetFormEntryPointsList(<[In]> pHierarchy As Object,
cItems As Integer,
<Out> bstrList() As String,
<Out> ByVal pcActualItems As IntPtr) As Integer Implements IVBEntryPointProvider.GetFormEntryPointsList
Dim workspace = ComponentModel.GetService(Of VisualStudioWorkspace)()
Dim hierarchy = CType(pHierarchy, IVsHierarchy)
For Each projectId In workspace.CurrentSolution.ProjectIds
Dim projectHierarchy = workspace.GetHierarchy(projectId)
If hierarchy Is projectHierarchy Then
Dim compilation = workspace.CurrentSolution.GetProject(projectId).GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None)
VisualBasicProject.GetEntryPointsWorker(compilation, cItems, bstrList, pcActualItems, findFormsOnly:=True)
End If
Next
Return VSConstants.S_OK
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.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
Imports Microsoft.VisualStudio.Shell.Interop
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
Partial Friend Class VisualBasicPackage
Implements IVBEntryPointProvider
Public Function GetFormEntryPointsList(<[In]> pHierarchy As Object,
cItems As Integer,
<Out> bstrList() As String,
<Out> ByVal pcActualItems As IntPtr) As Integer Implements IVBEntryPointProvider.GetFormEntryPointsList
Dim workspace = ComponentModel.GetService(Of VisualStudioWorkspace)()
Dim hierarchy = CType(pHierarchy, IVsHierarchy)
For Each projectId In workspace.CurrentSolution.ProjectIds
Dim projectHierarchy = workspace.GetHierarchy(projectId)
If hierarchy Is projectHierarchy Then
Dim compilation = workspace.CurrentSolution.GetProject(projectId).GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None)
VisualBasicProject.GetEntryPointsWorker(compilation, cItems, bstrList, pcActualItems, findFormsOnly:=True)
End If
Next
Return VSConstants.S_OK
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/CSharp/Test/Symbol/DocumentationComments/CrefTests.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.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using SymbolExtensions = Microsoft.CodeAnalysis.Test.Utilities.SymbolExtensions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class CrefTests : CSharpTestBase
{
[Fact]
public void EmptyCref()
{
var source = @"
/// <summary>
/// See <see cref=""""/>.
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute ''
// /// See <see cref=""/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @"""").WithArguments(""),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=""/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, @"""").WithArguments("Identifier expected", "1001"));
}
[Fact]
public void WhitespaceCref()
{
var source = @"
/// <summary>
/// See <see cref="" ""/>.
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute ''
// /// See <see cref=""/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @"""").WithArguments(""),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=""/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, @"""").WithArguments("Identifier expected", "1001"));
}
[Fact] //Lexer makes bad token with diagnostic and parser produces additional diagnostic when it consumes the bad token.
public void InvalidCrefCharacter1()
{
var source = @"
/// <summary>
/// See <see cref=""#""/>.
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute '#'
// /// See <see cref="#"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "#").WithArguments("#"),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref="#"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "#").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1658: Unexpected character '#'. See also error CS1056.
// /// See <see cref="#"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '#'", "1056"));
}
[Fact]
public void InvalidCrefCharacter2()
{
var source = @"
/// <summary>
/// See <see cref="" `""/>.
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute ' `'
// /// See <see cref=" `"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, " ").WithArguments(" `"),
// (3,21): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=" `"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "`").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1658: Unexpected character '`'. See also error CS1056.
// /// See <see cref=" `"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '`'", "1056"));
}
[Fact]
public void IncompleteCref1()
{
var source = @"
/// <summary>
/// See <see cref=""
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (4,5): warning CS1584: XML comment has syntactically incorrect cref attribute ''
// /// </summary>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "<").WithArguments(""),
// (4,5): warning CS1658: Identifier expected. See also error CS1001.
// /// </summary>
Diagnostic(ErrorCode.WRN_ErrorOverride, "<").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref="
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref="
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"));
}
[Fact]
public void IncompleteCref2()
{
var source = @"
/// <summary>
/// See <see cref='";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute ''
// /// See <see cref='
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "").WithArguments(""),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref='
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref='
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref='
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.'
// /// See <see cref='
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary"),
// (2,1): warning CS1587: XML comment is not placed on a valid language element
// /// <summary>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
}
[Fact(), WorkItem(546839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546839")]
public void IncompleteCref3()
{
var source = @"
/// <summary>
/// See <see cref='M(T, /// </summary>";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'M(T, ///'
// /// See <see cref='M(T, /// </summary>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "M(T,").WithArguments("M(T, ///"),
// (3,25): warning CS1658: ) expected. See also error CS1026.
// /// See <see cref='M(T, /// </summary>
Diagnostic(ErrorCode.WRN_ErrorOverride, "/").WithArguments(") expected", "1026"),
// (3,28): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref='M(T, /// </summary>
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,28): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref='M(T, /// </summary>
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"),
// (2,1): warning CS1587: XML comment is not placed on a valid language element
// /// <summary>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
}
[Fact(), WorkItem(546919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546919")]
public void IncompleteCref4()
{
var source = @"
/// <summary>
/// See <see cref='M{";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'M{'
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "M{").WithArguments("M{"),
// (3,22): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Identifier expected", "1001"),
// (3,22): warning CS1658: Syntax error, '>' expected. See also error CS1003.
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Syntax error, '>' expected", "1003"),
// (3,22): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,22): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"),
// (3,22): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.'
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary"),
// (2,1): warning CS1587: XML comment is not placed on a valid language element
// /// <summary>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
}
[Fact(), WorkItem(547000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547000")]
public void IncompleteCref5()
{
var source = @"
/// <summary>
/// See <see cref='T"; // Make sure the verbatim check doesn't choke on EOF.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,21): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref='T
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,21): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref='T
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"),
// (3,21): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.'
// /// See <see cref='T
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary"),
// (2,1): warning CS1587: XML comment is not placed on a valid language element
// /// <summary>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
}
[WorkItem(547000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547000")]
[Fact]
public void Verbatim()
{
var source = @"
/// <summary>
/// See <see cref=""Gibberish""/>.
/// See <see cref=""T:Gibberish""/>.
/// See <see cref=""T:Gibberish""/>.
/// See <see cref=""T:Gibberish""/>.
/// See <see cref=""T:Gibberish""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments);
compilation.VerifyDiagnostics(
// (3,20): warning CS1574: XML comment has cref attribute 'Gibberish' that could not be resolved
// /// See <see cref="Gibberish"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "Gibberish").WithArguments("Gibberish"));
// Only the first one counts as a cref attribute.
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'Gibberish' that could not be resolved
// /// See <see cref="Gibberish"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "Gibberish").WithArguments("Gibberish"));
Assert.Null(actualSymbol);
}
[WorkItem(547000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547000")]
[Fact]
public void NotQuiteVerbatim()
{
var source = @"
/// <summary>
/// See <see cref=""A""/> - only one character.
/// See <see cref="":""/> - first character is colon.
/// See <see cref=""::""/> - first character is colon.
/// See <see cref=""::Gibberish""/> - first character is colon.
/// </summary>
class Program { }
";
var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments);
compilation.VerifyDiagnostics(
// (4,20): warning CS1584: XML comment has syntactically incorrect cref attribute ':'
// /// See <see cref=":"/> - first character is colon.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, ":").WithArguments(":"),
// (4,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=":"/> - first character is colon.
Diagnostic(ErrorCode.WRN_ErrorOverride, ":").WithArguments("Identifier expected", "1001"),
// (5,20): warning CS1584: XML comment has syntactically incorrect cref attribute '::'
// /// See <see cref="::"/> - first character is colon.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, ":").WithArguments("::"),
// (5,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref="::"/> - first character is colon.
Diagnostic(ErrorCode.WRN_ErrorOverride, "::").WithArguments("Identifier expected", "1001"),
// (6,20): warning CS1584: XML comment has syntactically incorrect cref attribute '::Gibberish'
// /// See <see cref="::Gibberish"/> - first character is colon.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "&").WithArguments("::Gibberish"),
// (6,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref="::Gibberish"/> - first character is colon.
Diagnostic(ErrorCode.WRN_ErrorOverride, "::").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1574: XML comment has cref attribute 'A' that could not be resolved
// /// See <see cref="A"/> - only one character.
Diagnostic(ErrorCode.WRN_BadXMLRef, "A").WithArguments("A"));
var crefSyntaxes = GetCrefSyntaxes(compilation);
Assert.Equal(4, crefSyntaxes.Count());
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
AssertEx.All(crefSyntaxes, cref => model.GetSymbolInfo(cref).Symbol == null);
}
[Fact]
public void SpecialName1()
{
var source = @"
/// <summary>
/// See <see cref="".ctor""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
// The dot is syntactically incorrect.
compilation.VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute '.ctor'
// /// See <see cref=".ctor"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, ".").WithArguments(".ctor"),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=".ctor"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, ".").WithArguments("Identifier expected", "1001"));
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute '.ctor' that could not be resolved
// /// See <see cref=".ctor"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "").WithArguments(""));
Assert.Null(actualSymbol);
}
[Fact]
public void SpecialName2()
{
var source = @"
/// <summary>
/// See <see cref="".cctor""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
// The dot is syntactically incorrect.
compilation.VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute '.cctor'
// /// See <see cref=".cctor"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, ".").WithArguments(".cctor"),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=".cctor"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, ".").WithArguments("Identifier expected", "1001"));
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute '.cctor' that could not be resolved
// /// See <see cref=".cctor"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "").WithArguments(""));
Assert.Null(actualSymbol);
}
[Fact]
public void SpecialName3()
{
var source = @"
/// <summary>
/// See <see cref=""~Program""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
// The tilde is syntactically incorrect.
compilation.VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute '~Program'
// /// See <see cref="~Program"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "~").WithArguments("~Program"),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref="~Program"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "~").WithArguments("Identifier expected", "1001"));
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute '~Program' that could not be resolved
// /// See <see cref="~Program"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "").WithArguments(""));
Assert.Null(actualSymbol);
}
[Fact]
public void TypeScope1()
{
var source = @"
/// <summary>
/// See <see cref=""Program""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeScope2()
{
var source = @"
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class Program
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeScope3()
{
var source = @"
/// <summary>
/// See <see cref=""T""/>.
/// </summary>
class Program<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").TypeParameters.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter
// /// See <see cref="T"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T"));
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeScope4()
{
var source = @"
class Base
{
void M() { }
}
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class Derived : Base { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// As in dev11, we ignore the inherited method symbol.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (8,20): warning CS1574: XML comment has cref attribute 'M' that could not be resolved
// /// See <see cref="M"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "M").WithArguments("M"));
Assert.Null(actualSymbol);
}
[Fact]
public void TypeScope5()
{
var source = @"
class M
{
}
class Base
{
void M() { }
}
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class Derived : Base { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// As in dev11, we ignore the inherited method symbol.
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeScope6()
{
var source = @"
class Outer
{
void M() { }
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class Inner { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Outer").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void MethodScope1()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void MethodScope2()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""T""/>.
/// </summary>
void M<T>() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Type parameters are not in scope.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,24): warning CS1574: XML comment has cref attribute 'T' that could not be resolved
// /// See <see cref="T"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "T").WithArguments("T"));
Assert.Null(actualSymbol);
}
[Fact]
public void MethodScope3()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""p""/>.
/// </summary>
void M(int p) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Type parameters are not in scope.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,24): warning CS1574: XML comment has cref attribute 'p' that could not be resolved
// /// See <see cref="p"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "p").WithArguments("p"));
Assert.Null(actualSymbol);
}
[Fact]
public void IndexerScope1()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""Item""/>.
/// </summary>
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Slightly surprising, but matches the dev11 behavior (you're supposed to use "this").
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,24): warning CS1574: XML comment has cref attribute 'Item' that could not be resolved
// /// See <see cref="Item"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "Item").WithArguments("Item"));
Assert.Null(actualSymbol);
}
[Fact]
public void IndexerScope2()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""x""/>.
/// </summary>
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,24): warning CS1574: XML comment has cref attribute 'x' that could not be resolved
// /// See <see cref="x"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x"));
Assert.Null(actualSymbol);
}
[Fact]
public void ObsoleteType()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""A""/>.
/// </summary>
class Test
{
}
[Obsolete(""error"", true)]
class A
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var obsoleteType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A");
obsoleteType.ForceCompleteObsoleteAttribute();
var testType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
testType.ForceCompleteObsoleteAttribute();
var expectedSymbol = obsoleteType;
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void ObsoleteParameterType()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""M(A)""/>.
/// </summary>
class Test
{
void M(A a) { }
}
[Obsolete(""error"", true)]
class A
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var obsoleteType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A");
obsoleteType.ForceCompleteObsoleteAttribute();
var testType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
testType.ForceCompleteObsoleteAttribute();
var expectedSymbol = testType.GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeNotConstructor1()
{
var source = @"
/// <summary>
/// See <see cref=""A""/>.
/// </summary>
class A
{
}
/// <summary>
/// See <see cref=""B""/>.
/// </summary>
class B
{
B() { }
}
/// <summary>
/// See <see cref=""C""/>.
/// </summary>
static class C
{
static int x = 1;
}
/// <summary>
/// See <see cref=""D""/>.
/// </summary>
static class D
{
static D() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
Assert.Equal(SymbolKind.NamedType, GetReferencedSymbol(crefSyntax, compilation).Kind);
}
}
[Fact]
public void TypeNotConstructor2()
{
var il = @"
.class public auto ansi beforefieldinit B
extends [mscorlib]System.Object
{
.class auto ansi nested public beforefieldinit B
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
";
var csharp = @"
/// <summary>
/// See <see cref=""B""/>.
/// See <see cref=""B.B""/>.
/// </summary>
class C { }
";
var compilation = CreateCompilationWithILAndMscorlib40(csharp, il);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
Assert.Equal(SymbolKind.NamedType, GetReferencedSymbol(crefSyntax, compilation).Kind);
}
}
[Fact]
public void ConstructorNotType1()
{
var source = @"
/// <summary>
/// See <see cref=""A()""/>.
/// See <see cref=""A.A()""/>.
/// See <see cref=""A.A""/>.
/// </summary>
class A
{
}
/// <summary>
/// See <see cref=""B()""/>.
/// See <see cref=""B.B()""/>.
/// See <see cref=""B.B""/>.
/// </summary>
class B
{
B() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
Assert.Equal(SymbolKind.Method, GetReferencedSymbol(crefSyntax, compilation).Kind);
}
}
[Fact]
public void ConstructorNotType2()
{
var il = @"
.class public auto ansi beforefieldinit B
extends [mscorlib]System.Object
{
.class auto ansi nested public beforefieldinit B
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
";
var csharp = @"
/// <summary>
/// See <see cref=""B.B.B""/>.
/// See <see cref=""B()""/>.
/// See <see cref=""B.B()""/>.
/// See <see cref=""B.B.B()""/>.
/// </summary>
class C { }
";
var compilation = CreateCompilationWithILAndMscorlib40(csharp, il);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
Assert.Equal(SymbolKind.Method, GetReferencedSymbol(crefSyntax, compilation).Kind);
}
}
/// <summary>
/// Comment on constructor type.
/// </summary>
[Fact]
public void TypeVersusConstructor1()
{
var source = @"
/// <summary>
/// See <see cref=""A""/>.
/// See <see cref=""A()""/>.
/// See <see cref=""A.A""/>.
/// See <see cref=""A.A()""/>.
/// </summary>
class A
{
}
/// <summary>
/// See <see cref=""B""/>.
/// See <see cref=""B()""/>.
/// See <see cref=""B.B""/>.
/// See <see cref=""B.B()""/>.
///
/// See <see cref=""B{T}""/>.
/// See <see cref=""B{T}()""/>.
/// See <see cref=""B{T}.B""/>.
/// See <see cref=""B{T}.B()""/>.
///
/// See <see cref=""B{T}.B{T}""/>.
/// See <see cref=""B{T}.B{T}()""/>.
/// </summary>
class B<T>
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation);
var typeA = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var ctorA = typeA.InstanceConstructors.Single();
var typeB = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("B");
var ctorB = typeB.InstanceConstructors.Single();
var expected = new ISymbol[]
{
typeA,
ctorA,
ctorA,
ctorA,
null,
ctorB,
null,
null,
typeB,
ctorB,
null,
ctorB,
null,
null,
};
var actual = GetCrefOriginalDefinitions(model, crefs);
AssertEx.Equal(expected, actual);
compilation.VerifyDiagnostics(
// (13,20): warning CS1574: XML comment has cref attribute 'B' that could not be resolved
// /// See <see cref="B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B").WithArguments("B"),
// (15,20): warning CS1574: XML comment has cref attribute 'B.B' that could not be resolved
// /// See <see cref="B.B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B").WithArguments("B"),
// (16,20): warning CS1574: XML comment has cref attribute 'B.B()' that could not be resolved
// /// See <see cref="B.B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B()").WithArguments("B()"),
// (20,20): warning CS1574: XML comment has cref attribute 'B{T}.B' that could not be resolved
// /// See <see cref="B{T}.B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B").WithArguments("B"),
// (23,20): warning CS1574: XML comment has cref attribute 'B{T}.B{T}' that could not be resolved
// /// See <see cref="B{T}.B{T}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}").WithArguments("B{T}"),
// (24,20): warning CS1574: XML comment has cref attribute 'B{T}.B{T}()' that could not be resolved
// /// See <see cref="B{T}.B{T}()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}()").WithArguments("B{T}()"));
}
/// <summary>
/// Comment on unrelated type.
/// </summary>
[WorkItem(554077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554077")]
[Fact]
public void TypeVersusConstructor2()
{
var source = @"
class A
{
}
class B<T>
{
}
/// <summary>
/// See <see cref=""A""/>.
/// See <see cref=""A()""/>.
/// See <see cref=""A.A""/>.
/// See <see cref=""A.A()""/>.
///
/// See <see cref=""B""/>.
/// See <see cref=""B()""/>.
/// See <see cref=""B.B""/>.
/// See <see cref=""B.B()""/>.
///
/// See <see cref=""B{T}""/>.
/// See <see cref=""B{T}()""/>.
/// See <see cref=""B{T}.B""/>.
/// See <see cref=""B{T}.B()""/>.
///
/// See <see cref=""B{T}.B{T}""/>.
/// See <see cref=""B{T}.B{T}()""/>.
/// </summary>
class Other
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation);
var typeA = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var ctorA = typeA.InstanceConstructors.Single();
var typeB = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("B");
var ctorB = typeB.InstanceConstructors.Single();
var expected = new ISymbol[]
{
typeA,
ctorA,
ctorA,
ctorA,
null,
null,
null,
null,
typeB,
ctorB,
ctorB, //NB: different when comment is not applied on/in B.
ctorB,
null,
null,
};
var actual = GetCrefOriginalDefinitions(model, crefs);
AssertEx.Equal(expected, actual);
compilation.VerifyDiagnostics(
// (16,20): warning CS1574: XML comment has cref attribute 'B' that could not be resolved
// /// See <see cref="B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B").WithArguments("B"),
// (17,20): warning CS1574: XML comment has cref attribute 'B()' that could not be resolved
// /// See <see cref="B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B()").WithArguments("B()"),
// (18,20): warning CS1574: XML comment has cref attribute 'B.B' that could not be resolved
// /// See <see cref="B.B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B").WithArguments("B"),
// (19,20): warning CS1574: XML comment has cref attribute 'B.B()' that could not be resolved
// /// See <see cref="B.B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B()").WithArguments("B()"),
// (26,20): warning CS1574: XML comment has cref attribute 'B{T}.B{T}' that could not be resolved
// /// See <see cref="B{T}.B{T}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}").WithArguments("B{T}"),
// (27,20): warning CS1574: XML comment has cref attribute 'B{T}.B{T}()' that could not be resolved
// /// See <see cref="B{T}.B{T}()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}()").WithArguments("B{T}()"));
}
/// <summary>
/// Comment on nested type of constructor type (same behavior as unrelated type).
/// </summary>
[WorkItem(554077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554077")]
[Fact]
public void TypeVersusConstructor3()
{
var source = @"
class A
{
/// <summary>
/// See <see cref=""A""/>.
/// See <see cref=""A()""/>.
/// See <see cref=""A.A""/>.
/// See <see cref=""A.A()""/>.
/// </summary>
class Inner
{
}
}
class B<T>
{
/// <summary>
/// See <see cref=""B""/>.
/// See <see cref=""B()""/>.
/// See <see cref=""B.B""/>.
/// See <see cref=""B.B()""/>.
///
/// See <see cref=""B{T}""/>.
/// See <see cref=""B{T}()""/>.
/// See <see cref=""B{T}.B""/>.
/// See <see cref=""B{T}.B()""/>.
///
/// See <see cref=""B{T}.B{T}""/>.
/// See <see cref=""B{T}.B{T}()""/>.
/// </summary>
class Inner
{
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation);
var typeA = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var ctorA = typeA.InstanceConstructors.Single();
var typeB = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("B");
var ctorB = typeB.InstanceConstructors.Single();
var expected = new ISymbol[]
{
typeA,
ctorA,
ctorA,
ctorA,
null,
null,
null,
null,
typeB,
ctorB,
ctorB, //NB: different when comment is not applied on/in B.
ctorB,
null,
null,
};
var actual = GetCrefOriginalDefinitions(model, crefs);
AssertEx.Equal(expected, actual);
compilation.VerifyDiagnostics(
// (18,24): warning CS1574: XML comment has cref attribute 'B' that could not be resolved
// /// See <see cref="B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B").WithArguments("B"),
// (19,24): warning CS1574: XML comment has cref attribute 'B()' that could not be resolved
// /// See <see cref="B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B()").WithArguments("B()"),
// (20,24): warning CS1574: XML comment has cref attribute 'B.B' that could not be resolved
// /// See <see cref="B.B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B").WithArguments("B"),
// (21,24): warning CS1574: XML comment has cref attribute 'B.B()' that could not be resolved
// /// See <see cref="B.B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B()").WithArguments("B()"),
// (28,24): warning CS1574: XML comment has cref attribute 'B{T}.B{T}' that could not be resolved
// /// See <see cref="B{T}.B{T}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}").WithArguments("B{T}"),
// (29,24): warning CS1574: XML comment has cref attribute 'B{T}.B{T}()' that could not be resolved
// /// See <see cref="B{T}.B{T}()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}()").WithArguments("B{T}()"));
}
[Fact]
public void NoConstructor()
{
var source = @"
/// <summary>
/// See <see cref=""C()""/>.
/// See <see cref=""C.C()""/>.
/// See <see cref=""C.C""/>.
/// </summary>
static class C
{
}
/// <summary>
/// See <see cref=""D()""/>.
/// See <see cref=""D.D()""/>.
/// See <see cref=""D.D""/>.
/// </summary>
static class D
{
static D() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
string text = crefSyntax.ToString();
string arguments = text.Contains("C()") ? "C()" : text.Contains("C") ? "C" : text.Contains("D()") ? "D()" : "D";
Assert.Null(GetReferencedSymbol(crefSyntax, compilation,
Diagnostic(ErrorCode.WRN_BadXMLRef, text).WithArguments(arguments)));
}
}
[Fact]
public void AmbiguousReferenceWithoutParameters()
{
var source = @"
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class C
{
void M() { }
void M(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: Dev11 actually picks the constructor of C - probably an accidental fall-through.
var expectedCandidates = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("M").OfType<MethodSymbol>();
var expectedWinner = expectedCandidates.Single(m => m.ParameterCount == 0);
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'M'. Assuming 'C.M()', but could have also matched other overloads including 'C.M(int)'.
// /// See <see cref="M"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M").WithArguments("M", "C.M()", "C.M(int)"));
Assert.Equal(expectedWinner, actualWinner);
AssertEx.SetEqual(expectedCandidates.AsEnumerable(), actualCandidates.ToArray());
}
[Fact]
public void SourceMetadataConflict()
{
var il = @"
.class public auto ansi beforefieldinit B
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
";
var csharp = @"
/// <summary>
/// See <see cref=""B""/>.
/// </summary>
class B { }
";
var ilRef = CompileIL(il);
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(csharp, new[] { ilRef });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// NOTE: As in Dev11, no warning is produced.
var expectedSymbol = compilation.GlobalNamespace.GetMembers("B").OfType<SourceNamedTypeSymbol>().Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Basic()
{
var source = @"
/// <summary>
/// See <see cref=""M(int)""/>.
/// </summary>
class B
{
void M(string x) { }
void M(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.Parameters.Single().Type.SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Ref()
{
var source = @"
/// <summary>
/// See <see cref=""M(ref int)""/>.
/// </summary>
class B
{
void M(ref int x) { }
void M(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => !m.ParameterRefKinds.IsDefault);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Out()
{
var source = @"
/// <summary>
/// See <see cref=""M(out int)""/>.
/// </summary>
class B
{
void M(out int x) { }
void M(ref int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.ParameterRefKinds.Single() == RefKind.Out);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Params()
{
var source = @"
/// <summary>
/// See <see cref=""M(int[])""/>.
/// </summary>
class B
{
void M(int x) { }
void M(params int[] x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.HasParamsParameter());
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Extension()
{
var source = @"
/// <summary>
/// See <see cref=""M(B)""/>.
/// </summary>
class B
{
public static void M(string s) { }
public static void M(this B self) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.IsExtensionMethod);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Arglist1()
{
var source = @"
/// <summary>
/// See <see cref=""M()""/>.
/// </summary>
class B
{
void M() { }
void M(__arglist) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedCandidates = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M");
var expectedWinner = expectedCandidates.OfType<MethodSymbol>().Single(m => !m.IsVararg);
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'M()'. Assuming 'B.M()', but could have also matched other overloads including 'B.M(__arglist)'.
// /// See <see cref="M()"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M()").WithArguments("M()", "B.M()", "B.M(__arglist)"));
Assert.Equal(expectedWinner, actualWinner);
AssertEx.SetEqual(expectedCandidates, actualCandidates.ToArray());
}
[Fact]
public void OverloadResolution_Arglist2()
{
var source = @"
/// <summary>
/// See <see cref=""M()""/>.
/// </summary>
class B
{
void M(int x) { }
void M(__arglist) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.IsVararg);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeParameters_Simple1()
{
var source = @"
/// <summary>
/// See <see cref=""B{T}""/>.
/// </summary>
class B<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("T", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
}
[Fact]
public void TypeParameters_Simple2()
{
var source = @"
/// <summary>
/// See <see cref=""B{U}""/>.
/// </summary>
class B<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("U", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
}
[Fact]
public void TypeParameters_Simple3()
{
var source = @"
/// <summary>
/// See <see cref=""M{T}""/>.
/// </summary>
class B
{
void M<T>() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("T", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
}
[Fact]
public void TypeParameters_Simple4()
{
var source = @"
/// <summary>
/// See <see cref=""M{U}""/>.
/// </summary>
class B
{
void M<T>() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("U", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
}
[Fact]
public void TypeParameters_Duplicate()
{
var source = @"
/// <summary>
/// See <see cref=""T""/>.
/// </summary>
class B<T, T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").TypeArguments()[0];
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter
// /// See <see cref="T"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T"));
Assert.Equal(expectedSymbol, actualSymbol);
}
// Keep code coverage happy.
[Fact]
public void TypeParameters_Symbols()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A, B}""/>.
/// </summary>
class C<T, U, V>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
var actualTypeParameters = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Cast<CrefTypeParameterSymbol>().ToArray();
AssertEx.None(actualTypeParameters, p => p.IsFromCompilation(compilation));
AssertEx.None(actualTypeParameters, p => p.IsImplicitlyDeclared);
AssertEx.All(actualTypeParameters, p => p.Variance == VarianceKind.None);
AssertEx.All(actualTypeParameters, p => p.Locations.Single() == p.DeclaringSyntaxReferences.Single().GetLocation());
AssertEx.None(actualTypeParameters, p => p.HasValueTypeConstraint);
AssertEx.None(actualTypeParameters, p => p.HasReferenceTypeConstraint);
AssertEx.None(actualTypeParameters, p => p.HasConstructorConstraint);
AssertEx.All(actualTypeParameters, p => p.ContainingSymbol == null);
AssertEx.All(actualTypeParameters, p => p.GetConstraintTypes(null).Length == 0);
AssertEx.All(actualTypeParameters, p => p.GetInterfaces(null).Length == 0);
foreach (var p in actualTypeParameters)
{
Assert.ThrowsAny<Exception>(() => p.GetEffectiveBaseClass(null));
Assert.ThrowsAny<Exception>(() => p.GetDeducedBaseType(null));
}
Assert.Equal(actualTypeParameters[0], actualTypeParameters[1]);
Assert.Equal(actualTypeParameters[0].GetHashCode(), actualTypeParameters[1].GetHashCode());
Assert.NotEqual(actualTypeParameters[0], actualTypeParameters[2]);
#if !DISABLE_GOOD_HASH_TESTS
Assert.NotEqual(actualTypeParameters[0].GetHashCode(), actualTypeParameters[2].GetHashCode());
#endif
}
[Fact]
public void TypeParameters_Signature1()
{
var source = @"
/// <summary>
/// See <see cref=""M{U}(U)""/>.
/// </summary>
class B
{
void M<T>(T t) { }
void M<T>(int t) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>()
.Single(method => method.Parameters.Single().Type.TypeKind == TypeKind.TypeParameter);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("U", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
Assert.Equal(typeArgument, actualSymbol.GetParameters().Single().Type);
}
[Fact]
public void TypeParameters_Signature2()
{
var source = @"
/// <summary>
/// See <see cref=""A{S, T}.B{U, V}.M{W, X}(S, U, W, T, V, X)""/>.
/// </summary>
class A<M, N>
{
class B<O, P>
{
internal void M<Q, R>(M m, O o, Q q, N n, P p, R r) { }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var expectedOriginalParameterTypes = expectedOriginalDefinitionSymbol.Parameters.Select(p => p.Type).Cast<TypeParameterSymbol>();
var actualParameterTypes = actualSymbol.GetParameters().Select(p => p.Type).Cast<TypeParameterSymbol>();
AssertEx.Equal(expectedOriginalParameterTypes.Select(t => t.Ordinal), actualParameterTypes.Select(t => t.Ordinal));
AssertEx.None(expectedOriginalParameterTypes.Zip(actualParameterTypes, object.Equals), x => x);
}
[Fact]
public void TypeParameters_Duplicates1()
{
var source = @"
/// <summary>
/// See <see cref=""A{T, T}.M(T)""/>.
/// </summary>
class A<T, U>
{
void M(T t) { }
void M(U u) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: In Dev11, this unambiguously matches M(U) (i.e. the last type parameter wins).
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'A{T, T}.M(T)'. Assuming 'A<T, T>.M(T)', but could have also matched other overloads including 'A<T, T>.M(T)'.
// /// See <see cref="A{T, T}.M(T)"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "A{T, T}.M(T)").WithArguments("A{T, T}.M(T)", "A<T, T>.M(T)", "A<T, T>.M(T)"));
Assert.False(actualWinner.IsDefinition);
var actualParameterType = actualWinner.GetParameters().Single().Type;
AssertEx.All(actualWinner.ContainingType.TypeArguments(), typeParam => TypeSymbol.Equals(typeParam, actualParameterType, TypeCompareKind.ConsiderEverything2)); //CONSIDER: Would be different in Dev11.
Assert.Equal(1, ((TypeParameterSymbol)actualParameterType).Ordinal);
Assert.Equal(2, actualCandidates.Length);
Assert.Equal(actualWinner, actualCandidates[0]);
Assert.Equal(actualWinner.ContainingType.GetMembers(actualWinner.Name).Single(member => member != actualWinner), actualCandidates[1]);
}
[Fact]
public void TypeParameters_Duplicates2()
{
var source = @"
/// <summary>
/// See <see cref=""A{T}.B{T}.M(T)""/>.
/// </summary>
class A<T>
{
class B<U>
{
internal void M(T t) { }
internal void M(U u) { }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: In Dev11, this unambiguously matches M(U) (i.e. the last type parameter wins).
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'A{T}.B{T}.M(T)'. Assuming 'A<T>.B<T>.M(T)', but could have also matched other overloads including 'A<T>.B<T>.M(T)'.
// /// See <see cref="A{T}.B{T}.M(T)"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "A{T}.B{T}.M(T)").WithArguments("A{T}.B{T}.M(T)", "A<T>.B<T>.M(T)", "A<T>.B<T>.M(T)"));
Assert.False(actualWinner.IsDefinition);
var actualParameterType = actualWinner.GetParameters().Single().Type;
Assert.Equal(actualParameterType, actualWinner.ContainingType.TypeArguments().Single());
Assert.Equal(actualParameterType, actualWinner.ContainingType.ContainingType.TypeArguments().Single());
Assert.Equal(2, actualCandidates.Length);
Assert.Equal(actualWinner, actualCandidates[0]);
Assert.Equal(actualWinner.ContainingType.GetMembers(actualWinner.Name).Single(member => member != actualWinner), actualCandidates[1]);
}
[Fact]
public void TypeParameters_ExistingTypes1()
{
var source = @"
/// <summary>
/// See <see cref=""A{U}.M(U)""/>.
/// </summary>
class A<T>
{
void M(T t) { } // This one.
void M(U u) { }
}
class U { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMembers("M").OfType<MethodSymbol>().
Single(method => method.Parameters.Single().Type.TypeKind == TypeKind.TypeParameter);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
Assert.Equal(TypeKind.TypeParameter, actualSymbol.GetParameterTypes().Single().Type.TypeKind);
}
[Fact]
public void TypeParameters_ExistingTypes2()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""A{Int32}.M(Int32)""/>.
/// </summary>
class A<T>
{
void M(T t) { } // This one.
void M(int u) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMembers("M").OfType<MethodSymbol>().
Single(method => method.Parameters.Single().Type.TypeKind == TypeKind.TypeParameter);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
Assert.Equal(TypeKind.TypeParameter, actualSymbol.GetParameterTypes().Single().Type.TypeKind);
}
[Fact]
public void GenericTypeConstructor()
{
var source = @"
/// <summary>
/// See <see cref=""A{T}()""/>.
/// </summary>
class A<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
}
[Fact]
public void Inaccessible1()
{
var source = @"
/// <summary>
/// See <see cref=""C.M""/>.
/// </summary>
class A
{
}
class C
{
private void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.NotNull(actualSymbol);
Assert.Equal(
compilation.GlobalNamespace
.GetMember<NamedTypeSymbol>("C")
.GetMember<SourceOrdinaryMethodSymbol>("M"),
actualSymbol);
Assert.Equal(SymbolKind.Method, actualSymbol.Kind);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var info = model.GetSymbolInfo(crefSyntax);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(info.Symbol, actualSymbol.ISymbol);
}
[Fact]
public void Inaccessible2()
{
var source = @"
/// <summary>
/// See <see cref=""Outer.Inner.M""/>.
/// </summary>
class A
{
}
class Outer
{
private class Inner
{
private void M() { }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace
.GetMember<NamedTypeSymbol>("Outer")
.GetMember<NamedTypeSymbol>("Inner")
.GetMember<SourceOrdinaryMethodSymbol>("M");
// Consider inaccessible symbols, as in Dev11
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")]
[Fact]
public void Inaccessible3()
{
var lib1Source = @"internal class C { }";
var lib2Source = @"public class C { }";
var source = @"
/// <summary>
/// See <see cref=""C""/>.
/// </summary>
class Test { }
";
var lib1Ref = CreateCompilation(lib1Source, assemblyName: "A").EmitToImageReference();
var lib2Ref = CreateCompilation(lib2Source, assemblyName: "B").EmitToImageReference();
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { lib1Ref, lib2Ref });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Break: In dev11 the accessible symbol is preferred. We simply prefer the "first"
Symbol actualSymbol;
var symbols = GetReferencedSymbols(crefSyntax, compilation, out actualSymbol,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'C'. Assuming 'C', but could have also matched other overloads including 'C'.
// /// See <see cref="C"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C").WithArguments("C", "C", "C").WithLocation(3, 20));
Assert.Equal("A", actualSymbol.ContainingAssembly.Name);
}
[WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")]
[Fact]
public void Inaccessible4()
{
var source = @"
namespace Test
{
using System;
/// <summary>
/// <see cref=""ClientUtils.Goo""/>
/// </summary>
enum E { }
}
class ClientUtils
{
public static void Goo() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// NOTE: Matches dev11 - the accessible symbol is preferred (vs System.ClientUtils).
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("ClientUtils").GetMember<MethodSymbol>("Goo");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")]
[WorkItem(709199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709199")]
[Fact]
public void ProtectedInstanceBaseMember()
{
var source = @"
class Base
{
protected int F;
}
/// Accessible: <see cref=""Base.F""/>
class Derived : Base
{
}
/// Not accessible: <see cref=""Base.F""/>
class Other
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (4,26): warning CS0649: Field 'Base.F' is never assigned to, and will always have its default value 0
// protected static int F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("Base.F", "0"));
var crefSyntax = GetCrefSyntaxes(compilation).First();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base").GetMember<FieldSymbol>("F");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")]
[WorkItem(709199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709199")]
[Fact]
public void ProtectedStaticBaseMember()
{
var source = @"
class Base
{
protected static int F;
}
/// Accessible: <see cref=""Base.F""/>
class Derived : Base
{
}
/// Not accessible: <see cref=""Base.F""/>
class Other
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (4,26): warning CS0649: Field 'Base.F' is never assigned to, and will always have its default value 0
// protected static int F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("Base.F", "0"));
var crefSyntax = GetCrefSyntaxes(compilation).First();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base").GetMember<FieldSymbol>("F");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Ambiguous1()
{
var libSource = @"
public class A
{
}
";
var source = @"
/// <summary>
/// See <see cref=""A""/>.
/// </summary>
class B : A
{
}
";
var lib1 = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib1");
var lib2 = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib2");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib1), new CSharpCompilationReference(lib2) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: Dev11 fails with WRN_BadXMLRef.
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'A'. Assuming 'A', but could have also matched other overloads including 'A'.
// /// See <see cref="A"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "A").WithArguments("A", "A", "A"));
Assert.Contains(actualWinner, actualCandidates);
Assert.Equal(2, actualCandidates.Length);
AssertEx.SetEqual(actualCandidates.Select(sym => sym.ContainingAssembly.Name), "Lib1", "Lib2");
var model = compilation.GetSemanticModel(crefSyntax.SyntaxTree);
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason);
AssertEx.SetEqual(info.CandidateSymbols.Select(sym => sym.ContainingAssembly.Name), "Lib1", "Lib2");
}
[Fact]
public void Ambiguous2()
{
var libSource = @"
public class A
{
public void M() { }
}
";
var source = @"
/// <summary>
/// See <see cref=""A.M""/>.
/// </summary>
class B
{
}
";
var lib1 = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib1");
var lib2 = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib2");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib1), new CSharpCompilationReference(lib2) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Not ideal, but matches dev11.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'A.M' that could not be resolved
// /// See <see cref="A.M"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "A.M").WithArguments("M"));
Assert.Null(actualSymbol);
var model = compilation.GetSemanticModel(crefSyntax.SyntaxTree);
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[ConditionalFact(typeof(NoUsedAssembliesValidation))]
public void Ambiguous3()
{
var lib1Source = @"
public class A
{
}
";
var lib2Source = @"
public class A
{
}
public class B
{
public void M(A a) { }
public void M(int a) { }
}
";
var source = @"
/// <summary>
/// See <see cref=""B.M(A)""/>.
/// </summary>
class C
{
}
";
var lib1 = CreateCompilationWithMscorlib40AndDocumentationComments(lib1Source, assemblyName: "Lib1");
var lib2 = CreateCompilationWithMscorlib40AndDocumentationComments(lib2Source, assemblyName: "Lib2");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib1), new CSharpCompilationReference(lib2) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Not ideal, but matches dev11.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1580: Invalid type for parameter 'A' in XML comment cref attribute: 'B.M(A)'
// /// See <see cref="B.M(A)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "A").WithArguments("A", "B.M(A)"),
// (3,20): warning CS1574: XML comment has cref attribute 'B.M(A)' that could not be resolved
// /// See <see cref="B.M(A)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.M(A)").WithArguments("M(A)"));
Assert.Null(actualSymbol);
var model = compilation.GetSemanticModel(crefSyntax.SyntaxTree);
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[Fact]
public void TypeCref1()
{
var libSource = @"
public class A
{
}
";
var source = @"
extern alias LibAlias;
/// <summary>
/// See <see cref=""LibAlias::A""/>.
/// </summary>
class C
{
}
";
var lib = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("LibAlias")) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.IsType<SourceNamedTypeSymbol>(actualSymbol);
Assert.Equal("A", actualSymbol.Name);
Assert.Equal("Lib", actualSymbol.ContainingAssembly.Name);
}
[Fact]
public void TypeCref2()
{
var libSource = @"
public class A
{
}
";
var source = @"
extern alias LibAlias;
/// <summary>
/// See <see cref=""BadAlias::A""/>.
/// </summary>
class C
{
}
";
var lib = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("LibAlias")) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,20): warning CS1574: XML comment has cref attribute 'BadAlias::A' that could not be resolved
// /// See <see cref="BadAlias::A"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "BadAlias::A").WithArguments("BadAlias::A"));
}
[Fact]
public void TypeCref3()
{
var libSource = @"
public class A
{
}
";
var source = @"
extern alias LibAlias;
/// <summary>
/// See <see cref=""LibAlias::BadType""/>.
/// </summary>
class C
{
}
";
var lib = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("LibAlias")) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,20): warning CS1574: XML comment has cref attribute 'LibAlias::BadType' that could not be resolved
// /// See <see cref="LibAlias::BadType"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "LibAlias::BadType").WithArguments("LibAlias::BadType"));
}
[Fact]
public void TypeCref4()
{
var source = @"
/// <summary>
/// See <see cref=""int""/>.
/// </summary>
class C
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GetSpecialType(SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void IndexerCref_NoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""this""/>.
/// </summary>
class C
{
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void IndexerCref_Parameters()
{
var source = @"
/// <summary>
/// See <see cref=""this[int]""/>.
/// </summary>
class C
{
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void IndexerCref_OverloadResolutionFailure()
{
var source = @"
/// <summary>
/// See <see cref=""this[float]""/>.
/// </summary>
class C
{
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'this[float]' that could not be resolved
// /// See <see cref="this[float]"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "this[float]").WithArguments("this[float]"));
Assert.Null(actualSymbol);
}
[Fact]
public void UnaryOperator_NoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""operator !""/>.
/// </summary>
class C
{
public static C operator !(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.LogicalNotOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_OneParameter()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(C)""/>.
/// </summary>
class C
{
public static C operator !(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.LogicalNotOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_OverloadResolutionFailure()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(int)""/>.
/// </summary>
class C
{
public static C operator !(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'operator !(int)' that could not be resolved
// /// See <see cref="operator !(int)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "operator !(int)").WithArguments("operator !(int)"));
Assert.Null(actualSymbol);
}
[Fact]
public void UnaryOperator_OverloadResolution()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(int)""/>.
/// </summary>
class C
{
public static bool operator !(C q)
{
return false;
}
public static bool op_LogicalNot(int x)
{
return false;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.LogicalNotOperatorName).OfType<MethodSymbol>().
Single(method => method.ParameterTypesWithAnnotations.Single().SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_Type()
{
var source = @"
/// <summary>
/// See <see cref=""operator !""/>.
/// </summary>
class op_LogicalNot
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.LogicalNotOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_Constructor0()
{
var source = @"
/// <summary>
/// See <see cref=""operator !()""/>.
/// </summary>
class op_LogicalNot
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.LogicalNotOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_Constructor1()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(int)""/>.
/// </summary>
class op_LogicalNot
{
op_LogicalNot(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.LogicalNotOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_Constructor2()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(int, int)""/>.
/// </summary>
class op_LogicalNot
{
op_LogicalNot(int x, int y) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.LogicalNotOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_NoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""operator /""/>.
/// </summary>
class C
{
public static C operator /(C c, int x)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.DivisionOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_TwoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(C, int)""/>.
/// </summary>
class C
{
public static C operator /(C c, int x)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.DivisionOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_OverloadResolutionFailure()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int)""/>.
/// </summary>
class C
{
public static C operator /(C c, int x)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'operator /(int)' that could not be resolved
// /// See <see cref="operator /(int)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "operator /(int)").WithArguments("operator /(int)"));
Assert.Null(actualSymbol);
}
[Fact]
public void BinaryOperator_OverloadResolution()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int, int)""/>.
/// </summary>
class C
{
public static bool operator /(C q, int x)
{
return false;
}
public static bool op_Division(int x, int x)
{
return false;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.DivisionOperatorName).OfType<MethodSymbol>().
Single(method => method.ParameterTypesWithAnnotations.First().SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_Type()
{
var source = @"
/// <summary>
/// See <see cref=""operator /""/>.
/// </summary>
class op_Division
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.DivisionOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_Constructor0()
{
var source = @"
/// <summary>
/// See <see cref=""operator /()""/>.
/// </summary>
class op_Division
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.DivisionOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_Constructor1()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int)""/>.
/// </summary>
class op_Division
{
op_Division(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: This is a syntactic error in dev11.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'operator /(int)' that could not be resolved
// /// See <see cref="operator /(int)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "operator /(int)").WithArguments("operator /(int)"));
Assert.Null(actualSymbol);
}
[Fact]
public void BinaryOperator_Constructor2()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int, int)""/>.
/// </summary>
class op_Division
{
op_Division(int x, int y) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.DivisionOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_Constructor3()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int, int, int)""/>.
/// </summary>
class op_Division
{
op_Division(int x, int y, int z) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.DivisionOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_NoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""explicit operator int""/>.
/// </summary>
class C
{
public static explicit operator int(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_OneParameter()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(C)""/>.
/// </summary>
class C
{
public static implicit operator int(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.ImplicitConversionName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_OverloadResolutionFailure()
{
var source = @"
/// <summary>
/// See <see cref=""explicit operator int(int)""/>.
/// </summary>
class C
{
public static explicit operator int(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'explicit operator int(int)' that could not be resolved
// /// See <see cref="explicit operator int(int)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator int(int)").WithArguments("explicit operator int(int)"));
Assert.Null(actualSymbol);
}
[Fact]
public void Conversion_OverloadResolution()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(int)""/>.
/// </summary>
class C
{
public static implicit operator int(C q)
{
return false;
}
public static int op_Implicit(int x)
{
return false;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.ImplicitConversionName).OfType<MethodSymbol>().
Single(method => method.ParameterTypesWithAnnotations.Single().SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_ReturnType()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(int)""/>.
/// </summary>
class C
{
public static implicit operator int(C q)
{
return false;
}
public static string op_Implicit(int x)
{
return false;
}
// Declaration error, but not important for test.
public static int op_Implicit(int x)
{
return false;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.ImplicitConversionName).OfType<MethodSymbol>().
Single(method => method.ParameterTypesWithAnnotations.Single().SpecialType == SpecialType.System_Int32 && method.ReturnType.SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_Type()
{
var source = @"
/// <summary>
/// See <see cref=""explicit operator int""/>.
/// </summary>
class op_Explicit
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.ExplicitConversionName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_Constructor0()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int()""/>.
/// </summary>
class op_Implicit
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.ImplicitConversionName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_Constructor1()
{
var source = @"
/// <summary>
/// See <see cref=""explicit operator int(int)""/>.
/// </summary>
class op_Explicit
{
op_Explicit(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.ExplicitConversionName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_Constructor2()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(int, int)""/>.
/// </summary>
class op_Implicit
{
op_Implicit(int x, int y) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.ImplicitConversionName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void CrefSymbolInfo()
{
var source = @"
/// <summary>
/// See <see cref=""C.M""/>.
/// </summary>
class C
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M");
var actualSymbol = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedSymbol.ISymbol, actualSymbol);
}
[Fact]
public void CrefPartSymbolInfo1()
{
var source = @"
/// <summary>
/// See <see cref=""C.M""/>.
/// </summary>
class C
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (QualifiedCrefSyntax)GetCrefSyntaxes(compilation).Single();
var expectedTypeSymbol = ((Compilation)compilation).GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var expectedMethodSymbol = expectedTypeSymbol.GetMember<IMethodSymbol>("M");
var actualTypeSymbol = model.GetSymbolInfo(crefSyntax.Container).Symbol;
Assert.Equal(expectedTypeSymbol, actualTypeSymbol);
var actualMethodSymbol1 = model.GetSymbolInfo(crefSyntax.Member).Symbol;
Assert.Equal(actualMethodSymbol1, expectedMethodSymbol);
var actualMethodSymbol2 = model.GetSymbolInfo(((NameMemberCrefSyntax)crefSyntax.Member).Name).Symbol;
Assert.Equal(actualMethodSymbol2, expectedMethodSymbol);
}
[Fact]
public void CrefPartSymbolInfo2()
{
var source = @"
/// <summary>
/// See <see cref=""A{J}.B{K}.M{L}(int, J, K, L, A{L}, A{int}.B{K})""/>.
/// </summary>
class A<T>
{
class B<U>
{
internal void M<V>(int s, T t, U u, V v, A<V> w, A<int>.B<U> x) { }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (QualifiedCrefSyntax)GetCrefSyntaxes(compilation).Single();
var nameMemberSyntax = (NameMemberCrefSyntax)crefSyntax.Member;
var containingTypeSyntax = (QualifiedNameSyntax)crefSyntax.Container;
var typeA = ((Compilation)compilation).GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var typeB = typeA.GetMember<INamedTypeSymbol>("B");
var method = typeB.GetMember<IMethodSymbol>("M");
var typeInt = ((Compilation)compilation).GetSpecialType(SpecialType.System_Int32);
// A{J}
ITypeParameterSymbol actualJ;
{
var left = (GenericNameSyntax)containingTypeSyntax.Left;
var actualTypeA = (INamedTypeSymbol)model.GetSymbolInfo(left).Symbol;
Assert.False(actualTypeA.IsDefinition);
actualJ = (ITypeParameterSymbol)actualTypeA.TypeArguments.Single();
Assert.Equal(typeA, actualTypeA.OriginalDefinition);
var actualTypeArgument = model.GetSymbolInfo(left.TypeArgumentList.Arguments.Single()).Symbol;
Assert.Equal(actualJ, actualTypeArgument);
}
// B{K}
ITypeParameterSymbol actualK;
{
var actualTypeB = (INamedTypeSymbol)model.GetSymbolInfo(containingTypeSyntax).Symbol;
Assert.False(actualTypeB.IsDefinition);
actualK = (ITypeParameterSymbol)actualTypeB.TypeArguments.Single();
Assert.Equal(typeB, actualTypeB.OriginalDefinition);
var right = (GenericNameSyntax)containingTypeSyntax.Right;
Assert.Equal(actualTypeB, model.GetSymbolInfo(right).Symbol);
var actualTypeArgument = model.GetSymbolInfo(right.TypeArgumentList.Arguments.Single()).Symbol;
Assert.Equal(actualK, actualTypeArgument);
}
// M{L}
ITypeParameterSymbol actualL;
{
var actualMethod = (IMethodSymbol)model.GetSymbolInfo(crefSyntax).Symbol;
Assert.False(actualMethod.IsDefinition);
actualL = (ITypeParameterSymbol)actualMethod.TypeArguments.Single();
Assert.Equal(method, actualMethod.OriginalDefinition);
Assert.Equal(actualMethod, model.GetSymbolInfo(crefSyntax.Member).Symbol);
Assert.Equal(actualMethod, model.GetSymbolInfo(nameMemberSyntax.Name).Symbol);
var actualParameterTypes = nameMemberSyntax.Parameters.Parameters.Select(syntax => model.GetSymbolInfo(syntax.Type).Symbol).ToArray();
Assert.Equal(6, actualParameterTypes.Length);
Assert.Equal(typeInt, actualParameterTypes[0]);
Assert.Equal(actualJ, actualParameterTypes[1]);
Assert.Equal(actualK, actualParameterTypes[2]);
Assert.Equal(actualL, actualParameterTypes[3]);
Assert.Equal(typeA.Construct(actualL), actualParameterTypes[4]);
Assert.Equal(typeA.Construct(typeInt).GetMember<INamedTypeSymbol>("B").Construct(actualK), actualParameterTypes[5]);
}
}
[Fact]
public void IndexerCrefSymbolInfo()
{
var source = @"
/// <summary>
/// See <see cref=""this[int]""/>.
/// </summary>
class C
{
int this[int x] { get { return 0; } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (IndexerMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var expectedIndexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Single().ISymbol;
var actualIndexer = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedIndexer, actualIndexer);
var expectedParameterType = compilation.GetSpecialType(SpecialType.System_Int32).ISymbol;
var actualParameterType = model.GetSymbolInfo(crefSyntax.Parameters.Parameters.Single().Type).Symbol;
Assert.Equal(expectedParameterType, actualParameterType);
}
[Fact]
public void OperatorCrefSymbolInfo()
{
var source = @"
/// <summary>
/// See <see cref=""operator +(C)""/>.
/// </summary>
class C
{
public static int operator +(C c) { return 0; }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (OperatorMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var typeC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var expectedOperator = typeC.GetMember<MethodSymbol>(WellKnownMemberNames.UnaryPlusOperatorName).ISymbol;
var actualOperator = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedOperator, actualOperator);
var expectedParameterType = typeC.ISymbol;
var actualParameterType = model.GetSymbolInfo(crefSyntax.Parameters.Parameters.Single().Type).Symbol;
Assert.Equal(expectedParameterType, actualParameterType);
}
[Fact]
public void ConversionOperatorCrefSymbolInfo()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(C)""/>.
/// </summary>
class C
{
public static implicit operator int(C c) { return 0; }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (ConversionOperatorMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var typeC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var expectedOperator = typeC.GetMember<MethodSymbol>(WellKnownMemberNames.ImplicitConversionName).ISymbol;
var actualOperator = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedOperator, actualOperator);
var expectedParameterType = typeC.ISymbol;
var actualParameterType = model.GetSymbolInfo(crefSyntax.Parameters.Parameters.Single().Type).Symbol;
Assert.Equal(expectedParameterType, actualParameterType);
var expectedReturnType = compilation.GetSpecialType(SpecialType.System_Int32).ISymbol;
var actualReturnType = model.GetSymbolInfo(crefSyntax.Type).Symbol;
Assert.Equal(expectedReturnType, actualReturnType);
}
[Fact]
public void CrefSymbolInfo_None()
{
var source = @"
/// <summary>
/// See <see cref=""C.N""/>.
/// </summary>
class C
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[Fact]
public void CrefSymbolInfo_Ambiguous1()
{
var source = @"
/// <summary>
/// See <see cref=""M()""/>.
/// </summary>
class C
{
int M { get; set; }
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason); // Candidates have different kinds.
Assert.Equal(2, info.CandidateSymbols.Length);
}
[Fact]
public void CrefSymbolInfo_Ambiguous2()
{
var source = @"
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class C
{
void M() { }
void M(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason); // No parameter list.
Assert.Equal(2, info.CandidateSymbols.Length);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution1()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}.M(A)""/>.
/// </summary>
class C<T, U>
{
void M(T t) { }
void M(U u) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.Equal(MethodKind.Ordinary, ((IMethodSymbol)info.CandidateSymbols[0]).MethodKind);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution2()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}.this[A]""/>.
/// </summary>
class C<T, U>
{
int this[T t] { }
int this[U u] { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.True(((IPropertySymbol)info.CandidateSymbols[0]).IsIndexer);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution3()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}.explicit operator C{A, A}(A)""/>.
/// </summary>
class C<T, U>
{
public static explicit operator C<T, U>(T t) { return null; }
public static explicit operator C<T, U>(U u) { return null; }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.Equal(MethodKind.Conversion, ((IMethodSymbol)info.CandidateSymbols[0]).MethodKind);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution4()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}.operator +(C{A, A}, A)""/>.
/// </summary>
class C<T, U>
{
public static object operator +(C<T, U> c, T t) { return null; }
public static object operator +(C<T, U> c, U u) { return null; }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.Equal(MethodKind.UserDefinedOperator, ((IMethodSymbol)info.CandidateSymbols[0]).MethodKind);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution5()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}(A)""/>.
/// </summary>
class C<T, U>
{
C(T t) { }
C(U u) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)info.CandidateSymbols[0]).MethodKind);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution()
{
var source = @"
/// <summary>
/// See <see cref=""C.N""/>.
/// </summary>
class C
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[Fact]
public void CrefLookup()
{
var source = @"
/// <summary>
/// See <see cref=""C{U}""/>.
/// </summary>
class C<T>
{
void M() { }
}
class Outer
{
private class Inner { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var global = compilation.GlobalNamespace;
var typeC = global.GetMember<NamedTypeSymbol>("C");
var methodM = typeC.GetMember<MethodSymbol>("M");
var typeOuter = global.GetMember<NamedTypeSymbol>("Outer");
var typeInner = typeOuter.GetMember<NamedTypeSymbol>("Inner");
int position = source.IndexOf("{U}", StringComparison.Ordinal);
AssertEx.SetEqual(model.LookupSymbols(position).Select(SymbolExtensions.ToTestDisplayString),
// Implicit type parameter
"U",
// From source declarations
"T",
"void C<T>.M()",
"C<T>",
// Boring
"System",
// Inaccessible and boring
"FXAssembly",
"ThisAssembly",
"AssemblyRef",
"SRETW",
"Outer",
"Microsoft");
// Consider inaccessible symbols, as in Dev11
Assert.Equal(typeInner.GetPublicSymbol(), model.LookupSymbols(position, typeOuter.GetPublicSymbol(), typeInner.Name).Single());
}
[Fact]
public void InvalidIdentifier()
{
var source = @"
/// <summary>
/// Error <see cref=""2""/>
/// Error <see cref=""3A""/>
/// Error <see cref=""@4""/>
/// Error <see cref=""@5""/>
/// </summary>
class C
{
}
";
// CONSIDER: The "Unexpected character" warnings are redundant.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute '2'
// /// Error <see cref="2"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "2").WithArguments("2"),
// (3,22): warning CS1658: Identifier expected. See also error CS1001.
// /// Error <see cref="2"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "2").WithArguments("Identifier expected", "1001"),
// (3,22): warning CS1658: Unexpected character '2'. See also error CS1056.
// /// Error <see cref="2"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '2'", "1056"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute '3A'
// /// Error <see cref="3A"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "3").WithArguments("3A"),
// (4,22): warning CS1658: Identifier expected. See also error CS1001.
// /// Error <see cref="3A"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Identifier expected", "1001"),
// (4,22): warning CS1658: Unexpected character '3'. See also error CS1056.
// /// Error <see cref="3A"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '3'", "1056"),
// (5,22): warning CS1584: XML comment has syntactically incorrect cref attribute '@4'
// /// Error <see cref="@4"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "@").WithArguments("@4"),
// (5,22): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
// /// Error <see cref="@4"/>
Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, ""),
// (5,23): warning CS1658: Unexpected character '4'. See also error CS1056.
// /// Error <see cref="@4"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '4'", "1056"),
// (6,22): warning CS1584: XML comment has syntactically incorrect cref attribute '@5'
// /// Error <see cref="@5"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "@").WithArguments("@5"),
// (6,22): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
// /// Error <see cref="@5"/>
Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, ""),
// (6,27): warning CS1658: Unexpected character '5'. See also error CS1056.
// /// Error <see cref="@5"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '5'", "1056"));
}
[Fact]
public void InvalidIdentifier2()
{
var source = @"
/// <summary>
/// Error <see cref=""G<3>""/>
/// Error <see cref=""G{T}.M<3>""/>
/// </summary>
class G<T>
{
void M<U>(G<G<U>>) { }
}
";
// CONSIDER: There's room for improvement here, but it's a corner case.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G<3>'
// /// Error <see cref="G<3>"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G<").WithArguments("G<3>"),
// (3,27): warning CS1658: Identifier expected. See also error CS1001.
// /// Error <see cref="G<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Identifier expected", "1001"),
// (3,27): warning CS1658: Syntax error, '>' expected. See also error CS1003.
// /// Error <see cref="G<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Syntax error, '>' expected", "1003"),
// (3,27): warning CS1658: Unexpected character '3'. See also error CS1056.
// /// Error <see cref="G<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '3'", "1056"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{T}.M<3>'
// /// Error <see cref="G{T}.M<3>"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{T}.M<").WithArguments("G{T}.M<3>"),
// (4,32): warning CS1658: Identifier expected. See also error CS1001.
// /// Error <see cref="G{T}.M<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Identifier expected", "1001"),
// (4,32): warning CS1658: Syntax error, '>' expected. See also error CS1003.
// /// Error <see cref="G{T}.M<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Syntax error, '>' expected", "1003"),
// (4,32): warning CS1658: Unexpected character '3'. See also error CS1056.
// /// Error <see cref="G{T}.M<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '3'", "1056"),
// (8,22): error CS1001: Identifier expected
// void M<U>(G<G<U>>) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")"));
}
[Fact]
public void ERR_TypeParamMustBeIdentifier2()
{
var source = @"
/// <summary>
/// Error <see cref=""G{int}""/>
/// Error <see cref=""G{A.B}""/>
/// Error <see cref=""G{G{T}}}""/>
///
/// Error <see cref=""G{T}.M{int}""/>
/// Error <see cref=""G{T}.M{A.B}""/>
/// Error <see cref=""G{T}.M{G{T}}""/>
///
/// Fine <see cref=""G{T}.M{U}(int)""/>
/// Fine <see cref=""G{T}.M{U}(A.B)""/>
/// Fine <see cref=""G{T}.M{U}(G{G{U}})""/>
/// </summary>
class G<T>
{
void M<U>(int x) { }
void M<U>(A.B b) { }
void M<U>(G<G<U>> g) { }
}
class A
{
public class B
{
}
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{int}'
// /// Error <see cref="G{int}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{int}").WithArguments("G{int}"),
// (3,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{int}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{A.B}'
// /// Error <see cref="G{A.B}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{A.B}").WithArguments("G{A.B}"),
// (4,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{A.B}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "A.B").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (5,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{G{T}}}'
// /// Error <see cref="G{G{T}}}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{G{T}}").WithArguments("G{G{T}}}"),
// (5,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{G{T}}}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "G{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (7,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{T}.M{int}'
// /// Error <see cref="G{T}.M{int}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{T}.M{int}").WithArguments("G{T}.M{int}"),
// (7,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{T}.M{int}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (8,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{T}.M{A.B}'
// /// Error <see cref="G{T}.M{A.B}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{T}.M{A.B}").WithArguments("G{T}.M{A.B}"),
// (8,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{T}.M{A.B}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "A.B").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (9,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{T}.M{G{T}}'
// /// Error <see cref="G{T}.M{G{T}}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{T}.M{G{T}}").WithArguments("G{T}.M{G{T}}"),
// (9,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{T}.M{G{T}}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "G{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"));
}
[Fact]
public void WRN_DuplicateParamTag()
{
var source = @"
class C
{
/// <param name=""x""/>
/// <param name=""x""/> -- warning
void M(int x) { }
/// <param name=""value""/>
/// <param name=""value""/> -- fine, as in dev11
int P { get; set; }
/// <param name=""x""/>
/// <param name=""y""/>
/// <param name=""value""/>
/// <param name=""x""/> -- warning
/// <param name=""y""/> -- warning
/// <param name=""value""/> -- fine, as in dev11
int this[int x, int y] { get { return 0; } set { } }
}
partial class P
{
/// <param name=""x""/>
partial void M(int x);
}
partial class P
{
/// <param name=""x""/> -- fine, other is dropped
partial void M(int x) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (5,16): warning CS1571: XML comment has a duplicate param tag for 'x'
// /// <param name="x"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""x""").WithArguments("x"),
// (15,16): warning CS1571: XML comment has a duplicate param tag for 'x'
// /// <param name="x"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""x""").WithArguments("x"),
// (16,16): warning CS1571: XML comment has a duplicate param tag for 'y'
// /// <param name="y"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""y""").WithArguments("y"));
}
[Fact]
public void WRN_UnmatchedParamTag()
{
var source = @"
class C
{
/// <param name=""q""/>
/// <param name=""value""/>
void M(int x) { }
/// <param name=""x""/>
int P { get; set; }
/// <param name=""q""/>
int this[int x, int y] { get { return 0; } set { } }
/// <param name=""q""/>
/// <param name=""value""/>
event System.Action E;
}
partial class P
{
/// <param name=""x""/>
partial void M(int y);
}
partial class P
{
/// <param name=""y""/>
partial void M(int x) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (28,18): warning CS8826: Partial method declarations 'void P.M(int y)' and 'void P.M(int x)' have signature differences.
// partial void M(int x) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void P.M(int y)", "void P.M(int x)").WithLocation(28, 18),
// (16,25): warning CS0067: The event 'C.E' is never used
// event System.Action E;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(16, 25),
// (4,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q").WithLocation(4, 22),
// (5,22): warning CS1572: XML comment has a param tag for 'value', but there is no parameter by that name
// /// <param name="value"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "value").WithArguments("value").WithLocation(5, 22),
// (6,16): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.M(int)' (but other parameters do)
// void M(int x) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.M(int)").WithLocation(6, 16),
// (8,22): warning CS1572: XML comment has a param tag for 'x', but there is no parameter by that name
// /// <param name="x"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "x").WithArguments("x").WithLocation(8, 22),
// (11,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q").WithLocation(11, 22),
// (12,18): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.this[int, int]' (but other parameters do)
// int this[int x, int y] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.this[int, int]").WithLocation(12, 18),
// (12,25): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'C.this[int, int]' (but other parameters do)
// int this[int x, int y] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "C.this[int, int]").WithLocation(12, 25),
// (14,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q").WithLocation(14, 22),
// (15,22): warning CS1572: XML comment has a param tag for 'value', but there is no parameter by that name
// /// <param name="value"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "value").WithArguments("value").WithLocation(15, 22),
// (27,22): warning CS1572: XML comment has a param tag for 'y', but there is no parameter by that name
// /// <param name="y"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "y").WithArguments("y").WithLocation(27, 22),
// (28,24): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'P.M(int)' (but other parameters do)
// partial void M(int x) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "P.M(int)").WithLocation(28, 24),
// (21,22): warning CS1572: XML comment has a param tag for 'x', but there is no parameter by that name
// /// <param name="x"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "x").WithArguments("x").WithLocation(21, 22),
// (22,24): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'P.M(int)' (but other parameters do)
// partial void M(int y);
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "P.M(int)").WithLocation(22, 24));
}
[Fact]
public void WRN_MissingParamTag()
{
var source = @"
class C
{
/// <param name=""x""/>
void M(int x, int y) { }
/// <param name=""x""/>
int this[int x, int y] { get { return 0; } set { } }
/// <param name=""value""/>
int this[int x] { get { return 0; } set { } }
}
partial class P
{
/// <param name=""q""/>
partial void M(int q, int r);
}
partial class P
{
/// <param name=""x""/>
partial void M(int x, int y) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (23,18): warning CS8826: Partial method declarations 'void P.M(int q, int r)' and 'void P.M(int x, int y)' have signature differences.
// partial void M(int x, int y) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void P.M(int q, int r)", "void P.M(int x, int y)").WithLocation(23, 18),
// (5,23): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'C.M(int, int)' (but other parameters do)
// void M(int x, int y) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "C.M(int, int)").WithLocation(5, 23),
// (8,25): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'C.this[int, int]' (but other parameters do)
// int this[int x, int y] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "C.this[int, int]").WithLocation(8, 25),
// (11,18): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.this[int]' (but other parameters do)
// int this[int x] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.this[int]").WithLocation(11, 18),
// (23,31): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'P.M(int, int)' (but other parameters do)
// partial void M(int x, int y) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "P.M(int, int)").WithLocation(23, 31),
// (17,31): warning CS1573: Parameter 'r' has no matching param tag in the XML comment for 'P.M(int, int)' (but other parameters do)
// partial void M(int q, int r);
Diagnostic(ErrorCode.WRN_MissingParamTag, "r").WithArguments("r", "P.M(int, int)").WithLocation(17, 31));
}
[Fact]
public void WRN_DuplicateTypeParamTag()
{
var source = @"
/// <typeparam name=""T""/>
/// <typeparam name=""T""/> -- warning
class C<T>
{
/// <typeparam name=""U""/>
/// <typeparam name=""U""/> -- warning
void M<U>() { }
}
/// <typeparam name=""T""/>
partial class P<T>
{
/// <typeparam name=""U""/>
partial void M1<U>();
/// <typeparam name=""U""/>
/// <typeparam name=""U""/> -- warning
partial void M2<U>();
}
/// <typeparam name=""T""/> -- warning
partial class P<T>
{
/// <typeparam name=""U""/> -- fine, other is dropped
partial void M1<U>() { }
/// <typeparam name=""U""/>
/// <typeparam name=""U""/> -- warning
partial void M2<U>() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,16): warning CS1710: XML comment has a duplicate typeparam tag for 'T'
// /// <typeparam name="T"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""T""").WithArguments("T"),
// (7,20): warning CS1710: XML comment has a duplicate typeparam tag for 'U'
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""U""").WithArguments("U"),
// (22,16): warning CS1710: XML comment has a duplicate typeparam tag for 'T'
// /// <typeparam name="T"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""T""").WithArguments("T"),
// (29,20): warning CS1710: XML comment has a duplicate typeparam tag for 'U'
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""U""").WithArguments("U"),
// (18,20): warning CS1710: XML comment has a duplicate typeparam tag for 'U'
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""U""").WithArguments("U"));
}
[Fact]
public void WRN_UnmatchedParamRefTag()
{
var source = @"
class C
{
/// <paramref name=""q""/>
/// <paramref name=""value""/>
void M(int x) { }
/// <paramref name=""x""/>
int P { get; set; }
/// <paramref name=""q""/>
int this[int x, int y] { get { return 0; } set { } }
/// <paramref name=""q""/>
/// <paramref name=""value""/>
event System.Action E;
}
partial class P
{
/// <paramref name=""x""/>
partial void M(int y);
}
partial class P
{
/// <paramref name=""y""/>
partial void M(int x) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (28,18): warning CS8826: Partial method declarations 'void P.M(int y)' and 'void P.M(int x)' have signature differences.
// partial void M(int x) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void P.M(int y)", "void P.M(int x)").WithLocation(28, 18),
// (16,25): warning CS0067: The event 'C.E' is never used
// event System.Action E;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(16, 25),
// (4,25): warning CS1734: XML comment on 'C.M(int)' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.M(int)").WithLocation(4, 25),
// (5,25): warning CS1734: XML comment on 'C.M(int)' has a paramref tag for 'value', but there is no parameter by that name
// /// <paramref name="value"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "value").WithArguments("value", "C.M(int)").WithLocation(5, 25),
// (8,25): warning CS1734: XML comment on 'C.P' has a paramref tag for 'x', but there is no parameter by that name
// /// <paramref name="x"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "x").WithArguments("x", "C.P").WithLocation(8, 25),
// (11,25): warning CS1734: XML comment on 'C.this[int, int]' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.this[int, int]").WithLocation(11, 25),
// (14,25): warning CS1734: XML comment on 'C.E' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.E").WithLocation(14, 25),
// (15,25): warning CS1734: XML comment on 'C.E' has a paramref tag for 'value', but there is no parameter by that name
// /// <paramref name="value"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "value").WithArguments("value", "C.E").WithLocation(15, 25),
// (27,25): warning CS1734: XML comment on 'P.M(int)' has a paramref tag for 'y', but there is no parameter by that name
// /// <paramref name="y"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "y").WithArguments("y", "P.M(int)").WithLocation(27, 25),
// (21,25): warning CS1734: XML comment on 'P.M(int)' has a paramref tag for 'x', but there is no parameter by that name
// /// <paramref name="x"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "x").WithArguments("x", "P.M(int)").WithLocation(21, 25));
}
[Fact]
public void DuplicateParameterName()
{
var source = @"
class C
{
/// <param name=""x""/>
/// <paramref name=""x""/>
/// <param name=""q""/>
/// <paramref name=""q""/>
void M(int x, int x) { }
/// <param name=""x""/>
/// <paramref name=""x""/>
/// <param name=""q""/>
/// <paramref name=""q""/>
int this[int x, int x] { get { return 0; } set { } }
/// <param name=""q""/>
void M(double x, double x) { }
/// <param name=""q""/>
double this[double x, double x] { get { return 0; } set { } }
}
";
// These diagnostics don't exactly match dev11, but they seem reasonable and the main point
// of the test is to confirm that we don't crash.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (17,29): error CS0100: The parameter name 'x' is a duplicate
// void M(double x, double x) { }
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x"),
// (8,23): error CS0100: The parameter name 'x' is a duplicate
// void M(int x, int x) { }
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x"), // NOTE: double-reported in dev11
// (14,25): error CS0100: The parameter name 'x' is a duplicate
// int this[int x, int x] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x"),
// (20,34): error CS0100: The parameter name 'x' is a duplicate
// double this[double x, double x] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x"), // NOTE: double-reported in dev11
// Dev11 doesn't report these, but they seem reasonable (even desirable).
// (6,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"),
// (7,25): warning CS1734: XML comment on 'C.M(int, int)' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.M(int, int)"),
// These match dev11.
// (12,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"),
// (13,25): warning CS1734: XML comment on 'C.this[int, int]' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.this[int, int]"),
// Dev11 doesn't report these, but they seem reasonable (even desirable).
// (16,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"),
// (17,19): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.M(double, double)' (but other parameters do)
// void M(double x, double x) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.M(double, double)"),
// (17,29): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.M(double, double)' (but other parameters do)
// void M(double x, double x) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.M(double, double)"),
// These match dev11.
// (19,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"),
// (20,24): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.this[double, double]' (but other parameters do)
// double this[double x, double x] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.this[double, double]"),
// (20,34): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.this[double, double]' (but other parameters do)
// double this[double x, double x] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.this[double, double]"));
}
[Fact]
public void DuplicateTypeParameterName()
{
var source = @"
/// <typeparam name=""T""/>
/// <typeparamref name=""T""/>
/// <typeparam name=""Q""/>
/// <typeparamref name=""Q""/>
class C<T, T>
{
/// <typeparam name=""U""/>
/// <typeparamref name=""U""/>
/// <typeparam name=""Q""/>
/// <typeparamref name=""Q""/>
void M<U, U>() { }
}
/// <typeparam name=""Q""/>
class D<T, T>
{
/// <typeparam name=""Q""/>
void M<U, U>() { }
}
";
// Dev11 stops after the CS0692s on the types.
// We just want to confirm that the errors are sensible and we don't crash.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (6,12): error CS0692: Duplicate type parameter 'T'
// class C<T, T>
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T"),
// (16,12): error CS0692: Duplicate type parameter 'T'
// class D<T, T>
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T"),
// (12,15): error CS0692: Duplicate type parameter 'U'
// void M<U, U>() { }
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U"),
// (19,15): error CS0692: Duplicate type parameter 'U'
// void M<U, U>() { }
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U"),
// (4,22): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (5,25): warning CS1735: XML comment on 'C<T, T>' has a typeparamref tag for 'Q', but there is no type parameter by that name
// /// <typeparamref name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "Q").WithArguments("Q", "C<T, T>"),
// (10,26): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (11,29): warning CS1735: XML comment on 'C<T, T>.M<U, U>()' has a typeparamref tag for 'Q', but there is no type parameter by that name
// /// <typeparamref name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "Q").WithArguments("Q", "C<T, T>.M<U, U>()"),
// (15,22): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (16,9): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'D<T, T>' (but other type parameters do)
// class D<T, T>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "D<T, T>"),
// (16,12): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'D<T, T>' (but other type parameters do)
// class D<T, T>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "D<T, T>"),
// (18,26): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (19,12): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'D<T, T>.M<U, U>()' (but other type parameters do)
// void M<U, U>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "D<T, T>.M<U, U>()"),
// (19,15): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'D<T, T>.M<U, U>()' (but other type parameters do)
// void M<U, U>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "D<T, T>.M<U, U>()"));
}
[Fact]
public void WRN_UnmatchedTypeParamTag()
{
var source = @"
/// <typeparam name=""T""/> -- warning
class C
{
/// <typeparam name=""T""/> -- warning
void M() { }
}
/// <typeparam name=""T""/>
/// <typeparam name=""U""/> -- warning
class C<T>
{
/// <typeparam name=""U""/>
/// <typeparam name=""V""/> -- warning
void M<U>() { }
}
/// <typeparam name=""U""/> -- warning
partial class P<T>
{
/// <typeparam name=""V""/> -- warning
partial void M1<U>();
}
/// <typeparam name=""V""/> -- warning
partial class P<T>
{
/// <typeparam name=""U""/> -- warning
partial void M1<V>() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (29,18): warning CS8826: Partial method declarations 'void P<T>.M1<U>()' and 'void P<T>.M1<V>()' have signature differences.
// partial void M1<V>() { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M1").WithArguments("void P<T>.M1<U>()", "void P<T>.M1<V>()").WithLocation(29, 18),
// (2,22): warning CS1711: XML comment has a typeparam tag for 'T', but there is no type parameter by that name
// /// <typeparam name="T"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "T").WithArguments("T"),
// (5,26): warning CS1711: XML comment has a typeparam tag for 'T', but there is no type parameter by that name
// /// <typeparam name="T"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "T").WithArguments("T"),
// (10,22): warning CS1711: XML comment has a typeparam tag for 'U', but there is no type parameter by that name
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "U").WithArguments("U"),
// (14,26): warning CS1711: XML comment has a typeparam tag for 'V', but there is no type parameter by that name
// /// <typeparam name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "V").WithArguments("V"),
// (18,22): warning CS1711: XML comment has a typeparam tag for 'U', but there is no type parameter by that name
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "U").WithArguments("U"),
// (25,22): warning CS1711: XML comment has a typeparam tag for 'V', but there is no type parameter by that name
// /// <typeparam name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "V").WithArguments("V"),
// (28,26): warning CS1711: XML comment has a typeparam tag for 'U', but there is no type parameter by that name
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "U").WithArguments("U"),
// (21,26): warning CS1711: XML comment has a typeparam tag for 'V', but there is no type parameter by that name
// /// <typeparam name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "V").WithArguments("V"),
// (29,21): warning CS1712: Type parameter 'V' has no matching typeparam tag in the XML comment on 'P<T>.M1<V>()' (but other type parameters do)
// partial void M1<V>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "V").WithArguments("V", "P<T>.M1<V>()"),
// (19,17): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'P<T>' (but other type parameters do)
// partial class P<T>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "P<T>"),
// (22,21): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'P<T>.M1<U>()' (but other type parameters do)
// partial void M1<U>();
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "P<T>.M1<U>()"));
}
[Fact]
public void WRN_MissingTypeParamTag()
{
var source = @"
/// <typeparam name=""T""/>
class C<T, U>
{
/// <typeparam name=""V""/>
void M<V, W, X>() { }
}
/// <typeparam name=""Q""/>
class C<T>
{
/// <typeparam name=""Q""/>
void M<U>() { }
}
/// <typeparam name=""T""/>
partial class P<T, U>
{
/// <typeparam name=""V""/>
partial void M1<V, W>();
}
/// <typeparam name=""U""/>
partial class P<T, U>
{
/// <typeparam name=""W""/>
partial void M1<V, W>() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,12): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'C<T, U>' (but other type parameters do)
// class C<T, U>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "C<T, U>"),
// (6,15): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'C<T, U>.M<V, W, X>()' (but other type parameters do)
// void M<V, W, X>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "W").WithArguments("W", "C<T, U>.M<V, W, X>()"),
// (6,18): warning CS1712: Type parameter 'X' has no matching typeparam tag in the XML comment on 'C<T, U>.M<V, W, X>()' (but other type parameters do)
// void M<V, W, X>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "X").WithArguments("X", "C<T, U>.M<V, W, X>()"),
// (9,22): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (10,9): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'C<T>' (but other type parameters do)
// class C<T>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "C<T>"),
// (12,26): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (13,12): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'C<T>.M<U>()' (but other type parameters do)
// void M<U>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "C<T>.M<U>()"),
// (27,21): warning CS1712: Type parameter 'V' has no matching typeparam tag in the XML comment on 'P<T, U>.M1<V, W>()' (but other type parameters do)
// partial void M1<V, W>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "V").WithArguments("V", "P<T, U>.M1<V, W>()"),
// (20,24): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'P<T, U>.M1<V, W>()' (but other type parameters do)
// partial void M1<V, W>();
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "W").WithArguments("W", "P<T, U>.M1<V, W>()"));
}
[Fact]
public void WRN_UnmatchedTypeParamRefTag()
{
var source = @"
/// <typeparamref name=""T""/> -- warning
class C
{
/// <typeparamref name=""T""/> -- warning
void M() { }
}
/// <typeparamref name=""T""/>
/// <typeparamref name=""U""/> -- warning
class C<T>
{
/// <typeparamref name=""U""/>
/// <typeparamref name=""V""/> -- warning
void M<U>() { }
}
/// <typeparamref name=""U""/> -- warning
partial class P<T>
{
/// <typeparamref name=""V""/> -- warning
partial void M1<U>();
}
/// <typeparamref name=""V""/> -- warning
partial class P<T>
{
/// <typeparamref name=""U""/> -- warning
partial void M1<V>() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (29,18): warning CS8826: Partial method declarations 'void P<T>.M1<U>()' and 'void P<T>.M1<V>()' have signature differences.
// partial void M1<V>() { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M1").WithArguments("void P<T>.M1<U>()", "void P<T>.M1<V>()").WithLocation(29, 18),
// (2,25): warning CS1735: XML comment on 'C' has a typeparamref tag for 'T', but there is no type parameter by that name
// /// <typeparamref name="T"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "T").WithArguments("T", "C"),
// (5,29): warning CS1735: XML comment on 'C.M()' has a typeparamref tag for 'T', but there is no type parameter by that name
// /// <typeparamref name="T"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "T").WithArguments("T", "C.M()"),
// (10,25): warning CS1735: XML comment on 'C<T>' has a typeparamref tag for 'U', but there is no type parameter by that name
// /// <typeparamref name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "U").WithArguments("U", "C<T>"),
// (14,29): warning CS1735: XML comment on 'C<T>.M<U>()' has a typeparamref tag for 'V', but there is no type parameter by that name
// /// <typeparamref name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "V").WithArguments("V", "C<T>.M<U>()"),
// (18,25): warning CS1735: XML comment on 'P<T>' has a typeparamref tag for 'U', but there is no type parameter by that name
// /// <typeparamref name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "U").WithArguments("U", "P<T>"),
// (25,25): warning CS1735: XML comment on 'P<T>' has a typeparamref tag for 'V', but there is no type parameter by that name
// /// <typeparamref name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "V").WithArguments("V", "P<T>"),
// (28,29): warning CS1735: XML comment on 'P<T>.M1<V>()' has a typeparamref tag for 'U', but there is no type parameter by that name
// /// <typeparamref name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "U").WithArguments("U", "P<T>.M1<V>()"),
// (21,29): warning CS1735: XML comment on 'P<T>.M1<U>()' has a typeparamref tag for 'V', but there is no type parameter by that name
// /// <typeparamref name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "V").WithArguments("V", "P<T>.M1<U>()"));
}
[Fact]
public void WRN_MissingXMLComment_Accessibility()
{
var source = @"
/// <summary/>
public class C
{
public void M1() { }
protected internal void M2() { }
protected void M3() { }
internal void M4() { }
private void M5() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (5,17): warning CS1591: Missing XML comment for publicly visible type or member 'C.M1()'
// public void M1() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M1").WithArguments("C.M1()"),
// (6,29): warning CS1591: Missing XML comment for publicly visible type or member 'C.M2()'
// protected internal void M2() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M2").WithArguments("C.M2()"),
// (7,20): warning CS1591: Missing XML comment for publicly visible type or member 'C.M3()'
// protected void M3() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M3").WithArguments("C.M3()"));
}
[Fact]
public void WRN_MissingXMLComment_EffectiveAccessibility()
{
var source = @"
/// <summary/>
public class A
{
/// <summary/>
public class B1
{
/// <summary/>
public class C
{
public void M1() { }
}
}
/// <summary/>
protected internal class B2
{
/// <summary/>
public class C
{
public void M2() { }
}
}
/// <summary/>
protected class B3
{
/// <summary/>
public class C
{
public void M3() { }
}
}
internal class B4
{
public class C
{
public void M4() { }
}
}
private class B5
{
public class C
{
public void M5() { }
}
}
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (11,25): warning CS1591: Missing XML comment for publicly visible type or member 'A.B1.C.M1()'
// public void M1() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M1").WithArguments("A.B1.C.M1()"),
// (21,25): warning CS1591: Missing XML comment for publicly visible type or member 'A.B2.C.M2()'
// public void M2() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M2").WithArguments("A.B2.C.M2()"),
// (31,25): warning CS1591: Missing XML comment for publicly visible type or member 'A.B3.C.M3()'
// public void M3() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M3").WithArguments("A.B3.C.M3()"));
}
[Fact]
public void WRN_MissingXMLComment_Kind()
{
var source = @"
/// <summary/>
public class C
{
public class Class { }
public void Method() { }
public int Field;
public int Property { get; set; }
public int this[int x] { get { return 0; } set { } }
public event System.Action FieldLikeEvent;
public event System.Action Event { add { } remove { } }
public delegate void Delegate();
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (5,18): warning CS1591: Missing XML comment for publicly visible type or member 'C.Class'
// public class Class { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Class").WithArguments("C.Class"),
// (6,17): warning CS1591: Missing XML comment for publicly visible type or member 'C.Method()'
// public void Method() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Method").WithArguments("C.Method()"),
// (7,16): warning CS1591: Missing XML comment for publicly visible type or member 'C.Field'
// public int Field;
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Field").WithArguments("C.Field"),
// (8,16): warning CS1591: Missing XML comment for publicly visible type or member 'C.Property'
// public int Property { get; set; }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Property").WithArguments("C.Property"),
// (9,16): warning CS1591: Missing XML comment for publicly visible type or member 'C.this[int]'
// public int this[int x] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "this").WithArguments("C.this[int]"),
// (10,32): warning CS1591: Missing XML comment for publicly visible type or member 'C.FieldLikeEvent'
// public event System.Action FieldLikeEvent;
Diagnostic(ErrorCode.WRN_MissingXMLComment, "FieldLikeEvent").WithArguments("C.FieldLikeEvent"),
// (11,32): warning CS1591: Missing XML comment for publicly visible type or member 'C.Event'
// public event System.Action Event { add { } remove { } }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Event").WithArguments("C.Event"),
// (12,26): warning CS1591: Missing XML comment for publicly visible type or member 'C.Delegate'
// public delegate void Delegate();
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Delegate").WithArguments("C.Delegate"),
// (10,32): warning CS0067: The event 'C.FieldLikeEvent' is never used
// public event System.Action FieldLikeEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "FieldLikeEvent").WithArguments("C.FieldLikeEvent"));
}
[Fact]
public void WRN_MissingXMLComment_Interface()
{
var source = @"
interface I
{
void M();
}
";
// As in dev11, doesn't count since the *declared* accessibility is not public.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics();
}
[Fact]
public void WRN_MissingXMLComment_PartialClass()
{
var source = @"
/// <summary/>
public partial class C { }
public partial class C { }
public partial class D { }
public partial class D { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (6,22): warning CS1591: Missing XML comment for publicly visible type or member 'D'
// public partial class D { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "D").WithArguments("D"));
}
[Fact]
public void WRN_MissingXMLComment_DifferentOptions()
{
var source1 = @"
/// <summary/>
public partial class C { }
public partial class D { }
public partial class E { }
";
var source2 = @"
public partial class C { }
/// <summary/>
public partial class D { }
public partial class E { }
";
var tree1 = Parse(source1, options: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose).WithLanguageVersion(LanguageVersion.Latest));
var tree2 = Parse(source2, options: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None).WithLanguageVersion(LanguageVersion.Latest));
// This scenario does not exist in dev11, but the diagnostics seem reasonable.
CreateCompilation(new[] { tree1, tree2 }).VerifyDiagnostics(
// (5,22): warning CS1591: Missing XML comment for publicly visible type or member 'D'
// public partial class D { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "D").WithArguments("D").WithLocation(5, 22),
// (7,22): warning CS1591: Missing XML comment for publicly visible type or member 'E'
// public partial class E { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E").WithLocation(7, 22));
}
[Fact]
public void WRN_BadXMLRefParamType()
{
var source = @"
/// <see cref=""M(Q)""/>
/// <see cref=""M(C{Q})""/>
/// <see cref=""M(Q[])""/>
/// <see cref=""M(Q*)""/>
class C
{
void M(int x) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (2,16): warning CS1580: Invalid type for parameter 'Q' in XML comment cref attribute: 'M(Q)'
// /// <see cref="M(Q)"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "Q").WithArguments("Q", "M(Q)"),
// (2,16): warning CS1574: XML comment has cref attribute 'M(Q)' that could not be resolved
// /// <see cref="M(Q)"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "M(Q)").WithArguments("M(Q)"),
// (3,16): warning CS1580: Invalid type for parameter 'C{Q}' in XML comment cref attribute: 'M(C{Q})'
// /// <see cref="M(C{Q})"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "C{Q}").WithArguments("C{Q}", "M(C{Q})"),
// (3,16): warning CS1574: XML comment has cref attribute 'M(C{Q})' that could not be resolved
// /// <see cref="M(C{Q})"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "M(C{Q})").WithArguments("M(C{Q})"),
// (4,16): warning CS1580: Invalid type for parameter 'Q[]' in XML comment cref attribute: 'M(Q[])'
// /// <see cref="M(Q[])"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "Q[]").WithArguments("Q[]", "M(Q[])"),
// (4,16): warning CS1574: XML comment has cref attribute 'M(Q[])' that could not be resolved
// /// <see cref="M(Q[])"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "M(Q[])").WithArguments("M(Q[])"),
// (5,16): warning CS1580: Invalid type for parameter 'Q*' in XML comment cref attribute: 'M(Q*)'
// /// <see cref="M(Q*)"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "Q*").WithArguments("Q*", "M(Q*)"),
// (5,16): warning CS1574: XML comment has cref attribute 'M(Q*)' that could not be resolved
// /// <see cref="M(Q*)"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "M(Q*)").WithArguments("M(Q*)"));
}
[Fact]
public void WRN_BadXMLRefReturnType()
{
var source = @"
/// <see cref=""explicit operator Q""/>
/// <see cref=""explicit operator C{Q}""/>
/// <see cref=""explicit operator Q[]""/>
/// <see cref=""explicit operator Q*""/>
class C
{
public static explicit operator int(C c) { return 0; }
}
";
// BREAK: dev11 doesn't report CS1581 for "Q[]" or "Q*" because it only checks for error
// types and it finds an array type and a pointer type, respectively.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (2,16): warning CS1581: Invalid return type in XML comment cref attribute
// /// <see cref="explicit operator Q"/>
Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "Q").WithArguments("Q", "explicit operator Q"),
// (2,16): warning CS1574: XML comment has cref attribute 'explicit operator Q' that could not be resolved
// /// <see cref="explicit operator Q"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator Q").WithArguments("explicit operator Q"),
// (3,16): warning CS1581: Invalid return type in XML comment cref attribute
// /// <see cref="explicit operator C{Q}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "C{Q}").WithArguments("C{Q}", "explicit operator C{Q}"),
// (3,16): warning CS1574: XML comment has cref attribute 'explicit operator C{Q}' that could not be resolved
// /// <see cref="explicit operator C{Q}"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator C{Q}").WithArguments("explicit operator C{Q}"),
// (4,16): warning CS1581: Invalid return type in XML comment cref attribute
// /// <see cref="explicit operator Q[]"/>
Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "Q[]").WithArguments("Q[]", "explicit operator Q[]"),
// (4,16): warning CS1574: XML comment has cref attribute 'explicit operator Q[]' that could not be resolved
// /// <see cref="explicit operator Q[]"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator Q[]").WithArguments("explicit operator Q[]"),
// (5,16): warning CS1581: Invalid return type in XML comment cref attribute
// /// <see cref="explicit operator Q*"/>
Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "Q*").WithArguments("Q*", "explicit operator Q*"),
// (5,16): warning CS1574: XML comment has cref attribute 'explicit operator Q*' that could not be resolved
// /// <see cref="explicit operator Q*"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator Q*").WithArguments("explicit operator Q*"));
}
[Fact]
public void WRN_BadXMLRefTypeVar()
{
// NOTE: there isn't a corresponding case for indexers since they use an impossible member name.
var source = @"
class C<T, op_Explicit, op_Division>
{
/// <see cref=""T""/>
/// <see cref=""explicit operator int""/>
/// <see cref=""operator /""/>
void M() { }
}
";
// BREAK: Dev11 reports WRN_BadXMLRef, instead of WRN_BadXMLRefTypeVar, for the conversion operator.
// This seems like a bug; it binds to the type parameter, but throw it away because it's not a conversion
// method. On its own, this seems reasonable, but it actually performs this filtering *after* accepting
// type symbols for crefs without parameter lists (see Conversion_Type()). Therefore, conversion crefs
// can bind to aggregates, but not type parameters. To be both more consistent and more permissive,
// Roslyn binds to the type parameter and produces a more specific error messages.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (4,20): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter
// /// <see cref="T"/>
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T"),
// (5,20): warning CS1723: XML comment has cref attribute 'explicit operator int' that refers to a type parameter
// /// <see cref="explicit operator int"/>
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "explicit operator int").WithArguments("explicit operator int"),
// (6,20): warning CS1723: XML comment has cref attribute 'operator /' that refers to a type parameter
// /// <see cref="operator /"/>
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "operator /").WithArguments("operator /"));
}
[WorkItem(530970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530970")]
[Fact]
public void DanglingDocComment()
{
var source = @"
/// <summary>
/// See <see cref=""C""/>.
/// </summary>
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
Assert.Equal(SyntaxKind.EndOfFileToken, crefSyntax.Ancestors().First(n => n.IsStructuredTrivia).ParentTrivia.Token.Kind());
model.GetSymbolInfo(crefSyntax);
}
[WorkItem(530969, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530969")]
[Fact]
public void MissingCrefTypeParameter()
{
var source = @"
/// <summary>
/// See <see cref=""C{}""/>.
/// </summary>
class C<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
model.GetSymbolInfo(crefSyntax);
model.GetSymbolInfo(((GenericNameSyntax)crefSyntax.Name).TypeArgumentList.Arguments.Single());
}
[WorkItem(530969, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530969")]
[Fact]
public void InvalidCrefTypeParameter()
{
var source = @"
/// <summary>
/// See <see cref=""C{&}""/>.
/// </summary>
class C<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
model.GetSymbolInfo(crefSyntax);
model.GetSymbolInfo(((GenericNameSyntax)crefSyntax.Name).TypeArgumentList.Arguments.Single());
}
[Fact]
public void GenericTypeArgument()
{
var source = @"
/// <summary>
/// See <see cref=""C{C{T}}""/>.
/// </summary>
class C<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
model.GetSymbolInfo(crefSyntax);
model.GetSymbolInfo(((GenericNameSyntax)crefSyntax.Name).TypeArgumentList.Arguments.Single());
}
[Fact]
public void CrefAttributeNameCaseMismatch()
{
var source = @"
/// <summary>
/// See <see Cref=""C{C{T}}""/>.
/// </summary>
class C<T> { }
";
// Element names don't have to be lowercase, but "cref" does.
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
AssertEx.None(GetCrefSyntaxes(compilation), x => true);
}
[WorkItem(546965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546965")]
[Fact]
public void MultipleCrefs()
{
var source = @"
/// <summary>
/// See <see cref=""int""/>.
/// See <see cref=""C{T}""/>.
/// </summary>
class C<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(compilation);
// Make sure we're not reusing the binder from the first cref (no type parameters)
// for the second cref (has type parameters).
model.GetSymbolInfo(crefSyntaxes.ElementAt(0));
model.GetSymbolInfo(crefSyntaxes.ElementAt(1));
}
[WorkItem(546992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546992")]
[Fact]
public void NestedGenerics()
{
var source = @"
/// <summary>
/// Error <see cref=""A{A{T}}""/>.
/// Error <see cref=""A{T}.B{A{T}}""/>.
/// Error <see cref=""A{T}.B{U}.M{A{T}}""/>.
/// Fine <see cref=""A{T}.B{U}.M{V}(A{A{T}})""/>.
/// Fine <see cref=""A{T}.B{U}.explicit operator A{A{T}}""/>.
/// </summary>
class A<T>
{
class B<U>
{
internal void M<V>(A<A<T>> a) { }
public static explicit operator A<A<T>>(B<U> b) { throw null; }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{A{T}}'
// /// Error <see cref="A{A{T}}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{A{T}}").WithArguments("A{A{T}}"),
// (3,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{A{T}}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "A{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{T}.B{A{T}}'
// /// Error <see cref="A{T}.B{A{T}}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{T}.B{A{T}}").WithArguments("A{T}.B{A{T}}"),
// (4,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{T}.B{A{T}}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "A{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (5,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{T}.B{U}.M{A{T}}'
// /// Error <see cref="A{T}.B{U}.M{A{T}}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{T}.B{U}.M{A{T}}").WithArguments("A{T}.B{U}.M{A{T}}"),
// (5,34): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{T}.B{U}.M{A{T}}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "A{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(compilation);
Assert.Equal(5, crefSyntaxes.Count());
var symbols = crefSyntaxes.Select(cref => model.GetSymbolInfo(cref).Symbol).ToArray();
Assert.Equal("A<A<T>>", symbols[0].ToTestDisplayString());
Assert.Equal("A<T>.B<A<T>>", symbols[1].ToTestDisplayString());
Assert.Equal("void A<T>.B<U>.M<A<T>>(A<A<T>> a)", symbols[2].ToTestDisplayString());
Assert.Equal("void A<T>.B<U>.M<V>(A<A<T>> a)", symbols[3].ToTestDisplayString());
Assert.Equal("A<A<T>> A<T>.B<U>.op_Explicit(A<T>.B<U> b)", symbols[4].ToTestDisplayString());
}
[WorkItem(546992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546992")]
[WorkItem(546993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546993")]
[Fact]
public void NestedPredefinedTypes()
{
var source = @"
/// <summary>
/// Error <see cref=""A{int}""/>.
/// Error <see cref=""A{T}.B{int}""/>.
/// Error <see cref=""A{T}.B{U}.M{int}""/>.
/// Fine <see cref=""A{T}.B{U}.M{V}(A{int})""/>.
/// Fine <see cref=""A{T}.B{U}.explicit operator A{int}""/>.
/// </summary>
class A<T>
{
class B<U>
{
internal void M<V>(A<int> a) { }
public static explicit operator A<int>(B<U> b) { throw null; }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{int}'
// /// Error <see cref="A{int}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{int}").WithArguments("A{int}"),
// (3,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{int}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{T}.B{int}'
// /// Error <see cref="A{T}.B{int}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{T}.B{int}").WithArguments("A{T}.B{int}"),
// (4,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{T}.B{int}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (5,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{T}.B{U}.M{int}'
// /// Error <see cref="A{T}.B{U}.M{int}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{T}.B{U}.M{int}").WithArguments("A{T}.B{U}.M{int}"),
// (5,34): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{T}.B{U}.M{int}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(compilation);
Assert.Equal(5, crefSyntaxes.Count());
var symbols = crefSyntaxes.Select(cref => model.GetSymbolInfo(cref).Symbol).ToArray();
Assert.Equal("A<System.Int32>", symbols[0].ToTestDisplayString());
Assert.Equal("A<T>.B<System.Int32>", symbols[1].ToTestDisplayString());
Assert.Equal("void A<T>.B<U>.M<System.Int32>(A<System.Int32> a)", symbols[2].ToTestDisplayString());
Assert.Equal("void A<T>.B<U>.M<V>(A<System.Int32> a)", symbols[3].ToTestDisplayString());
Assert.Equal("A<System.Int32> A<T>.B<U>.op_Explicit(A<T>.B<U> b)", symbols[4].ToTestDisplayString());
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void NewMethods1()
{
var source = @"
class Base
{
public virtual void M() { }
}
/// <see cref=""Derived.M"" />
class Derived : Base
{
public new void M() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M");
Assert.Equal(overridingMethod, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void NewMethods2()
{
var source = @"
class Base
{
public virtual void M() { }
}
class Middle : Base
{
public new void M() { }
}
/// <see cref=""Derived.M"" />
class Derived : Middle
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (12,16): warning CS1574: XML comment has cref attribute 'Derived.M' that could not be resolved
// /// <see cref="Derived.M" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "Derived.M").WithArguments("M"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Middle").GetMember<MethodSymbol>("M");
Assert.Null(model.GetSymbolInfo(cref).Symbol); // As in dev11.
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[WorkItem(547037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547037")]
[Fact]
public void NewMethods3()
{
var source = @"
class Base
{
public virtual void M() { }
}
/// <see cref=""M"" />
class Derived : Base
{
public new void M() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M");
Assert.Equal(overridingMethod, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void Overrides1()
{
var source = @"
class Base
{
public virtual void M() { }
}
/// <see cref=""Derived.M"" />
class Derived : Base
{
public override void M() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M");
Assert.Equal(overridingMethod, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void Overrides2()
{
var source = @"
class Base
{
public virtual void M() { }
}
class Middle : Base
{
public override void M() { }
}
/// <see cref=""Derived.M"" />
class Derived : Middle
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (12,16): warning CS1574: XML comment has cref attribute 'Derived.M' that could not be resolved
// /// <see cref="Derived.M" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "Derived.M").WithArguments("M"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol); // As in dev11.
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[WorkItem(547037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547037")]
[Fact]
public void Overrides3()
{
var source = @"
class Base
{
public virtual void M() { }
}
/// <see cref=""M"" />
class Derived : Base
{
public override void M() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M");
Assert.Equal(overridingMethod, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void ExtensionMethod()
{
var source = @"
static class Extensions
{
public static void M1(this Derived d) { }
public static void M2(this Derived d) { }
public static void M3(this Derived d) { }
}
class Base
{
public void M2() { }
}
/// <see cref=""Derived.M1"" />
/// <see cref=""Derived.M2"" />
/// <see cref=""Derived.M3"" />
class Derived : Base
{
public void M1() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source, parseOptions: TestOptions.RegularWithDocumentationComments);
compilation.VerifyDiagnostics(
// (15,16): warning CS1574: XML comment has cref attribute 'Derived.M2' that could not be resolved
// /// <see cref="Derived.M2" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "Derived.M2").WithArguments("M2"),
// (16,16): warning CS1574: XML comment has cref attribute 'Derived.M3' that could not be resolved
// /// <see cref="Derived.M3" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "Derived.M3").WithArguments("M3"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
var global = compilation.GlobalNamespace;
var derivedM1 = global.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M1");
var baseM2 = global.GetMember<INamedTypeSymbol>("Base").GetMember<IMethodSymbol>("M2");
Assert.Equal(derivedM1, model.GetSymbolInfo(crefs[0]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[1]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[2]).Symbol);
}
[WorkItem(546990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546990")]
[Fact]
public void ConstructorOfGenericTypeWithinThatType()
{
var source = @"
/// Fine <see cref=""G()""/>.
/// Fine <see cref=""G{T}()""/>.
class G<T> { }
/// Error <see cref=""G()""/>.
/// Fine <see cref=""G{T}()""/>.
class Other { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (6,22): warning CS1574: XML comment has cref attribute 'G()' that could not be resolved
// /// Error <see cref="G()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "G()").WithArguments("G()"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
var constructor = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("G").InstanceConstructors.Single();
Assert.Equal(constructor, model.GetSymbolInfo(crefs[0]).Symbol.OriginalDefinition);
Assert.Equal(constructor, model.GetSymbolInfo(crefs[1]).Symbol.OriginalDefinition);
Assert.Null(model.GetSymbolInfo(crefs[2]).Symbol);
Assert.Equal(constructor, model.GetSymbolInfo(crefs[3]).Symbol.OriginalDefinition);
}
[WorkItem(546990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546990")]
[Fact]
public void ConstructorOfGenericTypeWithinNestedType()
{
var source = @"
class Outer<T>
{
class Inner<U>
{
/// <see cref=""Outer()""/>
void M()
{
}
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (6,24): warning CS1574: XML comment has cref attribute 'Outer()' that could not be resolved
// /// <see cref="Outer()"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Outer()").WithArguments("Outer()"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546990")]
[WorkItem(554077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554077")]
[Fact]
public void QualifiedConstructorOfGenericTypeWithinNestedType()
{
var source = @"
/// <see cref=""Outer{T}.Outer""/>
class Outer<T>
{
/// <see cref=""Outer{T}.Outer""/>
void M()
{
}
/// <see cref=""Outer{T}.Outer""/>
class Inner<U>
{
/// <see cref=""Outer{T}.Outer""/>
void M()
{
}
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'Outer{T}.Outer' that could not be resolved
// /// <see cref="Outer{T}.Outer"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Outer{T}.Outer").WithArguments("Outer"),
// (5,20): warning CS1574: XML comment has cref attribute 'Outer{T}.Outer' that could not be resolved
// /// <see cref="Outer{T}.Outer"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Outer{T}.Outer").WithArguments("Outer"));
var outerCtor = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Outer").InstanceConstructors.Single();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation);
var expectedSymbols = new ISymbol[] { null, null, outerCtor, outerCtor };
var actualSymbols = GetCrefOriginalDefinitions(model, crefs);
AssertEx.Equal(expectedSymbols, actualSymbols);
}
// VB had some problems with these cases between dev10 and dev11.
[WorkItem(546989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546989")]
[Fact]
public void GenericTypeWithoutTypeParameters()
{
var source = @"
class GenericClass<T>
{
internal void NormalSub()
{
}
internal void GenericSub<T2>()
{
}
}
/// <summary>This is other class</summary>
/// <remarks>
/// You may also like <see cref=""GenericClass""/>. <see cref=""GenericClass{T}""/> provides you some interesting methods.
/// <see cref=""GenericClass{T}.NormalSub""/> is normal. <see cref=""GenericClass.NormalSub""/> performs a normal operation.
/// <see cref=""GenericClass{T}.GenericSub""/> is generic. <see cref=""GenericClass.GenericSub""/> performs a generic operation.
/// <see cref=""GenericClass{T}.GenericSub{T}""/> has a generic parameter.
/// <see cref=""GenericClass.GenericSub{T}""/> 's parameters is called <c>T2</c>.
/// </remarks>
class SomeOtherClass
{
}
";
var tree = Parse(source, options: TestOptions.RegularWithDocumentationComments);
var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(new[] { tree });
compilation.VerifyDiagnostics(
// (15,34): warning CS1574: XML comment has cref attribute 'GenericClass' that could not be resolved
// /// You may also like <see cref="GenericClass"/>. <see cref="GenericClass{T}"/> provides you some interesting methods.
Diagnostic(ErrorCode.WRN_BadXMLRef, "GenericClass").WithArguments("GenericClass"),
// (16,67): warning CS1574: XML comment has cref attribute 'GenericClass.NormalSub' that could not be resolved
// /// <see cref="GenericClass{T}.NormalSub"/> is normal. <see cref="GenericClass.NormalSub"/> performs a normal operation.
Diagnostic(ErrorCode.WRN_BadXMLRef, "GenericClass.NormalSub").WithArguments("NormalSub"),
// (17,69): warning CS1574: XML comment has cref attribute 'GenericClass.GenericSub' that could not be resolved
// /// <see cref="GenericClass{T}.GenericSub"/> is generic. <see cref="GenericClass.GenericSub"/> performs a generic operation.
Diagnostic(ErrorCode.WRN_BadXMLRef, "GenericClass.GenericSub").WithArguments("GenericSub"),
// (19,16): warning CS1574: XML comment has cref attribute 'GenericClass.GenericSub{T}' that could not be resolved
// /// <see cref="GenericClass.GenericSub{T}"/> 's parameters is called <c>T2</c>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "GenericClass.GenericSub{T}").WithArguments("GenericSub{T}"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("GenericClass");
var nonGenericMethod = type.GetMember<IMethodSymbol>("NormalSub");
var genericMethod = type.GetMember<IMethodSymbol>("GenericSub");
Assert.Null(model.GetSymbolInfo(crefs[0]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[3]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[5]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[7]).Symbol);
Assert.Equal(type, model.GetSymbolInfo(crefs[1]).Symbol.OriginalDefinition);
Assert.Equal(nonGenericMethod, model.GetSymbolInfo(crefs[2]).Symbol.OriginalDefinition);
Assert.Equal(genericMethod, model.GetSymbolInfo(crefs[4]).Symbol.OriginalDefinition);
Assert.Equal(genericMethod, model.GetSymbolInfo(crefs[6]).Symbol.OriginalDefinition);
}
[WorkItem(546990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546990")]
[Fact]
public void Dynamic()
{
// This can't bind to the type "dynamic" because it is not a type-only context
// (e.g. a method called "dynamic" would be fine).
var source = @"
/// <see cref=""dynamic""/>
class C
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'dynamic' that could not be resolved
// /// <see cref="dynamic"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "dynamic").WithArguments("dynamic"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[Fact]
public void DynamicConstructor()
{
var source = @"
/// <see cref=""dynamic()""/>
class C
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'dynamic()' that could not be resolved
// /// <see cref="dynamic()"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "dynamic()").WithArguments("dynamic()"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[Fact]
public void DynamicInParameters()
{
// BREAK: Dev11 drops candidates with "dynamic" anywhere in their parameter lists.
// As a result, it does not match the first two or last two crefs.
var source = @"
/// <see cref=""M1(dynamic)""/>
/// <see cref=""M1(C{dynamic})""/>
/// <see cref=""M2(object)""/>
/// <see cref=""M2(C{object})""/>
///
/// <see cref=""M1(object)""/>
/// <see cref=""M1(C{object})""/>
/// <see cref=""M2(dynamic)""/>
/// <see cref=""M2(C{dynamic})""/>
class C<T>
{
void M1(dynamic p) { }
void M1(C<dynamic> p) { }
void M2(object p) { }
void M2(C<object> p) { }
}
";
SyntaxTree tree = Parse(source, options: TestOptions.RegularWithDocumentationComments);
var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(new[] { tree });
compilation.VerifyDiagnostics();
var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
//NOTE: deterministic, since GetMembers respects syntax order.
var m1a = type.GetMembers("M1").First();
var m1b = type.GetMembers("M1").Last();
var m2a = type.GetMembers("M2").First();
var m2b = type.GetMembers("M2").Last();
var model = compilation.GetSemanticModel(tree);
var crefs = GetCrefSyntaxes(compilation).ToArray();
Assert.Equal(8, crefs.Length);
Assert.Equal(m1a, model.GetSymbolInfo(crefs[0]).Symbol.OriginalDefinition);
Assert.Equal(m1b, model.GetSymbolInfo(crefs[1]).Symbol.OriginalDefinition);
Assert.Equal(m2a, model.GetSymbolInfo(crefs[2]).Symbol.OriginalDefinition);
Assert.Equal(m2b, model.GetSymbolInfo(crefs[3]).Symbol.OriginalDefinition);
Assert.Equal(m1a, model.GetSymbolInfo(crefs[4]).Symbol.OriginalDefinition);
Assert.Equal(m1b, model.GetSymbolInfo(crefs[5]).Symbol.OriginalDefinition);
Assert.Equal(m2a, model.GetSymbolInfo(crefs[6]).Symbol.OriginalDefinition);
Assert.Equal(m2b, model.GetSymbolInfo(crefs[7]).Symbol.OriginalDefinition);
}
[WorkItem(531152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531152")]
[Fact]
public void MissingArgumentTypes()
{
var source = @"
using System;
/// <see cref=""Console.WriteLine(,,)""/>
class Program
{
}
";
// Note: using is unused because syntactically invalid cref is never bound.
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (4,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'Console.WriteLine(,,)'
// /// <see cref="Console.WriteLine(,,)"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "Console.WriteLine(,,)").WithArguments("Console.WriteLine(,,)"),
// (4,34): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref="Console.WriteLine(,,)"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, ",").WithArguments("Identifier expected", "1001"),
// (4,35): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref="Console.WriteLine(,,)"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, ",").WithArguments("Identifier expected", "1001"),
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531135")]
[Fact]
public void NonOverloadableOperator()
{
var source = @"
/// <see cref=""operator =""/>
class Program
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator ='
// /// <see cref="operator ="/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator").WithArguments("operator ="),
// (2,25): warning CS1658: Overloadable operator expected. See also error CS1037.
// /// <see cref="operator ="/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "=").WithArguments("Overloadable operator expected", "1037"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531135")]
[Fact]
public void InvalidOperator()
{
var source = @"
/// <see cref=""operator q""/>
class Program
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (4,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator q'
// /// <see cref="operator q"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator").WithArguments("operator q"),
// (4,25): warning CS1658: Overloadable operator expected. See also error CS1037.
// /// <see cref="operator q"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "q").WithArguments("Overloadable operator expected", "1037"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(547041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547041")]
[Fact]
public void EmptyVerbatimIdentifier()
{
var source = @"
/// <see cref=""@""/>
class Program
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute '@'
// /// <see cref="@"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "@").WithArguments("@"),
// (2,16): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
// /// <see cref="@"/>
Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, ""));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531161")]
[Fact]
public void AttributeNameHasPrefix()
{
var source = @"
/// <see xmlns:cref=""Invalid""/>
class Program
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
Assert.Equal(0, GetCrefSyntaxes(compilation).Count());
}
[WorkItem(531160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531160")]
[Fact]
public void DuplicateAttribute()
{
var source = @"
/// <see cref=""int"" cref=""long""/>
class Program
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,20): warning CS1570: XML comment has badly formed XML -- 'Duplicate 'cref' attribute'
// /// <see cref="int" cref="long"/>
Diagnostic(ErrorCode.WRN_XMLParseError, @" cref=""long").WithArguments("cref"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(compilation).ToArray();
Assert.Equal(compilation.GetSpecialType(SpecialType.System_Int32), model.GetSymbolInfo(crefSyntaxes[0]).Symbol);
Assert.Equal(compilation.GetSpecialType(SpecialType.System_Int64), model.GetSymbolInfo(crefSyntaxes[1]).Symbol);
}
[WorkItem(531157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531157")]
[Fact]
public void IntPtrConversion()
{
var source = @"
using System;
/// <see cref=""IntPtr.op_Explicit(void*)""/>
class C
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Equal("System.IntPtr System.IntPtr.op_Explicit(System.Void* value)", model.GetSymbolInfo(cref).Symbol.ToTestDisplayString());
}
[WorkItem(531233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531233")]
[Fact]
public void CrefInOtherElement()
{
var source = @"
/// <other cref=""C""/>
class C
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531162")]
[Fact]
public void OuterVersusInheritedFromOuter()
{
var source = @"
class C<T>
{
public void Goo(T x) { }
class D : C<int>
{
/// <see cref=""Goo(T)""/>
void Bar() { }
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("Goo");
Assert.Equal(expectedSymbol, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531344")]
[Fact]
public void ConstraintsInCrefs()
{
var source = @"
/// <see cref=""Outer{Q}.Inner""/>
class Outer<T> where T: System.IFormattable
{
class Inner { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Outer").GetMember<INamedTypeSymbol>("Inner");
Assert.Equal(expectedSymbol, model.GetSymbolInfo(cref).Symbol.OriginalDefinition);
}
[Fact]
public void CrefTypeParameterEquality1()
{
var source = @"
/// <see cref=""C{Q}""/>
class C<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
Func<Symbol> lookupSymbol = () =>
{
var factory = new BinderFactory(compilation, tree, ignoreAccessibility: false);
var binder = factory.GetBinder(cref);
var lookupResult = LookupResult.GetInstance();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
binder.LookupSymbolsSimpleName(
lookupResult,
qualifierOpt: null,
plainName: "Q",
arity: 0,
basesBeingResolved: null,
options: LookupOptions.Default,
diagnose: false,
useSiteDiagnostics: ref useSiteDiagnostics);
Assert.Equal(LookupResultKind.Viable, lookupResult.Kind);
var symbol = lookupResult.Symbols.Single();
lookupResult.Free();
Assert.NotNull(symbol);
Assert.IsType<CrefTypeParameterSymbol>(symbol);
return symbol;
};
var symbol1 = lookupSymbol();
var symbol2 = lookupSymbol();
Assert.Equal(symbol1, symbol2); // Required for correctness.
Assert.NotSame(symbol1, symbol2); // Not required, just documenting.
}
[Fact]
public void CrefTypeParameterEquality2()
{
var source = @"
/// <see cref=""C{T}""/>
class C<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(tree);
var referencedType = (INamedTypeSymbol)model.GetSymbolInfo(cref).Symbol;
Assert.NotNull(referencedType);
var crefTypeParam = referencedType.TypeArguments.Single();
Assert.IsType<CrefTypeParameterSymbol>(crefTypeParam.GetSymbol());
var sourceTypeParam = referencedType.TypeParameters.Single();
Assert.IsType<SourceTypeParameterSymbol>(sourceTypeParam.GetSymbol());
Assert.NotEqual(crefTypeParam, sourceTypeParam);
Assert.NotEqual(sourceTypeParam, crefTypeParam);
}
[WorkItem(531337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531337")]
[Fact]
public void CrefInMethodBody()
{
var source = @"
class C
{
void M()
{
/// <see cref=""C""/>
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (6,9): warning CS1587: XML comment is not placed on a valid language element
// /// <see cref="C"/>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(tree);
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(531337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531337")]
[Fact]
public void CrefOnAccessor()
{
var source = @"
class C
{
int P
{
/// <see cref=""C""/>
get { return 0; }
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (6,9): warning CS1587: XML comment is not placed on a valid language element
// /// <see cref="C"/>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(tree);
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(531391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531391")]
[Fact]
public void IncompleteGenericCrefMissingName()
{
var source = @"
/// <see cref=' {'/>
class C { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute ' {'
// /// <see cref=' {'/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, " {").WithArguments(" {"),
// (2,17): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref=' {'/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "{").WithArguments("Identifier expected", "1001"),
// (2,18): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref=' {'/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "'").WithArguments("Identifier expected", "1001"),
// (2,18): warning CS1658: Syntax error, '>' expected. See also error CS1003.
// /// <see cref=' {'/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "'").WithArguments("Syntax error, '>' expected", "1003"));
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(tree);
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(548900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/548900")]
[Fact]
public void InvalidOperatorCref()
{
var source = @"
/// <see cref=""operator@""/>
class C
{
public static C operator +(C x, C y) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var cref = GetCrefSyntaxes(compilation).Single();
AssertEx.None(cref.DescendantTokens(descendIntoTrivia: true), token => token.ValueText == null);
}
[WorkItem(549210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/549210")]
[Fact]
public void InvalidGenericCref()
{
var source = @"
///<see cref=""X{@
///
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var cref = GetCrefSyntaxes(compilation).Single();
AssertEx.None(cref.DescendantTokens(descendIntoTrivia: true), token => token.ValueText == null);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
foreach (var id in cref.DescendantNodes().OfType<NameSyntax>())
{
Assert.Null(model.GetSymbolInfo(id).Symbol); //Used to assert/throw.
}
}
[WorkItem(549351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/549351")]
[Fact]
public void CrefNotOnMember()
{
var source = @"
/// <see cref=""decimal.operator
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var cref = GetCrefSyntaxes(compilation).Single();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var symbol = model.GetSymbolInfo(cref).Symbol;
Assert.NotNull(symbol);
Assert.Equal(MethodKind.UserDefinedOperator, ((IMethodSymbol)symbol).MethodKind);
Assert.Equal(WellKnownMemberNames.AdditionOperatorName, symbol.Name);
Assert.Equal(SpecialType.System_Decimal, symbol.ContainingType.SpecialType);
}
[WorkItem(551354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551354")]
[Fact]
public void DotIntoTypeParameter1()
{
var source = @"
/// <see cref=""F{T}(T.C)""/>
class C
{
void F<T>(T t) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1580: Invalid type for parameter 'T.C' in XML comment cref attribute: 'F{T}(T.C)'
// /// <see cref="F{T}(T.C)"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "T.C").WithArguments("T.C", "F{T}(T.C)"),
// (2,16): warning CS1574: XML comment has cref attribute 'F{T}(T.C)' that could not be resolved
// /// <see cref="F{T}(T.C)"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "F{T}(T.C)").WithArguments("F{T}(T.C)"));
var cref = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var parameterType = cref.Parameters.Parameters.Single().Type;
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var info = model.GetSymbolInfo(parameterType);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
var parameterTypeContainingType = parameterType.DescendantNodes().OfType<SimpleNameSyntax>().First();
var containingTypeInfo = model.GetSymbolInfo(parameterTypeContainingType);
Assert.IsType<CrefTypeParameterSymbol>(containingTypeInfo.Symbol.GetSymbol());
}
[WorkItem(551354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551354")]
[WorkItem(552759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552759")]
[Fact]
public void DotIntoTypeParameter2()
{
var source = @"
/// <see cref=""C{C}""/>
/// <see cref=""C.D{C}""/>
/// <see cref=""C.D.E{C}""/>
class C
{
class D
{
class E
{
}
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'C{C}' that could not be resolved
// /// <see cref="C{C}"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "C{C}").WithArguments("C{C}"),
// (2,16): warning CS1574: XML comment has cref attribute 'C.D{C}' that could not be resolved
// /// <see cref="C.D{C}"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "C.D{C}").WithArguments("D{C}"),
// (3,16): warning CS1574: XML comment has cref attribute 'C.D.E{C}' that could not be resolved
// /// <see cref="C.D.E{C}"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "C.D.E{C}").WithArguments("E{C}"));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var crefs = GetCrefSyntaxes(compilation).ToArray();
foreach (var cref in crefs)
{
var typeSyntax = cref.DescendantNodes().OfType<SimpleNameSyntax>().First();
var typeSymbol = model.GetSymbolInfo(typeSyntax).Symbol;
if (typeSyntax.Parent.Kind() == SyntaxKind.NameMemberCref)
{
Assert.Null(typeSymbol);
}
else
{
Assert.IsType<CrefTypeParameterSymbol>(typeSymbol.GetSymbol());
}
}
}
[WorkItem(549351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/549351")]
[WorkItem(675600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675600")]
[Fact]
public void OperatorGreaterThanGreaterThanEquals()
{
var source = @"
/// <see cref=""operator }}=""/>
class C { }
";
// Just don't blow up.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator }}='
// /// <see cref="operator }}="/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator").WithArguments("operator }}="),
// (2,24): warning CS1658: Overloadable operator expected. See also error CS1037.
// /// <see cref="operator }}="/>
Diagnostic(ErrorCode.WRN_ErrorOverride, " }}").WithArguments("Overloadable operator expected", "1037"));
}
[WorkItem(554077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554077")]
[Fact]
public void GenericDelegateConstructor()
{
var source = @"
using System;
/// <summary>
/// <see cref=""Action{T}.Action""/>
/// </summary>
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var delegateConstructor = compilation.GlobalNamespace.
GetMember<INamespaceSymbol>("System").GetMembers("Action").OfType<INamedTypeSymbol>().
Single(t => t.Arity == 1).
InstanceConstructors.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var symbol = model.GetSymbolInfo(cref).Symbol;
Assert.NotNull(symbol);
Assert.False(symbol.IsDefinition);
Assert.Equal(delegateConstructor, symbol.OriginalDefinition);
}
[WorkItem(553394, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553394")]
[Fact]
public void InaccessibleViaImports()
{
var source = @"
using System;
/// <see cref=""RuntimeType.Equals""/>
enum E { }
";
// Restore compat: include inaccessible members in cref lookup
var comp = CreateEmptyCompilation(
new[] { Parse(source, options: TestOptions.RegularWithDocumentationComments) },
new[] { MscorlibRef },
TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default));
comp.VerifyDiagnostics();
}
[WorkItem(554086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554086")]
[Fact]
public void InheritedInterfaceMember()
{
var source = @"
using System.Collections;
class GetEnumerator
{
/// <summary>
/// <see cref=""GetEnumerator""/>
/// </summary>
interface I : IEnumerable { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("GetEnumerator");
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void StringConstructor()
{
var source = @"
/// <summary>
/// <see cref=""string(char[])""/>
/// </summary>
enum E { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var expectedSymbol = compilation.GetSpecialType(SpecialType.System_String).
InstanceConstructors.Single(ctor => ctor.Parameters.Length == 1 && ctor.GetParameterType(0).Kind == SymbolKind.ArrayType);
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void InvalidStringConstructor()
{
var source = @"
/// <summary>
/// <see cref=""string(float[])""/>
/// </summary>
enum E { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,16): warning CS1574: XML comment has cref attribute 'string(float[])' that could not be resolved
// /// <see cref="string(float[])"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "string(float[])").WithArguments("string(float[])"));
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var info = model.GetSymbolInfo(cref);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void AliasQualifiedTypeConstructor()
{
var source = @"
/// <summary>
/// <see cref=""global::C()""/>
/// </summary>
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void InvalidAliasQualifiedTypeConstructor()
{
var source = @"
/// <summary>
/// <see cref=""global::D()""/>
/// </summary>
class C { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,16): warning CS1574: XML comment has cref attribute 'global::D()' that could not be resolved
// /// <see cref="global::D()"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "global::D()").WithArguments("global::D()"));
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var info = model.GetSymbolInfo(cref);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void AliasQualifiedGenericTypeConstructor()
{
var source = @"
/// <summary>
/// <see cref=""global::C{Q}(Q)""/>
/// </summary>
class C<T>
{
C(T t) { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var expectedSymbolOriginalDefinition = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.NotEqual(expectedSymbolOriginalDefinition, actualSymbol);
Assert.Equal(expectedSymbolOriginalDefinition, actualSymbol.OriginalDefinition);
}
[WorkItem(553592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553592")]
[Fact]
public void CrefTypeParameterMemberLookup1()
{
var source = @"
/// <see cref=""C{T}""/>
class C<U> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var typeParameterSyntax = crefSyntax.DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("T", typeParameterSyntax.ToString());
var model = compilation.GetSemanticModel(typeParameterSyntax.SyntaxTree);
var typeParameterSymbol = model.GetSymbolInfo(typeParameterSyntax).Symbol;
Assert.IsType<CrefTypeParameterSymbol>(((CSharp.Symbols.PublicModel.Symbol)typeParameterSymbol).UnderlyingSymbol);
var members = model.LookupSymbols(typeParameterSyntax.SpanStart, (ITypeSymbol)typeParameterSymbol);
Assert.Equal(0, members.Length);
}
[WorkItem(553592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553592")]
[Fact]
public void CrefTypeParameterMemberLookup2()
{
var source = @"
/// <see cref=""System.Nullable{T}.GetValueOrDefault()""/>
enum E { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var methodNameSyntax = crefSyntax.DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("GetValueOrDefault", methodNameSyntax.ToString());
var model = compilation.GetSemanticModel(methodNameSyntax.SyntaxTree);
var methodSymbol = model.GetSymbolInfo(methodNameSyntax).Symbol;
Assert.Equal(SymbolKind.Method, methodSymbol.Kind);
var members = model.LookupSymbols(methodNameSyntax.SpanStart, ((IMethodSymbol)methodSymbol).ReturnType);
Assert.Equal(0, members.Length);
}
[WorkItem(598371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598371")]
[Fact]
public void CrefParameterOrReturnTypeLookup1()
{
var source = @"
class X
{
/// <summary>
/// <see cref=""Y.implicit operator Y.Y""/>
/// </summary>
public class Y : X
{
public static implicit operator Y(int x)
{
return null;
}
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var returnTypeSyntax = ((ConversionOperatorMemberCrefSyntax)(((QualifiedCrefSyntax)crefSyntax).Member)).Type;
var expectedReturnTypeSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("X").GetMember<INamedTypeSymbol>("Y");
var actualReturnTypeSymbol = model.GetSymbolInfo(returnTypeSyntax).Symbol;
Assert.Equal(expectedReturnTypeSymbol, actualReturnTypeSymbol);
var expectedCrefSymbol = expectedReturnTypeSymbol.GetMember<IMethodSymbol>(WellKnownMemberNames.ImplicitConversionName);
var actualCrefSymbol = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedCrefSymbol, actualCrefSymbol);
}
[WorkItem(586815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586815")]
[Fact]
public void CrefParameterOrReturnTypeLookup2()
{
var source = @"
class A<T>
{
class B : A<B>
{
/// <summary>
/// <see cref=""Goo(B)""/>
/// </summary>
void Goo(B x) { }
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var classA = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var classB = classA.GetMember<INamedTypeSymbol>("B");
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var parameterTypeSyntax = ((NameMemberCrefSyntax)crefSyntax).Parameters.Parameters[0].Type;
var expectedParameterTypeSymbol = classA.Construct(classB).GetMember<INamedTypeSymbol>("B");
var actualParameterTypeSymbol = model.GetSymbolInfo(parameterTypeSyntax).Symbol;
Assert.Equal(expectedParameterTypeSymbol, actualParameterTypeSymbol);
var expectedCrefSymbol = classB.GetMember<IMethodSymbol>("Goo");
var actualCrefSymbol = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedCrefSymbol, actualCrefSymbol);
}
[WorkItem(743425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743425")]
[Fact]
public void NestedTypeInParameterList()
{
var source = @"
class Outer<T>
{
class Inner { }
/// <see cref='Outer{Q}.M(Inner)'/>
void M() { }
void M(Inner i) { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (6,31): warning CS8018: Within cref attributes, nested types of generic types should be qualified.
// /// <see cref='Outer{Q}.M(Inner)'/>
Diagnostic(ErrorCode.WRN_UnqualifiedNestedTypeInCref, "Inner"),
// (6,20): warning CS1574: XML comment has cref attribute 'Outer{Q}.M(Inner)' that could not be resolved
// /// <see cref='Outer{Q}.M(Inner)'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Outer{Q}.M(Inner)").WithArguments("M(Inner)"));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var outer = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Outer");
var inner = outer.GetMember<INamedTypeSymbol>("Inner");
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var parameterTypeSyntax = crefSyntax.DescendantNodes().OfType<CrefParameterSyntax>().Single().Type;
var parameterTypeSymbol = model.GetSymbolInfo(parameterTypeSyntax).Symbol;
Assert.True(parameterTypeSymbol.IsDefinition);
Assert.Equal(inner, parameterTypeSymbol);
}
[WorkItem(653402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653402")]
[Fact]
public void CrefAliasInfo_TopLevel()
{
var source = @"
using A = System.Int32;
/// <see cref=""A""/>
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
var alias = model.GetAliasInfo(crefSyntax.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().Single());
Assert.Equal(compilation.GetSpecialType(SpecialType.System_Int32), info.Symbol);
Assert.Equal(info.Symbol, alias.Target);
Assert.Equal("A", alias.Name);
}
[WorkItem(653402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653402")]
[Fact]
public void CrefAliasInfo_Parameter()
{
var source = @"
using A = System.Int32;
/// <see cref=""M(A)""/>
class C
{
void M(A a) { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var parameterSyntax = crefSyntax.
DescendantNodes().OfType<CrefParameterSyntax>().Single().
DescendantNodes().OfType<IdentifierNameSyntax>().Single();
var info = model.GetSymbolInfo(parameterSyntax);
var alias = model.GetAliasInfo(parameterSyntax);
Assert.Equal(compilation.GetSpecialType(SpecialType.System_Int32), info.Symbol);
Assert.Equal(info.Symbol, alias.Target);
Assert.Equal("A", alias.Name);
}
[Fact]
[WorkItem(760850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760850")]
public void TestGetSpeculativeSymbolInfoInsideCref()
{
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"
using System;
class P
{
Action<int> b = (int x) => { };
class B
{
/// <see cref=""b""/>
void a()
{
}
}
}
");
var tree = compilation.SyntaxTrees[0];
var cref = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var crefName = cref.Name;
var model = compilation.GetSemanticModel(tree);
var symbolInfo = model.GetSymbolInfo(crefName);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind);
Assert.Equal("System.Action<System.Int32> P.b", symbolInfo.Symbol.ToTestDisplayString());
var speculatedName = SyntaxFactory.ParseName("b");
symbolInfo = model.GetSpeculativeSymbolInfo(crefName.Position, speculatedName, SpeculativeBindingOption.BindAsExpression);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind);
Assert.Equal("System.Action<System.Int32> P.b", symbolInfo.Symbol.ToTestDisplayString());
SemanticModel speculativeModel;
var success = model.TryGetSpeculativeSemanticModel(crefName.Position, speculatedName, out speculativeModel);
Assert.True(success);
Assert.NotNull(speculativeModel);
symbolInfo = speculativeModel.GetSymbolInfo(speculatedName);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind);
Assert.Equal("System.Action<System.Int32> P.b", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact]
[WorkItem(760850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760850")]
public void TestGetSpeculativeSymbolInfoInsideCrefParameterOrReturnType()
{
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(@"
class Base
{
class Inherited { }
}
class Outer
{
class Inner : Base
{
int P { get; set; };
/// <see cref=""explicit operator Return(Param)""/>
void M()
{
}
}
}
");
var tree = compilation.SyntaxTrees.First();
var cref = (ConversionOperatorMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var crefReturnType = cref.Type;
var crefParameterType = cref.Parameters.Parameters.Single().Type;
var crefPosition = cref.SpanStart;
var crefReturnTypePosition = crefReturnType.SpanStart;
var crefParameterTypePosition = crefParameterType.SpanStart;
var nonCrefPosition = tree.GetRoot().DescendantTrivia().Single(t => t.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)).SpanStart;
var accessor = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Outer").GetMember<INamedTypeSymbol>("Inner").GetMember<IPropertySymbol>("P").GetMethod;
var inheritedType = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Base").GetMember<INamedTypeSymbol>("Inherited");
var model = compilation.GetSemanticModel(tree);
// Try a non-type. Should work in a cref, unless it's in a parameter or return type.
// Should not work outside a cref, because the accessor cannot be referenced by name.
var accessorName = SyntaxFactory.ParseName(accessor.Name);
var crefInfo = model.GetSpeculativeSymbolInfo(crefPosition, accessorName, SpeculativeBindingOption.BindAsExpression);
var returnInfo = model.GetSpeculativeSymbolInfo(crefReturnTypePosition, accessorName, SpeculativeBindingOption.BindAsExpression);
var paramInfo = model.GetSpeculativeSymbolInfo(crefParameterTypePosition, accessorName, SpeculativeBindingOption.BindAsExpression);
var nonCrefInfo = model.GetSpeculativeSymbolInfo(nonCrefPosition, accessorName, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(accessor, crefInfo.Symbol);
Assert.Equal(SymbolInfo.None, returnInfo);
Assert.Equal(SymbolInfo.None, paramInfo);
Assert.Equal(accessor, nonCrefInfo.CandidateSymbols.Single());
Assert.Equal(CandidateReason.NotReferencable, nonCrefInfo.CandidateReason);
// Try an inaccessible inherited types. Should work in a cref, but only if it's in a parameter or return type (since it's inherited).
// Should not work outside a cref, because it's inaccessible.
// NOTE: SpeculativeBindingOptions are ignored when the position is inside a cref.
var inheritedTypeName = SyntaxFactory.ParseName(inheritedType.Name);
crefInfo = model.GetSpeculativeSymbolInfo(crefPosition, inheritedTypeName, SpeculativeBindingOption.BindAsExpression);
returnInfo = model.GetSpeculativeSymbolInfo(crefReturnTypePosition, inheritedTypeName, SpeculativeBindingOption.BindAsExpression);
paramInfo = model.GetSpeculativeSymbolInfo(crefParameterTypePosition, inheritedTypeName, SpeculativeBindingOption.BindAsExpression);
nonCrefInfo = model.GetSpeculativeSymbolInfo(nonCrefPosition, inheritedTypeName, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, crefInfo);
Assert.Equal(inheritedType, returnInfo.Symbol);
Assert.Equal(inheritedType, paramInfo.Symbol);
Assert.Equal(inheritedType, nonCrefInfo.CandidateSymbols.Single());
Assert.Equal(CandidateReason.Inaccessible, nonCrefInfo.CandidateReason);
}
[WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")]
[Fact]
public void CrefsOnDelegate()
{
var source = @"
/// <see cref='T'/>
/// <see cref='t'/>
/// <see cref='Invoke'/>
/// <see cref='ToString'/>
delegate void D< T > (T t);
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'T' that could not be resolved
// /// <see cref='T'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "T").WithArguments("T"),
// (3,16): warning CS1574: XML comment has cref attribute 't' that could not be resolved
// /// <see cref='t'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "t").WithArguments("t"),
// (4,16): warning CS1574: XML comment has cref attribute 'Invoke' that could not be resolved
// /// <see cref='Invoke'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Invoke").WithArguments("Invoke"),
// (5,16): warning CS1574: XML comment has cref attribute 'ToString' that could not be resolved
// /// <see cref='ToString'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "ToString").WithArguments("ToString"));
}
[WorkItem(924473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924473")]
[Fact]
public void InterfaceInheritedMembersInSemanticModelLookup()
{
var source = @"
interface IBase
{
int P { get; set; }
}
interface IDerived : IBase
{
}
/// <see cref='IDerived.P'/>
class C
{
}
";
var comp = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
// Not expected to bind, since we don't consider inherited members.
comp.VerifyDiagnostics(
// (11,16): warning CS1574: XML comment has cref attribute 'IDerived.P' that could not be resolved
// /// <see cref='IDerived.P'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "IDerived.P").WithArguments("P").WithLocation(11, 16));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = GetCrefSyntaxes(comp).Single();
// No info, since it doesn't bind.
var info = model.GetSymbolInfo(syntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
// No lookup results.
var derivedInterface = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("IDerived");
Assert.Equal(0, model.LookupSymbols(syntax.SpanStart, derivedInterface).Length);
}
[WorkItem(924473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924473")]
[Fact]
public void InterfaceObjectMembers()
{
var source = @"
interface I
{
}
/// <see cref='I.ToString'/>
class C
{
}
";
var comp = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
// Not expected to bind, since we don't consider inherited members.
comp.VerifyDiagnostics(
// (6,16): warning CS1574: XML comment has cref attribute 'I.ToString' that could not be resolved
// /// <see cref='I.ToString'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "I.ToString").WithArguments("ToString").WithLocation(6, 16));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = GetCrefSyntaxes(comp).Single();
// No info, since it doesn't bind.
var info = model.GetSymbolInfo(syntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
// No lookup results.
var symbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("I");
Assert.Equal(0, model.LookupSymbols(syntax.SpanStart, symbol).Length);
}
#region Dev10 bugs from KevinH
[Fact]
public void Dev10_461967()
{
// Can use anything we want as the name of the type parameter.
var source = @"
/// <see cref=""C{Blah}"" />
/// <see cref=""C{Blah}.Inner"" />
class C<T>
{
class Inner { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
Assert.Equal(2, crefs.Length);
var outer = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var inner = outer.GetMember<INamedTypeSymbol>("Inner");
Assert.Equal(outer, model.GetSymbolInfo(crefs[0]).Symbol.OriginalDefinition);
Assert.Equal(inner, model.GetSymbolInfo(crefs[1]).Symbol.OriginalDefinition);
}
[Fact]
public void Dev10_461974()
{
// Can't omit type parameters.
var source = @"
/// <see cref=""C"" />
/// <see cref=""C{}"" />
class C<T>
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'C{}'
// /// <see cref="C{}" />
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C{}").WithArguments("C{}").WithLocation(3, 16),
// (3,18): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref="C{}" />
Diagnostic(ErrorCode.WRN_ErrorOverride, "}").WithArguments("Identifier expected", "1001").WithLocation(3, 18),
// (2,16): warning CS1574: XML comment has cref attribute 'C' that could not be resolved
// /// <see cref="C" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "C").WithArguments("C").WithLocation(2, 16));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
Assert.Equal(2, crefs.Length);
var actualSymbol0 = model.GetSymbolInfo(crefs[0]).Symbol;
Assert.Null(actualSymbol0);
var actualSymbol1 = model.GetSymbolInfo(crefs[1]).Symbol;
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), actualSymbol1.OriginalDefinition);
Assert.Equal(TypeKind.Error, ((INamedTypeSymbol)actualSymbol1).TypeArguments.Single().TypeKind);
}
[Fact]
public void Dev10_461986()
{
// Can't cref an array type.
var source = @"
/// <see cref=""C[]"" />
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'C[]'
// /// <see cref="C[]" />
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C").WithArguments("C[]"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
// Once the square brackets are skipped, binding works just fine.
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), model.GetSymbolInfo(cref).Symbol);
}
[Fact]
public void Dev10_461988()
{
// Can't cref a nullable type (unless you use the generic type syntax).
var source = @"
/// <see cref=""C?"" />
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'C?'
// /// <see cref="C?" />
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C").WithArguments("C?"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
// Once the question mark is skipped, binding works just fine.
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), model.GetSymbolInfo(cref).Symbol);
}
[Fact]
public void Dev10_461990()
{
// Can't put a smiley face at the end of a cref.
// NOTE: if we had used a type named "C", this would have been accepted as a verbatim cref.
var source = @"
/// <see cref=""Cat:-)"" />
class Cat { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'Cat:-)'
// /// <see cref="Cat:-)" />
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "Cat").WithArguments("Cat:-)"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
// Once the smiley is skipped, binding works just fine.
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Cat"), model.GetSymbolInfo(cref).Symbol);
}
#endregion Dev10 bugs from KevinH
private static IEnumerable<CrefSyntax> GetCrefSyntaxes(Compilation compilation) => GetCrefSyntaxes((CSharpCompilation)compilation);
private static IEnumerable<CrefSyntax> GetCrefSyntaxes(CSharpCompilation compilation)
{
return compilation.SyntaxTrees.SelectMany(tree =>
{
var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>();
return docComments.SelectMany(docComment => docComment.DescendantNodes().OfType<XmlCrefAttributeSyntax>().Select(attr => attr.Cref));
});
}
private static Symbol GetReferencedSymbol(CrefSyntax crefSyntax, CSharpCompilation compilation, params DiagnosticDescription[] expectedDiagnostics)
{
Symbol ambiguityWinner;
var references = GetReferencedSymbols(crefSyntax, compilation, out ambiguityWinner, expectedDiagnostics);
Assert.Null(ambiguityWinner);
Assert.InRange(references.Length, 0, 1); //Otherwise, call GetReferencedSymbols
return references.FirstOrDefault();
}
private static ImmutableArray<Symbol> GetReferencedSymbols(CrefSyntax crefSyntax, CSharpCompilation compilation, out Symbol ambiguityWinner, params DiagnosticDescription[] expectedDiagnostics)
{
var binderFactory = compilation.GetBinderFactory(crefSyntax.SyntaxTree);
var binder = binderFactory.GetBinder(crefSyntax);
DiagnosticBag diagnostics = DiagnosticBag.GetInstance();
var references = binder.BindCref(crefSyntax, out ambiguityWinner, diagnostics);
diagnostics.Verify(expectedDiagnostics);
diagnostics.Free();
return references;
}
private static ISymbol[] GetCrefOriginalDefinitions(SemanticModel model, IEnumerable<CrefSyntax> crefs)
{
return crefs.Select(syntax => model.GetSymbolInfo(syntax).Symbol).Select(symbol => (object)symbol == null ? null : symbol.OriginalDefinition).ToArray();
}
[Fact]
[WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")]
public void LookupOnCrefTypeParameter()
{
var source = @"
class Test
{
T F<T>()
{
}
/// <summary>
/// <see cref=""F{U}()""/>
/// </summary>
void S()
{ }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var name = ((GenericNameSyntax)crefSyntax.Name).TypeArgumentList.Arguments.Single();
Assert.Equal("U", name.ToString());
var typeParameter = (ITypeParameterSymbol)model.GetSymbolInfo(name).Symbol;
Assert.Empty(model.LookupSymbols(name.SpanStart, typeParameter, "GetAwaiter"));
}
[Fact]
[WorkItem(23957, "https://github.com/dotnet/roslyn/issues/23957")]
public void CRef_InParameter()
{
var source = @"
class Test
{
void M(in int x)
{
}
/// <summary>
/// <see cref=""M(in int)""/>
/// </summary>
void S()
{
}
}
";
var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments).VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var parameter = cref.Parameters.Parameters.Single();
Assert.Equal(SyntaxKind.InKeyword, parameter.RefKindKeyword.Kind());
var parameterSymbol = ((IMethodSymbol)model.GetSymbolInfo(cref).Symbol).Parameters.Single();
Assert.Equal(RefKind.In, parameterSymbol.RefKind);
}
[Fact]
public void Cref_TupleType()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""ValueTuple{T,T}""/>.
/// </summary>
class C
{
}
";
var parseOptions = TestOptions.RegularWithDocumentationComments;
var options = TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default);
var compilation = CreateCompilation(source, parseOptions: parseOptions, options: options, targetFramework: TargetFramework.StandardAndCSharp);
var cMember = compilation.GetMember<NamedTypeSymbol>("C");
var xmlDocumentationString = cMember.GetDocumentationCommentXml();
var xml = System.Xml.Linq.XDocument.Parse(xmlDocumentationString);
var cref = xml.Descendants("see").Single().Attribute("cref").Value;
Assert.Equal("T:System.ValueTuple`2", cref);
}
[Fact]
public void Cref_TupleTypeField()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""ValueTuple{Int32,Int32}.Item1""/>.
/// </summary>
class C
{
}
";
var parseOptions = TestOptions.RegularWithDocumentationComments;
var options = TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default);
var compilation = CreateCompilation(source, parseOptions: parseOptions, options: options, targetFramework: TargetFramework.StandardAndCSharp);
var cMember = compilation.GetMember<NamedTypeSymbol>("C");
var xmlDocumentationString = cMember.GetDocumentationCommentXml();
var xml = System.Xml.Linq.XDocument.Parse(xmlDocumentationString);
var cref = xml.Descendants("see").Single().Attribute("cref").Value;
Assert.Equal("F:System.ValueTuple`2.Item1", cref);
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
[WorkItem(50330, "https://github.com/dotnet/roslyn/issues/50330")]
public void OnRecord(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// See also <see cref=""RelativePathBase""/>.
/// See also <see cref=""InvalidCref""/>.
/// </summary>
record CacheContext(string RelativePathBase)" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (6,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(6, 25),
// (6,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(6, 25));
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
[WorkItem(50330, "https://github.com/dotnet/roslyn/issues/50330")]
public void OnRecordStruct(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// See also <see cref=""RelativePathBase""/>.
/// See also <see cref=""InvalidCref""/>.
/// </summary>
record struct CacheContext(string RelativePathBase)" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments.WithLanguageVersion(LanguageVersion.CSharp10), targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (6,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(6, 25),
// (6,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(6, 25));
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
[WorkItem(50330, "https://github.com/dotnet/roslyn/issues/50330")]
public void OnRecord_WithoutPrimaryCtor(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// See also <see cref=""InvalidCref""/>.
/// </summary>
record CacheContext" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (5,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(5, 25));
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
[WorkItem(50330, "https://github.com/dotnet/roslyn/issues/50330")]
public void OnRecordStruct_WithoutPrimaryCtor(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// See also <see cref=""InvalidCref""/>.
/// </summary>
record struct CacheContext" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments.WithLanguageVersion(LanguageVersion.CSharp10), targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (5,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(5, 25));
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
public void Record_TypeAndPropertyWithSameNameInScope(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// </summary>
record CacheContext(string String)" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (1,1): hidden CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1));
var model = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(comp);
var symbol = model.GetSymbolInfo(crefSyntaxes.Single()).Symbol;
Assert.Equal(SymbolKind.Property, symbol.Kind);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
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;
using SymbolExtensions = Microsoft.CodeAnalysis.Test.Utilities.SymbolExtensions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class CrefTests : CSharpTestBase
{
[Fact]
public void EmptyCref()
{
var source = @"
/// <summary>
/// See <see cref=""""/>.
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute ''
// /// See <see cref=""/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @"""").WithArguments(""),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=""/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, @"""").WithArguments("Identifier expected", "1001"));
}
[Fact]
public void WhitespaceCref()
{
var source = @"
/// <summary>
/// See <see cref="" ""/>.
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute ''
// /// See <see cref=""/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @"""").WithArguments(""),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=""/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, @"""").WithArguments("Identifier expected", "1001"));
}
[Fact] //Lexer makes bad token with diagnostic and parser produces additional diagnostic when it consumes the bad token.
public void InvalidCrefCharacter1()
{
var source = @"
/// <summary>
/// See <see cref=""#""/>.
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute '#'
// /// See <see cref="#"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "#").WithArguments("#"),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref="#"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "#").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1658: Unexpected character '#'. See also error CS1056.
// /// See <see cref="#"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '#'", "1056"));
}
[Fact]
public void InvalidCrefCharacter2()
{
var source = @"
/// <summary>
/// See <see cref="" `""/>.
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute ' `'
// /// See <see cref=" `"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, " ").WithArguments(" `"),
// (3,21): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=" `"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "`").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1658: Unexpected character '`'. See also error CS1056.
// /// See <see cref=" `"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '`'", "1056"));
}
[Fact]
public void IncompleteCref1()
{
var source = @"
/// <summary>
/// See <see cref=""
/// </summary>
class Program { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (4,5): warning CS1584: XML comment has syntactically incorrect cref attribute ''
// /// </summary>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "<").WithArguments(""),
// (4,5): warning CS1658: Identifier expected. See also error CS1001.
// /// </summary>
Diagnostic(ErrorCode.WRN_ErrorOverride, "<").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref="
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref="
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"));
}
[Fact]
public void IncompleteCref2()
{
var source = @"
/// <summary>
/// See <see cref='";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute ''
// /// See <see cref='
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "").WithArguments(""),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref='
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref='
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref='
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"),
// (3,20): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.'
// /// See <see cref='
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary"),
// (2,1): warning CS1587: XML comment is not placed on a valid language element
// /// <summary>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
}
[Fact(), WorkItem(546839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546839")]
public void IncompleteCref3()
{
var source = @"
/// <summary>
/// See <see cref='M(T, /// </summary>";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'M(T, ///'
// /// See <see cref='M(T, /// </summary>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "M(T,").WithArguments("M(T, ///"),
// (3,25): warning CS1658: ) expected. See also error CS1026.
// /// See <see cref='M(T, /// </summary>
Diagnostic(ErrorCode.WRN_ErrorOverride, "/").WithArguments(") expected", "1026"),
// (3,28): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref='M(T, /// </summary>
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,28): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref='M(T, /// </summary>
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"),
// (2,1): warning CS1587: XML comment is not placed on a valid language element
// /// <summary>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
}
[Fact(), WorkItem(546919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546919")]
public void IncompleteCref4()
{
var source = @"
/// <summary>
/// See <see cref='M{";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute 'M{'
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "M{").WithArguments("M{"),
// (3,22): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Identifier expected", "1001"),
// (3,22): warning CS1658: Syntax error, '>' expected. See also error CS1003.
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Syntax error, '>' expected", "1003"),
// (3,22): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,22): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"),
// (3,22): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.'
// /// See <see cref='M{
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary"),
// (2,1): warning CS1587: XML comment is not placed on a valid language element
// /// <summary>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
}
[Fact(), WorkItem(547000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547000")]
public void IncompleteCref5()
{
var source = @"
/// <summary>
/// See <see cref='T"; // Make sure the verbatim check doesn't choke on EOF.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,21): warning CS1570: XML comment has badly formed XML -- 'Missing closing quotation mark for string literal.'
// /// See <see cref='T
Diagnostic(ErrorCode.WRN_XMLParseError, ""),
// (3,21): warning CS1570: XML comment has badly formed XML -- 'Expected '>' or '/>' to close tag 'see'.'
// /// See <see cref='T
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("see"),
// (3,21): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'summary'.'
// /// See <see cref='T
Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("summary"),
// (2,1): warning CS1587: XML comment is not placed on a valid language element
// /// <summary>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
}
[WorkItem(547000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547000")]
[Fact]
public void Verbatim()
{
var source = @"
/// <summary>
/// See <see cref=""Gibberish""/>.
/// See <see cref=""T:Gibberish""/>.
/// See <see cref=""T:Gibberish""/>.
/// See <see cref=""T:Gibberish""/>.
/// See <see cref=""T:Gibberish""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments);
compilation.VerifyDiagnostics(
// (3,20): warning CS1574: XML comment has cref attribute 'Gibberish' that could not be resolved
// /// See <see cref="Gibberish"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "Gibberish").WithArguments("Gibberish"));
// Only the first one counts as a cref attribute.
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'Gibberish' that could not be resolved
// /// See <see cref="Gibberish"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "Gibberish").WithArguments("Gibberish"));
Assert.Null(actualSymbol);
}
[WorkItem(547000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547000")]
[Fact]
public void NotQuiteVerbatim()
{
var source = @"
/// <summary>
/// See <see cref=""A""/> - only one character.
/// See <see cref="":""/> - first character is colon.
/// See <see cref=""::""/> - first character is colon.
/// See <see cref=""::Gibberish""/> - first character is colon.
/// </summary>
class Program { }
";
var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments);
compilation.VerifyDiagnostics(
// (4,20): warning CS1584: XML comment has syntactically incorrect cref attribute ':'
// /// See <see cref=":"/> - first character is colon.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, ":").WithArguments(":"),
// (4,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=":"/> - first character is colon.
Diagnostic(ErrorCode.WRN_ErrorOverride, ":").WithArguments("Identifier expected", "1001"),
// (5,20): warning CS1584: XML comment has syntactically incorrect cref attribute '::'
// /// See <see cref="::"/> - first character is colon.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, ":").WithArguments("::"),
// (5,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref="::"/> - first character is colon.
Diagnostic(ErrorCode.WRN_ErrorOverride, "::").WithArguments("Identifier expected", "1001"),
// (6,20): warning CS1584: XML comment has syntactically incorrect cref attribute '::Gibberish'
// /// See <see cref="::Gibberish"/> - first character is colon.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "&").WithArguments("::Gibberish"),
// (6,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref="::Gibberish"/> - first character is colon.
Diagnostic(ErrorCode.WRN_ErrorOverride, "::").WithArguments("Identifier expected", "1001"),
// (3,20): warning CS1574: XML comment has cref attribute 'A' that could not be resolved
// /// See <see cref="A"/> - only one character.
Diagnostic(ErrorCode.WRN_BadXMLRef, "A").WithArguments("A"));
var crefSyntaxes = GetCrefSyntaxes(compilation);
Assert.Equal(4, crefSyntaxes.Count());
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
AssertEx.All(crefSyntaxes, cref => model.GetSymbolInfo(cref).Symbol == null);
}
[Fact]
public void SpecialName1()
{
var source = @"
/// <summary>
/// See <see cref="".ctor""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
// The dot is syntactically incorrect.
compilation.VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute '.ctor'
// /// See <see cref=".ctor"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, ".").WithArguments(".ctor"),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=".ctor"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, ".").WithArguments("Identifier expected", "1001"));
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute '.ctor' that could not be resolved
// /// See <see cref=".ctor"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "").WithArguments(""));
Assert.Null(actualSymbol);
}
[Fact]
public void SpecialName2()
{
var source = @"
/// <summary>
/// See <see cref="".cctor""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
// The dot is syntactically incorrect.
compilation.VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute '.cctor'
// /// See <see cref=".cctor"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, ".").WithArguments(".cctor"),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref=".cctor"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, ".").WithArguments("Identifier expected", "1001"));
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute '.cctor' that could not be resolved
// /// See <see cref=".cctor"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "").WithArguments(""));
Assert.Null(actualSymbol);
}
[Fact]
public void SpecialName3()
{
var source = @"
/// <summary>
/// See <see cref=""~Program""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
// The tilde is syntactically incorrect.
compilation.VerifyDiagnostics(
// (3,20): warning CS1584: XML comment has syntactically incorrect cref attribute '~Program'
// /// See <see cref="~Program"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "~").WithArguments("~Program"),
// (3,20): warning CS1658: Identifier expected. See also error CS1001.
// /// See <see cref="~Program"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "~").WithArguments("Identifier expected", "1001"));
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute '~Program' that could not be resolved
// /// See <see cref="~Program"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "").WithArguments(""));
Assert.Null(actualSymbol);
}
[Fact]
public void TypeScope1()
{
var source = @"
/// <summary>
/// See <see cref=""Program""/>.
/// </summary>
class Program { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeScope2()
{
var source = @"
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class Program
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeScope3()
{
var source = @"
/// <summary>
/// See <see cref=""T""/>.
/// </summary>
class Program<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").TypeParameters.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter
// /// See <see cref="T"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T"));
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeScope4()
{
var source = @"
class Base
{
void M() { }
}
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class Derived : Base { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// As in dev11, we ignore the inherited method symbol.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (8,20): warning CS1574: XML comment has cref attribute 'M' that could not be resolved
// /// See <see cref="M"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "M").WithArguments("M"));
Assert.Null(actualSymbol);
}
[Fact]
public void TypeScope5()
{
var source = @"
class M
{
}
class Base
{
void M() { }
}
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class Derived : Base { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// As in dev11, we ignore the inherited method symbol.
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeScope6()
{
var source = @"
class Outer
{
void M() { }
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class Inner { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Outer").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void MethodScope1()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void MethodScope2()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""T""/>.
/// </summary>
void M<T>() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Type parameters are not in scope.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,24): warning CS1574: XML comment has cref attribute 'T' that could not be resolved
// /// See <see cref="T"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "T").WithArguments("T"));
Assert.Null(actualSymbol);
}
[Fact]
public void MethodScope3()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""p""/>.
/// </summary>
void M(int p) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Type parameters are not in scope.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,24): warning CS1574: XML comment has cref attribute 'p' that could not be resolved
// /// See <see cref="p"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "p").WithArguments("p"));
Assert.Null(actualSymbol);
}
[Fact]
public void IndexerScope1()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""Item""/>.
/// </summary>
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Slightly surprising, but matches the dev11 behavior (you're supposed to use "this").
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,24): warning CS1574: XML comment has cref attribute 'Item' that could not be resolved
// /// See <see cref="Item"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "Item").WithArguments("Item"));
Assert.Null(actualSymbol);
}
[Fact]
public void IndexerScope2()
{
var source = @"
class Program
{
/// <summary>
/// See <see cref=""x""/>.
/// </summary>
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,24): warning CS1574: XML comment has cref attribute 'x' that could not be resolved
// /// See <see cref="x"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x"));
Assert.Null(actualSymbol);
}
[Fact]
public void ObsoleteType()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""A""/>.
/// </summary>
class Test
{
}
[Obsolete(""error"", true)]
class A
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var obsoleteType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A");
obsoleteType.ForceCompleteObsoleteAttribute();
var testType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
testType.ForceCompleteObsoleteAttribute();
var expectedSymbol = obsoleteType;
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void ObsoleteParameterType()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""M(A)""/>.
/// </summary>
class Test
{
void M(A a) { }
}
[Obsolete(""error"", true)]
class A
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var obsoleteType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A");
obsoleteType.ForceCompleteObsoleteAttribute();
var testType = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
testType.ForceCompleteObsoleteAttribute();
var expectedSymbol = testType.GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeNotConstructor1()
{
var source = @"
/// <summary>
/// See <see cref=""A""/>.
/// </summary>
class A
{
}
/// <summary>
/// See <see cref=""B""/>.
/// </summary>
class B
{
B() { }
}
/// <summary>
/// See <see cref=""C""/>.
/// </summary>
static class C
{
static int x = 1;
}
/// <summary>
/// See <see cref=""D""/>.
/// </summary>
static class D
{
static D() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
Assert.Equal(SymbolKind.NamedType, GetReferencedSymbol(crefSyntax, compilation).Kind);
}
}
[Fact]
public void TypeNotConstructor2()
{
var il = @"
.class public auto ansi beforefieldinit B
extends [mscorlib]System.Object
{
.class auto ansi nested public beforefieldinit B
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
";
var csharp = @"
/// <summary>
/// See <see cref=""B""/>.
/// See <see cref=""B.B""/>.
/// </summary>
class C { }
";
var compilation = CreateCompilationWithILAndMscorlib40(csharp, il);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
Assert.Equal(SymbolKind.NamedType, GetReferencedSymbol(crefSyntax, compilation).Kind);
}
}
[Fact]
public void ConstructorNotType1()
{
var source = @"
/// <summary>
/// See <see cref=""A()""/>.
/// See <see cref=""A.A()""/>.
/// See <see cref=""A.A""/>.
/// </summary>
class A
{
}
/// <summary>
/// See <see cref=""B()""/>.
/// See <see cref=""B.B()""/>.
/// See <see cref=""B.B""/>.
/// </summary>
class B
{
B() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
Assert.Equal(SymbolKind.Method, GetReferencedSymbol(crefSyntax, compilation).Kind);
}
}
[Fact]
public void ConstructorNotType2()
{
var il = @"
.class public auto ansi beforefieldinit B
extends [mscorlib]System.Object
{
.class auto ansi nested public beforefieldinit B
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
";
var csharp = @"
/// <summary>
/// See <see cref=""B.B.B""/>.
/// See <see cref=""B()""/>.
/// See <see cref=""B.B()""/>.
/// See <see cref=""B.B.B()""/>.
/// </summary>
class C { }
";
var compilation = CreateCompilationWithILAndMscorlib40(csharp, il);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
Assert.Equal(SymbolKind.Method, GetReferencedSymbol(crefSyntax, compilation).Kind);
}
}
/// <summary>
/// Comment on constructor type.
/// </summary>
[Fact]
public void TypeVersusConstructor1()
{
var source = @"
/// <summary>
/// See <see cref=""A""/>.
/// See <see cref=""A()""/>.
/// See <see cref=""A.A""/>.
/// See <see cref=""A.A()""/>.
/// </summary>
class A
{
}
/// <summary>
/// See <see cref=""B""/>.
/// See <see cref=""B()""/>.
/// See <see cref=""B.B""/>.
/// See <see cref=""B.B()""/>.
///
/// See <see cref=""B{T}""/>.
/// See <see cref=""B{T}()""/>.
/// See <see cref=""B{T}.B""/>.
/// See <see cref=""B{T}.B()""/>.
///
/// See <see cref=""B{T}.B{T}""/>.
/// See <see cref=""B{T}.B{T}()""/>.
/// </summary>
class B<T>
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation);
var typeA = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var ctorA = typeA.InstanceConstructors.Single();
var typeB = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("B");
var ctorB = typeB.InstanceConstructors.Single();
var expected = new ISymbol[]
{
typeA,
ctorA,
ctorA,
ctorA,
null,
ctorB,
null,
null,
typeB,
ctorB,
null,
ctorB,
null,
null,
};
var actual = GetCrefOriginalDefinitions(model, crefs);
AssertEx.Equal(expected, actual);
compilation.VerifyDiagnostics(
// (13,20): warning CS1574: XML comment has cref attribute 'B' that could not be resolved
// /// See <see cref="B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B").WithArguments("B"),
// (15,20): warning CS1574: XML comment has cref attribute 'B.B' that could not be resolved
// /// See <see cref="B.B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B").WithArguments("B"),
// (16,20): warning CS1574: XML comment has cref attribute 'B.B()' that could not be resolved
// /// See <see cref="B.B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B()").WithArguments("B()"),
// (20,20): warning CS1574: XML comment has cref attribute 'B{T}.B' that could not be resolved
// /// See <see cref="B{T}.B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B").WithArguments("B"),
// (23,20): warning CS1574: XML comment has cref attribute 'B{T}.B{T}' that could not be resolved
// /// See <see cref="B{T}.B{T}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}").WithArguments("B{T}"),
// (24,20): warning CS1574: XML comment has cref attribute 'B{T}.B{T}()' that could not be resolved
// /// See <see cref="B{T}.B{T}()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}()").WithArguments("B{T}()"));
}
/// <summary>
/// Comment on unrelated type.
/// </summary>
[WorkItem(554077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554077")]
[Fact]
public void TypeVersusConstructor2()
{
var source = @"
class A
{
}
class B<T>
{
}
/// <summary>
/// See <see cref=""A""/>.
/// See <see cref=""A()""/>.
/// See <see cref=""A.A""/>.
/// See <see cref=""A.A()""/>.
///
/// See <see cref=""B""/>.
/// See <see cref=""B()""/>.
/// See <see cref=""B.B""/>.
/// See <see cref=""B.B()""/>.
///
/// See <see cref=""B{T}""/>.
/// See <see cref=""B{T}()""/>.
/// See <see cref=""B{T}.B""/>.
/// See <see cref=""B{T}.B()""/>.
///
/// See <see cref=""B{T}.B{T}""/>.
/// See <see cref=""B{T}.B{T}()""/>.
/// </summary>
class Other
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation);
var typeA = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var ctorA = typeA.InstanceConstructors.Single();
var typeB = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("B");
var ctorB = typeB.InstanceConstructors.Single();
var expected = new ISymbol[]
{
typeA,
ctorA,
ctorA,
ctorA,
null,
null,
null,
null,
typeB,
ctorB,
ctorB, //NB: different when comment is not applied on/in B.
ctorB,
null,
null,
};
var actual = GetCrefOriginalDefinitions(model, crefs);
AssertEx.Equal(expected, actual);
compilation.VerifyDiagnostics(
// (16,20): warning CS1574: XML comment has cref attribute 'B' that could not be resolved
// /// See <see cref="B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B").WithArguments("B"),
// (17,20): warning CS1574: XML comment has cref attribute 'B()' that could not be resolved
// /// See <see cref="B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B()").WithArguments("B()"),
// (18,20): warning CS1574: XML comment has cref attribute 'B.B' that could not be resolved
// /// See <see cref="B.B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B").WithArguments("B"),
// (19,20): warning CS1574: XML comment has cref attribute 'B.B()' that could not be resolved
// /// See <see cref="B.B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B()").WithArguments("B()"),
// (26,20): warning CS1574: XML comment has cref attribute 'B{T}.B{T}' that could not be resolved
// /// See <see cref="B{T}.B{T}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}").WithArguments("B{T}"),
// (27,20): warning CS1574: XML comment has cref attribute 'B{T}.B{T}()' that could not be resolved
// /// See <see cref="B{T}.B{T}()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}()").WithArguments("B{T}()"));
}
/// <summary>
/// Comment on nested type of constructor type (same behavior as unrelated type).
/// </summary>
[WorkItem(554077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554077")]
[Fact]
public void TypeVersusConstructor3()
{
var source = @"
class A
{
/// <summary>
/// See <see cref=""A""/>.
/// See <see cref=""A()""/>.
/// See <see cref=""A.A""/>.
/// See <see cref=""A.A()""/>.
/// </summary>
class Inner
{
}
}
class B<T>
{
/// <summary>
/// See <see cref=""B""/>.
/// See <see cref=""B()""/>.
/// See <see cref=""B.B""/>.
/// See <see cref=""B.B()""/>.
///
/// See <see cref=""B{T}""/>.
/// See <see cref=""B{T}()""/>.
/// See <see cref=""B{T}.B""/>.
/// See <see cref=""B{T}.B()""/>.
///
/// See <see cref=""B{T}.B{T}""/>.
/// See <see cref=""B{T}.B{T}()""/>.
/// </summary>
class Inner
{
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation);
var typeA = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var ctorA = typeA.InstanceConstructors.Single();
var typeB = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("B");
var ctorB = typeB.InstanceConstructors.Single();
var expected = new ISymbol[]
{
typeA,
ctorA,
ctorA,
ctorA,
null,
null,
null,
null,
typeB,
ctorB,
ctorB, //NB: different when comment is not applied on/in B.
ctorB,
null,
null,
};
var actual = GetCrefOriginalDefinitions(model, crefs);
AssertEx.Equal(expected, actual);
compilation.VerifyDiagnostics(
// (18,24): warning CS1574: XML comment has cref attribute 'B' that could not be resolved
// /// See <see cref="B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B").WithArguments("B"),
// (19,24): warning CS1574: XML comment has cref attribute 'B()' that could not be resolved
// /// See <see cref="B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B()").WithArguments("B()"),
// (20,24): warning CS1574: XML comment has cref attribute 'B.B' that could not be resolved
// /// See <see cref="B.B"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B").WithArguments("B"),
// (21,24): warning CS1574: XML comment has cref attribute 'B.B()' that could not be resolved
// /// See <see cref="B.B()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.B()").WithArguments("B()"),
// (28,24): warning CS1574: XML comment has cref attribute 'B{T}.B{T}' that could not be resolved
// /// See <see cref="B{T}.B{T}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}").WithArguments("B{T}"),
// (29,24): warning CS1574: XML comment has cref attribute 'B{T}.B{T}()' that could not be resolved
// /// See <see cref="B{T}.B{T}()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B{T}.B{T}()").WithArguments("B{T}()"));
}
[Fact]
public void NoConstructor()
{
var source = @"
/// <summary>
/// See <see cref=""C()""/>.
/// See <see cref=""C.C()""/>.
/// See <see cref=""C.C""/>.
/// </summary>
static class C
{
}
/// <summary>
/// See <see cref=""D()""/>.
/// See <see cref=""D.D()""/>.
/// See <see cref=""D.D""/>.
/// </summary>
static class D
{
static D() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
foreach (var crefSyntax in GetCrefSyntaxes(compilation))
{
string text = crefSyntax.ToString();
string arguments = text.Contains("C()") ? "C()" : text.Contains("C") ? "C" : text.Contains("D()") ? "D()" : "D";
Assert.Null(GetReferencedSymbol(crefSyntax, compilation,
Diagnostic(ErrorCode.WRN_BadXMLRef, text).WithArguments(arguments)));
}
}
[Fact]
public void AmbiguousReferenceWithoutParameters()
{
var source = @"
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class C
{
void M() { }
void M(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: Dev11 actually picks the constructor of C - probably an accidental fall-through.
var expectedCandidates = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("M").OfType<MethodSymbol>();
var expectedWinner = expectedCandidates.Single(m => m.ParameterCount == 0);
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'M'. Assuming 'C.M()', but could have also matched other overloads including 'C.M(int)'.
// /// See <see cref="M"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M").WithArguments("M", "C.M()", "C.M(int)"));
Assert.Equal(expectedWinner, actualWinner);
AssertEx.SetEqual(expectedCandidates.AsEnumerable(), actualCandidates.ToArray());
}
[Fact]
public void SourceMetadataConflict()
{
var il = @"
.class public auto ansi beforefieldinit B
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class B
";
var csharp = @"
/// <summary>
/// See <see cref=""B""/>.
/// </summary>
class B { }
";
var ilRef = CompileIL(il);
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(csharp, new[] { ilRef });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// NOTE: As in Dev11, no warning is produced.
var expectedSymbol = compilation.GlobalNamespace.GetMembers("B").OfType<SourceNamedTypeSymbol>().Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Basic()
{
var source = @"
/// <summary>
/// See <see cref=""M(int)""/>.
/// </summary>
class B
{
void M(string x) { }
void M(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.Parameters.Single().Type.SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Ref()
{
var source = @"
/// <summary>
/// See <see cref=""M(ref int)""/>.
/// </summary>
class B
{
void M(ref int x) { }
void M(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => !m.ParameterRefKinds.IsDefault);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Out()
{
var source = @"
/// <summary>
/// See <see cref=""M(out int)""/>.
/// </summary>
class B
{
void M(out int x) { }
void M(ref int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.ParameterRefKinds.Single() == RefKind.Out);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Params()
{
var source = @"
/// <summary>
/// See <see cref=""M(int[])""/>.
/// </summary>
class B
{
void M(int x) { }
void M(params int[] x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.HasParamsParameter());
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Extension()
{
var source = @"
/// <summary>
/// See <see cref=""M(B)""/>.
/// </summary>
class B
{
public static void M(string s) { }
public static void M(this B self) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.IsExtensionMethod);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void OverloadResolution_Arglist1()
{
var source = @"
/// <summary>
/// See <see cref=""M()""/>.
/// </summary>
class B
{
void M() { }
void M(__arglist) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedCandidates = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M");
var expectedWinner = expectedCandidates.OfType<MethodSymbol>().Single(m => !m.IsVararg);
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'M()'. Assuming 'B.M()', but could have also matched other overloads including 'B.M(__arglist)'.
// /// See <see cref="M()"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "M()").WithArguments("M()", "B.M()", "B.M(__arglist)"));
Assert.Equal(expectedWinner, actualWinner);
AssertEx.SetEqual(expectedCandidates, actualCandidates.ToArray());
}
[Fact]
public void OverloadResolution_Arglist2()
{
var source = @"
/// <summary>
/// See <see cref=""M()""/>.
/// </summary>
class B
{
void M(int x) { }
void M(__arglist) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>().
Single(m => m.IsVararg);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void TypeParameters_Simple1()
{
var source = @"
/// <summary>
/// See <see cref=""B{T}""/>.
/// </summary>
class B<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("T", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
}
[Fact]
public void TypeParameters_Simple2()
{
var source = @"
/// <summary>
/// See <see cref=""B{U}""/>.
/// </summary>
class B<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("U", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
}
[Fact]
public void TypeParameters_Simple3()
{
var source = @"
/// <summary>
/// See <see cref=""M{T}""/>.
/// </summary>
class B
{
void M<T>() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("T", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
}
[Fact]
public void TypeParameters_Simple4()
{
var source = @"
/// <summary>
/// See <see cref=""M{U}""/>.
/// </summary>
class B
{
void M<T>() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("U", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
}
[Fact]
public void TypeParameters_Duplicate()
{
var source = @"
/// <summary>
/// See <see cref=""T""/>.
/// </summary>
class B<T, T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").TypeArguments()[0];
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter
// /// See <see cref="T"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T"));
Assert.Equal(expectedSymbol, actualSymbol);
}
// Keep code coverage happy.
[Fact]
public void TypeParameters_Symbols()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A, B}""/>.
/// </summary>
class C<T, U, V>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
var actualTypeParameters = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Cast<CrefTypeParameterSymbol>().ToArray();
AssertEx.None(actualTypeParameters, p => p.IsFromCompilation(compilation));
AssertEx.None(actualTypeParameters, p => p.IsImplicitlyDeclared);
AssertEx.All(actualTypeParameters, p => p.Variance == VarianceKind.None);
AssertEx.All(actualTypeParameters, p => p.Locations.Single() == p.DeclaringSyntaxReferences.Single().GetLocation());
AssertEx.None(actualTypeParameters, p => p.HasValueTypeConstraint);
AssertEx.None(actualTypeParameters, p => p.HasReferenceTypeConstraint);
AssertEx.None(actualTypeParameters, p => p.HasConstructorConstraint);
AssertEx.All(actualTypeParameters, p => p.ContainingSymbol == null);
AssertEx.All(actualTypeParameters, p => p.GetConstraintTypes(null).Length == 0);
AssertEx.All(actualTypeParameters, p => p.GetInterfaces(null).Length == 0);
foreach (var p in actualTypeParameters)
{
Assert.ThrowsAny<Exception>(() => p.GetEffectiveBaseClass(null));
Assert.ThrowsAny<Exception>(() => p.GetDeducedBaseType(null));
}
Assert.Equal(actualTypeParameters[0], actualTypeParameters[1]);
Assert.Equal(actualTypeParameters[0].GetHashCode(), actualTypeParameters[1].GetHashCode());
Assert.NotEqual(actualTypeParameters[0], actualTypeParameters[2]);
#if !DISABLE_GOOD_HASH_TESTS
Assert.NotEqual(actualTypeParameters[0].GetHashCode(), actualTypeParameters[2].GetHashCode());
#endif
}
[Fact]
public void TypeParameters_Signature1()
{
var source = @"
/// <summary>
/// See <see cref=""M{U}(U)""/>.
/// </summary>
class B
{
void M<T>(T t) { }
void M<T>(int t) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMembers("M").OfType<MethodSymbol>()
.Single(method => method.Parameters.Single().Type.TypeKind == TypeKind.TypeParameter);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var typeArgument = actualSymbol.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single();
Assert.NotEqual(expectedOriginalDefinitionSymbol.TypeParameters.Single(), typeArgument);
Assert.Equal("U", typeArgument.Name);
Assert.IsType<CrefTypeParameterSymbol>(typeArgument);
Assert.Equal(0, ((TypeParameterSymbol)typeArgument).Ordinal);
Assert.Equal(typeArgument, actualSymbol.GetParameters().Single().Type);
}
[Fact]
public void TypeParameters_Signature2()
{
var source = @"
/// <summary>
/// See <see cref=""A{S, T}.B{U, V}.M{W, X}(S, U, W, T, V, X)""/>.
/// </summary>
class A<M, N>
{
class B<O, P>
{
internal void M<Q, R>(M m, O o, Q q, N n, P p, R r) { }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("M");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
var expectedOriginalParameterTypes = expectedOriginalDefinitionSymbol.Parameters.Select(p => p.Type).Cast<TypeParameterSymbol>();
var actualParameterTypes = actualSymbol.GetParameters().Select(p => p.Type).Cast<TypeParameterSymbol>();
AssertEx.Equal(expectedOriginalParameterTypes.Select(t => t.Ordinal), actualParameterTypes.Select(t => t.Ordinal));
AssertEx.None(expectedOriginalParameterTypes.Zip(actualParameterTypes, object.Equals), x => x);
}
[Fact]
public void TypeParameters_Duplicates1()
{
var source = @"
/// <summary>
/// See <see cref=""A{T, T}.M(T)""/>.
/// </summary>
class A<T, U>
{
void M(T t) { }
void M(U u) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: In Dev11, this unambiguously matches M(U) (i.e. the last type parameter wins).
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'A{T, T}.M(T)'. Assuming 'A<T, T>.M(T)', but could have also matched other overloads including 'A<T, T>.M(T)'.
// /// See <see cref="A{T, T}.M(T)"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "A{T, T}.M(T)").WithArguments("A{T, T}.M(T)", "A<T, T>.M(T)", "A<T, T>.M(T)"));
Assert.False(actualWinner.IsDefinition);
var actualParameterType = actualWinner.GetParameters().Single().Type;
AssertEx.All(actualWinner.ContainingType.TypeArguments(), typeParam => TypeSymbol.Equals(typeParam, actualParameterType, TypeCompareKind.ConsiderEverything2)); //CONSIDER: Would be different in Dev11.
Assert.Equal(1, ((TypeParameterSymbol)actualParameterType).Ordinal);
Assert.Equal(2, actualCandidates.Length);
Assert.Equal(actualWinner, actualCandidates[0]);
Assert.Equal(actualWinner.ContainingType.GetMembers(actualWinner.Name).Single(member => member != actualWinner), actualCandidates[1]);
}
[Fact]
public void TypeParameters_Duplicates2()
{
var source = @"
/// <summary>
/// See <see cref=""A{T}.B{T}.M(T)""/>.
/// </summary>
class A<T>
{
class B<U>
{
internal void M(T t) { }
internal void M(U u) { }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: In Dev11, this unambiguously matches M(U) (i.e. the last type parameter wins).
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'A{T}.B{T}.M(T)'. Assuming 'A<T>.B<T>.M(T)', but could have also matched other overloads including 'A<T>.B<T>.M(T)'.
// /// See <see cref="A{T}.B{T}.M(T)"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "A{T}.B{T}.M(T)").WithArguments("A{T}.B{T}.M(T)", "A<T>.B<T>.M(T)", "A<T>.B<T>.M(T)"));
Assert.False(actualWinner.IsDefinition);
var actualParameterType = actualWinner.GetParameters().Single().Type;
Assert.Equal(actualParameterType, actualWinner.ContainingType.TypeArguments().Single());
Assert.Equal(actualParameterType, actualWinner.ContainingType.ContainingType.TypeArguments().Single());
Assert.Equal(2, actualCandidates.Length);
Assert.Equal(actualWinner, actualCandidates[0]);
Assert.Equal(actualWinner.ContainingType.GetMembers(actualWinner.Name).Single(member => member != actualWinner), actualCandidates[1]);
}
[Fact]
public void TypeParameters_ExistingTypes1()
{
var source = @"
/// <summary>
/// See <see cref=""A{U}.M(U)""/>.
/// </summary>
class A<T>
{
void M(T t) { } // This one.
void M(U u) { }
}
class U { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMembers("M").OfType<MethodSymbol>().
Single(method => method.Parameters.Single().Type.TypeKind == TypeKind.TypeParameter);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
Assert.Equal(TypeKind.TypeParameter, actualSymbol.GetParameterTypes().Single().Type.TypeKind);
}
[Fact]
public void TypeParameters_ExistingTypes2()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""A{Int32}.M(Int32)""/>.
/// </summary>
class A<T>
{
void M(T t) { } // This one.
void M(int u) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMembers("M").OfType<MethodSymbol>().
Single(method => method.Parameters.Single().Type.TypeKind == TypeKind.TypeParameter);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
Assert.Equal(TypeKind.TypeParameter, actualSymbol.GetParameterTypes().Single().Type.TypeKind);
}
[Fact]
public void GenericTypeConstructor()
{
var source = @"
/// <summary>
/// See <see cref=""A{T}()""/>.
/// </summary>
class A<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedOriginalDefinitionSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedOriginalDefinitionSymbol, actualSymbol.OriginalDefinition);
}
[Fact]
public void Inaccessible1()
{
var source = @"
/// <summary>
/// See <see cref=""C.M""/>.
/// </summary>
class A
{
}
class C
{
private void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.NotNull(actualSymbol);
Assert.Equal(
compilation.GlobalNamespace
.GetMember<NamedTypeSymbol>("C")
.GetMember<SourceOrdinaryMethodSymbol>("M"),
actualSymbol);
Assert.Equal(SymbolKind.Method, actualSymbol.Kind);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var info = model.GetSymbolInfo(crefSyntax);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(info.Symbol, actualSymbol.ISymbol);
}
[Fact]
public void Inaccessible2()
{
var source = @"
/// <summary>
/// See <see cref=""Outer.Inner.M""/>.
/// </summary>
class A
{
}
class Outer
{
private class Inner
{
private void M() { }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace
.GetMember<NamedTypeSymbol>("Outer")
.GetMember<NamedTypeSymbol>("Inner")
.GetMember<SourceOrdinaryMethodSymbol>("M");
// Consider inaccessible symbols, as in Dev11
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")]
[Fact]
public void Inaccessible3()
{
var lib1Source = @"internal class C { }";
var lib2Source = @"public class C { }";
var source = @"
/// <summary>
/// See <see cref=""C""/>.
/// </summary>
class Test { }
";
var lib1Ref = CreateCompilation(lib1Source, assemblyName: "A").EmitToImageReference();
var lib2Ref = CreateCompilation(lib2Source, assemblyName: "B").EmitToImageReference();
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { lib1Ref, lib2Ref });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Break: In dev11 the accessible symbol is preferred. We simply prefer the "first"
Symbol actualSymbol;
var symbols = GetReferencedSymbols(crefSyntax, compilation, out actualSymbol,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'C'. Assuming 'C', but could have also matched other overloads including 'C'.
// /// See <see cref="C"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "C").WithArguments("C", "C", "C").WithLocation(3, 20));
Assert.Equal("A", actualSymbol.ContainingAssembly.Name);
}
[WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")]
[Fact]
public void Inaccessible4()
{
var source = @"
namespace Test
{
using System;
/// <summary>
/// <see cref=""ClientUtils.Goo""/>
/// </summary>
enum E { }
}
class ClientUtils
{
public static void Goo() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// NOTE: Matches dev11 - the accessible symbol is preferred (vs System.ClientUtils).
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("ClientUtils").GetMember<MethodSymbol>("Goo");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")]
[WorkItem(709199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709199")]
[Fact]
public void ProtectedInstanceBaseMember()
{
var source = @"
class Base
{
protected int F;
}
/// Accessible: <see cref=""Base.F""/>
class Derived : Base
{
}
/// Not accessible: <see cref=""Base.F""/>
class Other
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (4,26): warning CS0649: Field 'Base.F' is never assigned to, and will always have its default value 0
// protected static int F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("Base.F", "0"));
var crefSyntax = GetCrefSyntaxes(compilation).First();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base").GetMember<FieldSymbol>("F");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(568006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568006")]
[WorkItem(709199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709199")]
[Fact]
public void ProtectedStaticBaseMember()
{
var source = @"
class Base
{
protected static int F;
}
/// Accessible: <see cref=""Base.F""/>
class Derived : Base
{
}
/// Not accessible: <see cref=""Base.F""/>
class Other
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (4,26): warning CS0649: Field 'Base.F' is never assigned to, and will always have its default value 0
// protected static int F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("Base.F", "0"));
var crefSyntax = GetCrefSyntaxes(compilation).First();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Base").GetMember<FieldSymbol>("F");
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Ambiguous1()
{
var libSource = @"
public class A
{
}
";
var source = @"
/// <summary>
/// See <see cref=""A""/>.
/// </summary>
class B : A
{
}
";
var lib1 = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib1");
var lib2 = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib2");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib1), new CSharpCompilationReference(lib2) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: Dev11 fails with WRN_BadXMLRef.
Symbol actualWinner;
var actualCandidates = GetReferencedSymbols(crefSyntax, compilation, out actualWinner,
// (3,20): warning CS0419: Ambiguous reference in cref attribute: 'A'. Assuming 'A', but could have also matched other overloads including 'A'.
// /// See <see cref="A"/>.
Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "A").WithArguments("A", "A", "A"));
Assert.Contains(actualWinner, actualCandidates);
Assert.Equal(2, actualCandidates.Length);
AssertEx.SetEqual(actualCandidates.Select(sym => sym.ContainingAssembly.Name), "Lib1", "Lib2");
var model = compilation.GetSemanticModel(crefSyntax.SyntaxTree);
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason);
AssertEx.SetEqual(info.CandidateSymbols.Select(sym => sym.ContainingAssembly.Name), "Lib1", "Lib2");
}
[Fact]
public void Ambiguous2()
{
var libSource = @"
public class A
{
public void M() { }
}
";
var source = @"
/// <summary>
/// See <see cref=""A.M""/>.
/// </summary>
class B
{
}
";
var lib1 = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib1");
var lib2 = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib2");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib1), new CSharpCompilationReference(lib2) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Not ideal, but matches dev11.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'A.M' that could not be resolved
// /// See <see cref="A.M"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "A.M").WithArguments("M"));
Assert.Null(actualSymbol);
var model = compilation.GetSemanticModel(crefSyntax.SyntaxTree);
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[ConditionalFact(typeof(NoUsedAssembliesValidation))]
public void Ambiguous3()
{
var lib1Source = @"
public class A
{
}
";
var lib2Source = @"
public class A
{
}
public class B
{
public void M(A a) { }
public void M(int a) { }
}
";
var source = @"
/// <summary>
/// See <see cref=""B.M(A)""/>.
/// </summary>
class C
{
}
";
var lib1 = CreateCompilationWithMscorlib40AndDocumentationComments(lib1Source, assemblyName: "Lib1");
var lib2 = CreateCompilationWithMscorlib40AndDocumentationComments(lib2Source, assemblyName: "Lib2");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib1), new CSharpCompilationReference(lib2) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// Not ideal, but matches dev11.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1580: Invalid type for parameter 'A' in XML comment cref attribute: 'B.M(A)'
// /// See <see cref="B.M(A)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "A").WithArguments("A", "B.M(A)"),
// (3,20): warning CS1574: XML comment has cref attribute 'B.M(A)' that could not be resolved
// /// See <see cref="B.M(A)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "B.M(A)").WithArguments("M(A)"));
Assert.Null(actualSymbol);
var model = compilation.GetSemanticModel(crefSyntax.SyntaxTree);
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[Fact]
public void TypeCref1()
{
var libSource = @"
public class A
{
}
";
var source = @"
extern alias LibAlias;
/// <summary>
/// See <see cref=""LibAlias::A""/>.
/// </summary>
class C
{
}
";
var lib = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("LibAlias")) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.IsType<SourceNamedTypeSymbol>(actualSymbol);
Assert.Equal("A", actualSymbol.Name);
Assert.Equal("Lib", actualSymbol.ContainingAssembly.Name);
}
[Fact]
public void TypeCref2()
{
var libSource = @"
public class A
{
}
";
var source = @"
extern alias LibAlias;
/// <summary>
/// See <see cref=""BadAlias::A""/>.
/// </summary>
class C
{
}
";
var lib = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("LibAlias")) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,20): warning CS1574: XML comment has cref attribute 'BadAlias::A' that could not be resolved
// /// See <see cref="BadAlias::A"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "BadAlias::A").WithArguments("BadAlias::A"));
}
[Fact]
public void TypeCref3()
{
var libSource = @"
public class A
{
}
";
var source = @"
extern alias LibAlias;
/// <summary>
/// See <see cref=""LibAlias::BadType""/>.
/// </summary>
class C
{
}
";
var lib = CreateCompilationWithMscorlib40AndDocumentationComments(libSource, assemblyName: "Lib");
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("LibAlias")) });
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (5,20): warning CS1574: XML comment has cref attribute 'LibAlias::BadType' that could not be resolved
// /// See <see cref="LibAlias::BadType"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "LibAlias::BadType").WithArguments("LibAlias::BadType"));
}
[Fact]
public void TypeCref4()
{
var source = @"
/// <summary>
/// See <see cref=""int""/>.
/// </summary>
class C
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GetSpecialType(SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void IndexerCref_NoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""this""/>.
/// </summary>
class C
{
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void IndexerCref_Parameters()
{
var source = @"
/// <summary>
/// See <see cref=""this[int]""/>.
/// </summary>
class C
{
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void IndexerCref_OverloadResolutionFailure()
{
var source = @"
/// <summary>
/// See <see cref=""this[float]""/>.
/// </summary>
class C
{
int this[int x] { get { return 0; } set { } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'this[float]' that could not be resolved
// /// See <see cref="this[float]"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "this[float]").WithArguments("this[float]"));
Assert.Null(actualSymbol);
}
[Fact]
public void UnaryOperator_NoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""operator !""/>.
/// </summary>
class C
{
public static C operator !(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.LogicalNotOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_OneParameter()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(C)""/>.
/// </summary>
class C
{
public static C operator !(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.LogicalNotOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_OverloadResolutionFailure()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(int)""/>.
/// </summary>
class C
{
public static C operator !(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'operator !(int)' that could not be resolved
// /// See <see cref="operator !(int)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "operator !(int)").WithArguments("operator !(int)"));
Assert.Null(actualSymbol);
}
[Fact]
public void UnaryOperator_OverloadResolution()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(int)""/>.
/// </summary>
class C
{
public static bool operator !(C q)
{
return false;
}
public static bool op_LogicalNot(int x)
{
return false;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.LogicalNotOperatorName).OfType<MethodSymbol>().
Single(method => method.ParameterTypesWithAnnotations.Single().SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_Type()
{
var source = @"
/// <summary>
/// See <see cref=""operator !""/>.
/// </summary>
class op_LogicalNot
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.LogicalNotOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_Constructor0()
{
var source = @"
/// <summary>
/// See <see cref=""operator !()""/>.
/// </summary>
class op_LogicalNot
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.LogicalNotOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_Constructor1()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(int)""/>.
/// </summary>
class op_LogicalNot
{
op_LogicalNot(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.LogicalNotOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void UnaryOperator_Constructor2()
{
var source = @"
/// <summary>
/// See <see cref=""operator !(int, int)""/>.
/// </summary>
class op_LogicalNot
{
op_LogicalNot(int x, int y) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.LogicalNotOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_NoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""operator /""/>.
/// </summary>
class C
{
public static C operator /(C c, int x)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.DivisionOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_TwoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(C, int)""/>.
/// </summary>
class C
{
public static C operator /(C c, int x)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.DivisionOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_OverloadResolutionFailure()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int)""/>.
/// </summary>
class C
{
public static C operator /(C c, int x)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'operator /(int)' that could not be resolved
// /// See <see cref="operator /(int)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "operator /(int)").WithArguments("operator /(int)"));
Assert.Null(actualSymbol);
}
[Fact]
public void BinaryOperator_OverloadResolution()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int, int)""/>.
/// </summary>
class C
{
public static bool operator /(C q, int x)
{
return false;
}
public static bool op_Division(int x, int x)
{
return false;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.DivisionOperatorName).OfType<MethodSymbol>().
Single(method => method.ParameterTypesWithAnnotations.First().SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_Type()
{
var source = @"
/// <summary>
/// See <see cref=""operator /""/>.
/// </summary>
class op_Division
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.DivisionOperatorName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_Constructor0()
{
var source = @"
/// <summary>
/// See <see cref=""operator /()""/>.
/// </summary>
class op_Division
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.DivisionOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_Constructor1()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int)""/>.
/// </summary>
class op_Division
{
op_Division(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
// CONSIDER: This is a syntactic error in dev11.
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'operator /(int)' that could not be resolved
// /// See <see cref="operator /(int)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "operator /(int)").WithArguments("operator /(int)"));
Assert.Null(actualSymbol);
}
[Fact]
public void BinaryOperator_Constructor2()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int, int)""/>.
/// </summary>
class op_Division
{
op_Division(int x, int y) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.DivisionOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void BinaryOperator_Constructor3()
{
var source = @"
/// <summary>
/// See <see cref=""operator /(int, int, int)""/>.
/// </summary>
class op_Division
{
op_Division(int x, int y, int z) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.DivisionOperatorName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_NoParameters()
{
var source = @"
/// <summary>
/// See <see cref=""explicit operator int""/>.
/// </summary>
class C
{
public static explicit operator int(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_OneParameter()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(C)""/>.
/// </summary>
class C
{
public static implicit operator int(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.ImplicitConversionName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_OverloadResolutionFailure()
{
var source = @"
/// <summary>
/// See <see cref=""explicit operator int(int)""/>.
/// </summary>
class C
{
public static explicit operator int(C c)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation,
// (3,20): warning CS1574: XML comment has cref attribute 'explicit operator int(int)' that could not be resolved
// /// See <see cref="explicit operator int(int)"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator int(int)").WithArguments("explicit operator int(int)"));
Assert.Null(actualSymbol);
}
[Fact]
public void Conversion_OverloadResolution()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(int)""/>.
/// </summary>
class C
{
public static implicit operator int(C q)
{
return false;
}
public static int op_Implicit(int x)
{
return false;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.ImplicitConversionName).OfType<MethodSymbol>().
Single(method => method.ParameterTypesWithAnnotations.Single().SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_ReturnType()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(int)""/>.
/// </summary>
class C
{
public static implicit operator int(C q)
{
return false;
}
public static string op_Implicit(int x)
{
return false;
}
// Declaration error, but not important for test.
public static int op_Implicit(int x)
{
return false;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.ImplicitConversionName).OfType<MethodSymbol>().
Single(method => method.ParameterTypesWithAnnotations.Single().SpecialType == SpecialType.System_Int32 && method.ReturnType.SpecialType == SpecialType.System_Int32);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_Type()
{
var source = @"
/// <summary>
/// See <see cref=""explicit operator int""/>.
/// </summary>
class op_Explicit
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.ExplicitConversionName);
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_Constructor0()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int()""/>.
/// </summary>
class op_Implicit
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.ImplicitConversionName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_Constructor1()
{
var source = @"
/// <summary>
/// See <see cref=""explicit operator int(int)""/>.
/// </summary>
class op_Explicit
{
op_Explicit(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.ExplicitConversionName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void Conversion_Constructor2()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(int, int)""/>.
/// </summary>
class op_Implicit
{
op_Implicit(int x, int y) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.ImplicitConversionName).InstanceConstructors.Single();
var actualSymbol = GetReferencedSymbol(crefSyntax, compilation);
Assert.Equal(expectedSymbol, actualSymbol);
}
[Fact]
public void CrefSymbolInfo()
{
var source = @"
/// <summary>
/// See <see cref=""C.M""/>.
/// </summary>
class C
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M");
var actualSymbol = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedSymbol.ISymbol, actualSymbol);
}
[Fact]
public void CrefPartSymbolInfo1()
{
var source = @"
/// <summary>
/// See <see cref=""C.M""/>.
/// </summary>
class C
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (QualifiedCrefSyntax)GetCrefSyntaxes(compilation).Single();
var expectedTypeSymbol = ((Compilation)compilation).GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var expectedMethodSymbol = expectedTypeSymbol.GetMember<IMethodSymbol>("M");
var actualTypeSymbol = model.GetSymbolInfo(crefSyntax.Container).Symbol;
Assert.Equal(expectedTypeSymbol, actualTypeSymbol);
var actualMethodSymbol1 = model.GetSymbolInfo(crefSyntax.Member).Symbol;
Assert.Equal(actualMethodSymbol1, expectedMethodSymbol);
var actualMethodSymbol2 = model.GetSymbolInfo(((NameMemberCrefSyntax)crefSyntax.Member).Name).Symbol;
Assert.Equal(actualMethodSymbol2, expectedMethodSymbol);
}
[Fact]
public void CrefPartSymbolInfo2()
{
var source = @"
/// <summary>
/// See <see cref=""A{J}.B{K}.M{L}(int, J, K, L, A{L}, A{int}.B{K})""/>.
/// </summary>
class A<T>
{
class B<U>
{
internal void M<V>(int s, T t, U u, V v, A<V> w, A<int>.B<U> x) { }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (QualifiedCrefSyntax)GetCrefSyntaxes(compilation).Single();
var nameMemberSyntax = (NameMemberCrefSyntax)crefSyntax.Member;
var containingTypeSyntax = (QualifiedNameSyntax)crefSyntax.Container;
var typeA = ((Compilation)compilation).GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var typeB = typeA.GetMember<INamedTypeSymbol>("B");
var method = typeB.GetMember<IMethodSymbol>("M");
var typeInt = ((Compilation)compilation).GetSpecialType(SpecialType.System_Int32);
// A{J}
ITypeParameterSymbol actualJ;
{
var left = (GenericNameSyntax)containingTypeSyntax.Left;
var actualTypeA = (INamedTypeSymbol)model.GetSymbolInfo(left).Symbol;
Assert.False(actualTypeA.IsDefinition);
actualJ = (ITypeParameterSymbol)actualTypeA.TypeArguments.Single();
Assert.Equal(typeA, actualTypeA.OriginalDefinition);
var actualTypeArgument = model.GetSymbolInfo(left.TypeArgumentList.Arguments.Single()).Symbol;
Assert.Equal(actualJ, actualTypeArgument);
}
// B{K}
ITypeParameterSymbol actualK;
{
var actualTypeB = (INamedTypeSymbol)model.GetSymbolInfo(containingTypeSyntax).Symbol;
Assert.False(actualTypeB.IsDefinition);
actualK = (ITypeParameterSymbol)actualTypeB.TypeArguments.Single();
Assert.Equal(typeB, actualTypeB.OriginalDefinition);
var right = (GenericNameSyntax)containingTypeSyntax.Right;
Assert.Equal(actualTypeB, model.GetSymbolInfo(right).Symbol);
var actualTypeArgument = model.GetSymbolInfo(right.TypeArgumentList.Arguments.Single()).Symbol;
Assert.Equal(actualK, actualTypeArgument);
}
// M{L}
ITypeParameterSymbol actualL;
{
var actualMethod = (IMethodSymbol)model.GetSymbolInfo(crefSyntax).Symbol;
Assert.False(actualMethod.IsDefinition);
actualL = (ITypeParameterSymbol)actualMethod.TypeArguments.Single();
Assert.Equal(method, actualMethod.OriginalDefinition);
Assert.Equal(actualMethod, model.GetSymbolInfo(crefSyntax.Member).Symbol);
Assert.Equal(actualMethod, model.GetSymbolInfo(nameMemberSyntax.Name).Symbol);
var actualParameterTypes = nameMemberSyntax.Parameters.Parameters.Select(syntax => model.GetSymbolInfo(syntax.Type).Symbol).ToArray();
Assert.Equal(6, actualParameterTypes.Length);
Assert.Equal(typeInt, actualParameterTypes[0]);
Assert.Equal(actualJ, actualParameterTypes[1]);
Assert.Equal(actualK, actualParameterTypes[2]);
Assert.Equal(actualL, actualParameterTypes[3]);
Assert.Equal(typeA.Construct(actualL), actualParameterTypes[4]);
Assert.Equal(typeA.Construct(typeInt).GetMember<INamedTypeSymbol>("B").Construct(actualK), actualParameterTypes[5]);
}
}
[Fact]
public void IndexerCrefSymbolInfo()
{
var source = @"
/// <summary>
/// See <see cref=""this[int]""/>.
/// </summary>
class C
{
int this[int x] { get { return 0; } }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (IndexerMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var expectedIndexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Single().ISymbol;
var actualIndexer = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedIndexer, actualIndexer);
var expectedParameterType = compilation.GetSpecialType(SpecialType.System_Int32).ISymbol;
var actualParameterType = model.GetSymbolInfo(crefSyntax.Parameters.Parameters.Single().Type).Symbol;
Assert.Equal(expectedParameterType, actualParameterType);
}
[Fact]
public void OperatorCrefSymbolInfo()
{
var source = @"
/// <summary>
/// See <see cref=""operator +(C)""/>.
/// </summary>
class C
{
public static int operator +(C c) { return 0; }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (OperatorMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var typeC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var expectedOperator = typeC.GetMember<MethodSymbol>(WellKnownMemberNames.UnaryPlusOperatorName).ISymbol;
var actualOperator = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedOperator, actualOperator);
var expectedParameterType = typeC.ISymbol;
var actualParameterType = model.GetSymbolInfo(crefSyntax.Parameters.Parameters.Single().Type).Symbol;
Assert.Equal(expectedParameterType, actualParameterType);
}
[Fact]
public void ConversionOperatorCrefSymbolInfo()
{
var source = @"
/// <summary>
/// See <see cref=""implicit operator int(C)""/>.
/// </summary>
class C
{
public static implicit operator int(C c) { return 0; }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (ConversionOperatorMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var typeC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var expectedOperator = typeC.GetMember<MethodSymbol>(WellKnownMemberNames.ImplicitConversionName).ISymbol;
var actualOperator = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedOperator, actualOperator);
var expectedParameterType = typeC.ISymbol;
var actualParameterType = model.GetSymbolInfo(crefSyntax.Parameters.Parameters.Single().Type).Symbol;
Assert.Equal(expectedParameterType, actualParameterType);
var expectedReturnType = compilation.GetSpecialType(SpecialType.System_Int32).ISymbol;
var actualReturnType = model.GetSymbolInfo(crefSyntax.Type).Symbol;
Assert.Equal(expectedReturnType, actualReturnType);
}
[Fact]
public void CrefSymbolInfo_None()
{
var source = @"
/// <summary>
/// See <see cref=""C.N""/>.
/// </summary>
class C
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[Fact]
public void CrefSymbolInfo_Ambiguous1()
{
var source = @"
/// <summary>
/// See <see cref=""M()""/>.
/// </summary>
class C
{
int M { get; set; }
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason); // Candidates have different kinds.
Assert.Equal(2, info.CandidateSymbols.Length);
}
[Fact]
public void CrefSymbolInfo_Ambiguous2()
{
var source = @"
/// <summary>
/// See <see cref=""M""/>.
/// </summary>
class C
{
void M() { }
void M(int x) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.Ambiguous, info.CandidateReason); // No parameter list.
Assert.Equal(2, info.CandidateSymbols.Length);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution1()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}.M(A)""/>.
/// </summary>
class C<T, U>
{
void M(T t) { }
void M(U u) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.Equal(MethodKind.Ordinary, ((IMethodSymbol)info.CandidateSymbols[0]).MethodKind);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution2()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}.this[A]""/>.
/// </summary>
class C<T, U>
{
int this[T t] { }
int this[U u] { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.True(((IPropertySymbol)info.CandidateSymbols[0]).IsIndexer);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution3()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}.explicit operator C{A, A}(A)""/>.
/// </summary>
class C<T, U>
{
public static explicit operator C<T, U>(T t) { return null; }
public static explicit operator C<T, U>(U u) { return null; }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.Equal(MethodKind.Conversion, ((IMethodSymbol)info.CandidateSymbols[0]).MethodKind);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution4()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}.operator +(C{A, A}, A)""/>.
/// </summary>
class C<T, U>
{
public static object operator +(C<T, U> c, T t) { return null; }
public static object operator +(C<T, U> c, U u) { return null; }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.Equal(MethodKind.UserDefinedOperator, ((IMethodSymbol)info.CandidateSymbols[0]).MethodKind);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution5()
{
var source = @"
/// <summary>
/// See <see cref=""C{A, A}(A)""/>.
/// </summary>
class C<T, U>
{
C(T t) { }
C(U u) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
Assert.Equal(2, info.CandidateSymbols.Length);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)info.CandidateSymbols[0]).MethodKind);
}
[Fact]
public void CrefSymbolInfo_OverloadResolution()
{
var source = @"
/// <summary>
/// See <see cref=""C.N""/>.
/// </summary>
class C
{
void M() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[Fact]
public void CrefLookup()
{
var source = @"
/// <summary>
/// See <see cref=""C{U}""/>.
/// </summary>
class C<T>
{
void M() { }
}
class Outer
{
private class Inner { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var global = compilation.GlobalNamespace;
var typeC = global.GetMember<NamedTypeSymbol>("C");
var methodM = typeC.GetMember<MethodSymbol>("M");
var typeOuter = global.GetMember<NamedTypeSymbol>("Outer");
var typeInner = typeOuter.GetMember<NamedTypeSymbol>("Inner");
int position = source.IndexOf("{U}", StringComparison.Ordinal);
AssertEx.SetEqual(model.LookupSymbols(position).Select(SymbolExtensions.ToTestDisplayString),
// Implicit type parameter
"U",
// From source declarations
"T",
"void C<T>.M()",
"C<T>",
// Boring
"System",
// Inaccessible and boring
"FXAssembly",
"ThisAssembly",
"AssemblyRef",
"SRETW",
"Outer",
"Microsoft");
// Consider inaccessible symbols, as in Dev11
Assert.Equal(typeInner.GetPublicSymbol(), model.LookupSymbols(position, typeOuter.GetPublicSymbol(), typeInner.Name).Single());
}
[Fact]
public void InvalidIdentifier()
{
var source = @"
/// <summary>
/// Error <see cref=""2""/>
/// Error <see cref=""3A""/>
/// Error <see cref=""@4""/>
/// Error <see cref=""@5""/>
/// </summary>
class C
{
}
";
// CONSIDER: The "Unexpected character" warnings are redundant.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute '2'
// /// Error <see cref="2"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "2").WithArguments("2"),
// (3,22): warning CS1658: Identifier expected. See also error CS1001.
// /// Error <see cref="2"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "2").WithArguments("Identifier expected", "1001"),
// (3,22): warning CS1658: Unexpected character '2'. See also error CS1056.
// /// Error <see cref="2"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '2'", "1056"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute '3A'
// /// Error <see cref="3A"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "3").WithArguments("3A"),
// (4,22): warning CS1658: Identifier expected. See also error CS1001.
// /// Error <see cref="3A"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Identifier expected", "1001"),
// (4,22): warning CS1658: Unexpected character '3'. See also error CS1056.
// /// Error <see cref="3A"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '3'", "1056"),
// (5,22): warning CS1584: XML comment has syntactically incorrect cref attribute '@4'
// /// Error <see cref="@4"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "@").WithArguments("@4"),
// (5,22): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
// /// Error <see cref="@4"/>
Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, ""),
// (5,23): warning CS1658: Unexpected character '4'. See also error CS1056.
// /// Error <see cref="@4"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '4'", "1056"),
// (6,22): warning CS1584: XML comment has syntactically incorrect cref attribute '@5'
// /// Error <see cref="@5"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "@").WithArguments("@5"),
// (6,22): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
// /// Error <see cref="@5"/>
Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, ""),
// (6,27): warning CS1658: Unexpected character '5'. See also error CS1056.
// /// Error <see cref="@5"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '5'", "1056"));
}
[Fact]
public void InvalidIdentifier2()
{
var source = @"
/// <summary>
/// Error <see cref=""G<3>""/>
/// Error <see cref=""G{T}.M<3>""/>
/// </summary>
class G<T>
{
void M<U>(G<G<U>>) { }
}
";
// CONSIDER: There's room for improvement here, but it's a corner case.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G<3>'
// /// Error <see cref="G<3>"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G<").WithArguments("G<3>"),
// (3,27): warning CS1658: Identifier expected. See also error CS1001.
// /// Error <see cref="G<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Identifier expected", "1001"),
// (3,27): warning CS1658: Syntax error, '>' expected. See also error CS1003.
// /// Error <see cref="G<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Syntax error, '>' expected", "1003"),
// (3,27): warning CS1658: Unexpected character '3'. See also error CS1056.
// /// Error <see cref="G<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '3'", "1056"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{T}.M<3>'
// /// Error <see cref="G{T}.M<3>"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{T}.M<").WithArguments("G{T}.M<3>"),
// (4,32): warning CS1658: Identifier expected. See also error CS1001.
// /// Error <see cref="G{T}.M<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Identifier expected", "1001"),
// (4,32): warning CS1658: Syntax error, '>' expected. See also error CS1003.
// /// Error <see cref="G{T}.M<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "3").WithArguments("Syntax error, '>' expected", "1003"),
// (4,32): warning CS1658: Unexpected character '3'. See also error CS1056.
// /// Error <see cref="G{T}.M<3>"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '3'", "1056"),
// (8,22): error CS1001: Identifier expected
// void M<U>(G<G<U>>) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")"));
}
[Fact]
public void ERR_TypeParamMustBeIdentifier2()
{
var source = @"
/// <summary>
/// Error <see cref=""G{int}""/>
/// Error <see cref=""G{A.B}""/>
/// Error <see cref=""G{G{T}}}""/>
///
/// Error <see cref=""G{T}.M{int}""/>
/// Error <see cref=""G{T}.M{A.B}""/>
/// Error <see cref=""G{T}.M{G{T}}""/>
///
/// Fine <see cref=""G{T}.M{U}(int)""/>
/// Fine <see cref=""G{T}.M{U}(A.B)""/>
/// Fine <see cref=""G{T}.M{U}(G{G{U}})""/>
/// </summary>
class G<T>
{
void M<U>(int x) { }
void M<U>(A.B b) { }
void M<U>(G<G<U>> g) { }
}
class A
{
public class B
{
}
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{int}'
// /// Error <see cref="G{int}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{int}").WithArguments("G{int}"),
// (3,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{int}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{A.B}'
// /// Error <see cref="G{A.B}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{A.B}").WithArguments("G{A.B}"),
// (4,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{A.B}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "A.B").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (5,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{G{T}}}'
// /// Error <see cref="G{G{T}}}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{G{T}}").WithArguments("G{G{T}}}"),
// (5,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{G{T}}}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "G{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (7,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{T}.M{int}'
// /// Error <see cref="G{T}.M{int}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{T}.M{int}").WithArguments("G{T}.M{int}"),
// (7,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{T}.M{int}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (8,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{T}.M{A.B}'
// /// Error <see cref="G{T}.M{A.B}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{T}.M{A.B}").WithArguments("G{T}.M{A.B}"),
// (8,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{T}.M{A.B}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "A.B").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (9,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'G{T}.M{G{T}}'
// /// Error <see cref="G{T}.M{G{T}}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "G{T}.M{G{T}}").WithArguments("G{T}.M{G{T}}"),
// (9,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="G{T}.M{G{T}}"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "G{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"));
}
[Fact]
public void WRN_DuplicateParamTag()
{
var source = @"
class C
{
/// <param name=""x""/>
/// <param name=""x""/> -- warning
void M(int x) { }
/// <param name=""value""/>
/// <param name=""value""/> -- fine, as in dev11
int P { get; set; }
/// <param name=""x""/>
/// <param name=""y""/>
/// <param name=""value""/>
/// <param name=""x""/> -- warning
/// <param name=""y""/> -- warning
/// <param name=""value""/> -- fine, as in dev11
int this[int x, int y] { get { return 0; } set { } }
}
partial class P
{
/// <param name=""x""/>
partial void M(int x);
}
partial class P
{
/// <param name=""x""/> -- fine, other is dropped
partial void M(int x) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (5,16): warning CS1571: XML comment has a duplicate param tag for 'x'
// /// <param name="x"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""x""").WithArguments("x"),
// (15,16): warning CS1571: XML comment has a duplicate param tag for 'x'
// /// <param name="x"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""x""").WithArguments("x"),
// (16,16): warning CS1571: XML comment has a duplicate param tag for 'y'
// /// <param name="y"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""y""").WithArguments("y"));
}
[Fact]
public void WRN_UnmatchedParamTag()
{
var source = @"
class C
{
/// <param name=""q""/>
/// <param name=""value""/>
void M(int x) { }
/// <param name=""x""/>
int P { get; set; }
/// <param name=""q""/>
int this[int x, int y] { get { return 0; } set { } }
/// <param name=""q""/>
/// <param name=""value""/>
event System.Action E;
}
partial class P
{
/// <param name=""x""/>
partial void M(int y);
}
partial class P
{
/// <param name=""y""/>
partial void M(int x) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (28,18): warning CS8826: Partial method declarations 'void P.M(int y)' and 'void P.M(int x)' have signature differences.
// partial void M(int x) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void P.M(int y)", "void P.M(int x)").WithLocation(28, 18),
// (16,25): warning CS0067: The event 'C.E' is never used
// event System.Action E;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(16, 25),
// (4,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q").WithLocation(4, 22),
// (5,22): warning CS1572: XML comment has a param tag for 'value', but there is no parameter by that name
// /// <param name="value"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "value").WithArguments("value").WithLocation(5, 22),
// (6,16): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.M(int)' (but other parameters do)
// void M(int x) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.M(int)").WithLocation(6, 16),
// (8,22): warning CS1572: XML comment has a param tag for 'x', but there is no parameter by that name
// /// <param name="x"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "x").WithArguments("x").WithLocation(8, 22),
// (11,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q").WithLocation(11, 22),
// (12,18): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.this[int, int]' (but other parameters do)
// int this[int x, int y] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.this[int, int]").WithLocation(12, 18),
// (12,25): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'C.this[int, int]' (but other parameters do)
// int this[int x, int y] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "C.this[int, int]").WithLocation(12, 25),
// (14,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q").WithLocation(14, 22),
// (15,22): warning CS1572: XML comment has a param tag for 'value', but there is no parameter by that name
// /// <param name="value"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "value").WithArguments("value").WithLocation(15, 22),
// (27,22): warning CS1572: XML comment has a param tag for 'y', but there is no parameter by that name
// /// <param name="y"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "y").WithArguments("y").WithLocation(27, 22),
// (28,24): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'P.M(int)' (but other parameters do)
// partial void M(int x) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "P.M(int)").WithLocation(28, 24),
// (21,22): warning CS1572: XML comment has a param tag for 'x', but there is no parameter by that name
// /// <param name="x"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "x").WithArguments("x").WithLocation(21, 22),
// (22,24): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'P.M(int)' (but other parameters do)
// partial void M(int y);
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "P.M(int)").WithLocation(22, 24));
}
[Fact]
public void WRN_MissingParamTag()
{
var source = @"
class C
{
/// <param name=""x""/>
void M(int x, int y) { }
/// <param name=""x""/>
int this[int x, int y] { get { return 0; } set { } }
/// <param name=""value""/>
int this[int x] { get { return 0; } set { } }
}
partial class P
{
/// <param name=""q""/>
partial void M(int q, int r);
}
partial class P
{
/// <param name=""x""/>
partial void M(int x, int y) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (23,18): warning CS8826: Partial method declarations 'void P.M(int q, int r)' and 'void P.M(int x, int y)' have signature differences.
// partial void M(int x, int y) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void P.M(int q, int r)", "void P.M(int x, int y)").WithLocation(23, 18),
// (5,23): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'C.M(int, int)' (but other parameters do)
// void M(int x, int y) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "C.M(int, int)").WithLocation(5, 23),
// (8,25): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'C.this[int, int]' (but other parameters do)
// int this[int x, int y] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "C.this[int, int]").WithLocation(8, 25),
// (11,18): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.this[int]' (but other parameters do)
// int this[int x] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.this[int]").WithLocation(11, 18),
// (23,31): warning CS1573: Parameter 'y' has no matching param tag in the XML comment for 'P.M(int, int)' (but other parameters do)
// partial void M(int x, int y) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "y").WithArguments("y", "P.M(int, int)").WithLocation(23, 31),
// (17,31): warning CS1573: Parameter 'r' has no matching param tag in the XML comment for 'P.M(int, int)' (but other parameters do)
// partial void M(int q, int r);
Diagnostic(ErrorCode.WRN_MissingParamTag, "r").WithArguments("r", "P.M(int, int)").WithLocation(17, 31));
}
[Fact]
public void WRN_DuplicateTypeParamTag()
{
var source = @"
/// <typeparam name=""T""/>
/// <typeparam name=""T""/> -- warning
class C<T>
{
/// <typeparam name=""U""/>
/// <typeparam name=""U""/> -- warning
void M<U>() { }
}
/// <typeparam name=""T""/>
partial class P<T>
{
/// <typeparam name=""U""/>
partial void M1<U>();
/// <typeparam name=""U""/>
/// <typeparam name=""U""/> -- warning
partial void M2<U>();
}
/// <typeparam name=""T""/> -- warning
partial class P<T>
{
/// <typeparam name=""U""/> -- fine, other is dropped
partial void M1<U>() { }
/// <typeparam name=""U""/>
/// <typeparam name=""U""/> -- warning
partial void M2<U>() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,16): warning CS1710: XML comment has a duplicate typeparam tag for 'T'
// /// <typeparam name="T"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""T""").WithArguments("T"),
// (7,20): warning CS1710: XML comment has a duplicate typeparam tag for 'U'
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""U""").WithArguments("U"),
// (22,16): warning CS1710: XML comment has a duplicate typeparam tag for 'T'
// /// <typeparam name="T"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""T""").WithArguments("T"),
// (29,20): warning CS1710: XML comment has a duplicate typeparam tag for 'U'
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""U""").WithArguments("U"),
// (18,20): warning CS1710: XML comment has a duplicate typeparam tag for 'U'
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""U""").WithArguments("U"));
}
[Fact]
public void WRN_UnmatchedParamRefTag()
{
var source = @"
class C
{
/// <paramref name=""q""/>
/// <paramref name=""value""/>
void M(int x) { }
/// <paramref name=""x""/>
int P { get; set; }
/// <paramref name=""q""/>
int this[int x, int y] { get { return 0; } set { } }
/// <paramref name=""q""/>
/// <paramref name=""value""/>
event System.Action E;
}
partial class P
{
/// <paramref name=""x""/>
partial void M(int y);
}
partial class P
{
/// <paramref name=""y""/>
partial void M(int x) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (28,18): warning CS8826: Partial method declarations 'void P.M(int y)' and 'void P.M(int x)' have signature differences.
// partial void M(int x) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void P.M(int y)", "void P.M(int x)").WithLocation(28, 18),
// (16,25): warning CS0067: The event 'C.E' is never used
// event System.Action E;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(16, 25),
// (4,25): warning CS1734: XML comment on 'C.M(int)' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.M(int)").WithLocation(4, 25),
// (5,25): warning CS1734: XML comment on 'C.M(int)' has a paramref tag for 'value', but there is no parameter by that name
// /// <paramref name="value"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "value").WithArguments("value", "C.M(int)").WithLocation(5, 25),
// (8,25): warning CS1734: XML comment on 'C.P' has a paramref tag for 'x', but there is no parameter by that name
// /// <paramref name="x"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "x").WithArguments("x", "C.P").WithLocation(8, 25),
// (11,25): warning CS1734: XML comment on 'C.this[int, int]' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.this[int, int]").WithLocation(11, 25),
// (14,25): warning CS1734: XML comment on 'C.E' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.E").WithLocation(14, 25),
// (15,25): warning CS1734: XML comment on 'C.E' has a paramref tag for 'value', but there is no parameter by that name
// /// <paramref name="value"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "value").WithArguments("value", "C.E").WithLocation(15, 25),
// (27,25): warning CS1734: XML comment on 'P.M(int)' has a paramref tag for 'y', but there is no parameter by that name
// /// <paramref name="y"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "y").WithArguments("y", "P.M(int)").WithLocation(27, 25),
// (21,25): warning CS1734: XML comment on 'P.M(int)' has a paramref tag for 'x', but there is no parameter by that name
// /// <paramref name="x"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "x").WithArguments("x", "P.M(int)").WithLocation(21, 25));
}
[Fact]
public void DuplicateParameterName()
{
var source = @"
class C
{
/// <param name=""x""/>
/// <paramref name=""x""/>
/// <param name=""q""/>
/// <paramref name=""q""/>
void M(int x, int x) { }
/// <param name=""x""/>
/// <paramref name=""x""/>
/// <param name=""q""/>
/// <paramref name=""q""/>
int this[int x, int x] { get { return 0; } set { } }
/// <param name=""q""/>
void M(double x, double x) { }
/// <param name=""q""/>
double this[double x, double x] { get { return 0; } set { } }
}
";
// These diagnostics don't exactly match dev11, but they seem reasonable and the main point
// of the test is to confirm that we don't crash.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (17,29): error CS0100: The parameter name 'x' is a duplicate
// void M(double x, double x) { }
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x"),
// (8,23): error CS0100: The parameter name 'x' is a duplicate
// void M(int x, int x) { }
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x"), // NOTE: double-reported in dev11
// (14,25): error CS0100: The parameter name 'x' is a duplicate
// int this[int x, int x] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x"),
// (20,34): error CS0100: The parameter name 'x' is a duplicate
// double this[double x, double x] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x"), // NOTE: double-reported in dev11
// Dev11 doesn't report these, but they seem reasonable (even desirable).
// (6,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"),
// (7,25): warning CS1734: XML comment on 'C.M(int, int)' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.M(int, int)"),
// These match dev11.
// (12,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"),
// (13,25): warning CS1734: XML comment on 'C.this[int, int]' has a paramref tag for 'q', but there is no parameter by that name
// /// <paramref name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "q").WithArguments("q", "C.this[int, int]"),
// Dev11 doesn't report these, but they seem reasonable (even desirable).
// (16,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"),
// (17,19): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.M(double, double)' (but other parameters do)
// void M(double x, double x) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.M(double, double)"),
// (17,29): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.M(double, double)' (but other parameters do)
// void M(double x, double x) { }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.M(double, double)"),
// These match dev11.
// (19,22): warning CS1572: XML comment has a param tag for 'q', but there is no parameter by that name
// /// <param name="q"/>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "q").WithArguments("q"),
// (20,24): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.this[double, double]' (but other parameters do)
// double this[double x, double x] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.this[double, double]"),
// (20,34): warning CS1573: Parameter 'x' has no matching param tag in the XML comment for 'C.this[double, double]' (but other parameters do)
// double this[double x, double x] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingParamTag, "x").WithArguments("x", "C.this[double, double]"));
}
[Fact]
public void DuplicateTypeParameterName()
{
var source = @"
/// <typeparam name=""T""/>
/// <typeparamref name=""T""/>
/// <typeparam name=""Q""/>
/// <typeparamref name=""Q""/>
class C<T, T>
{
/// <typeparam name=""U""/>
/// <typeparamref name=""U""/>
/// <typeparam name=""Q""/>
/// <typeparamref name=""Q""/>
void M<U, U>() { }
}
/// <typeparam name=""Q""/>
class D<T, T>
{
/// <typeparam name=""Q""/>
void M<U, U>() { }
}
";
// Dev11 stops after the CS0692s on the types.
// We just want to confirm that the errors are sensible and we don't crash.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (6,12): error CS0692: Duplicate type parameter 'T'
// class C<T, T>
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T"),
// (16,12): error CS0692: Duplicate type parameter 'T'
// class D<T, T>
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T"),
// (12,15): error CS0692: Duplicate type parameter 'U'
// void M<U, U>() { }
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U"),
// (19,15): error CS0692: Duplicate type parameter 'U'
// void M<U, U>() { }
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U"),
// (4,22): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (5,25): warning CS1735: XML comment on 'C<T, T>' has a typeparamref tag for 'Q', but there is no type parameter by that name
// /// <typeparamref name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "Q").WithArguments("Q", "C<T, T>"),
// (10,26): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (11,29): warning CS1735: XML comment on 'C<T, T>.M<U, U>()' has a typeparamref tag for 'Q', but there is no type parameter by that name
// /// <typeparamref name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "Q").WithArguments("Q", "C<T, T>.M<U, U>()"),
// (15,22): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (16,9): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'D<T, T>' (but other type parameters do)
// class D<T, T>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "D<T, T>"),
// (16,12): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'D<T, T>' (but other type parameters do)
// class D<T, T>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "D<T, T>"),
// (18,26): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (19,12): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'D<T, T>.M<U, U>()' (but other type parameters do)
// void M<U, U>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "D<T, T>.M<U, U>()"),
// (19,15): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'D<T, T>.M<U, U>()' (but other type parameters do)
// void M<U, U>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "D<T, T>.M<U, U>()"));
}
[Fact]
public void WRN_UnmatchedTypeParamTag()
{
var source = @"
/// <typeparam name=""T""/> -- warning
class C
{
/// <typeparam name=""T""/> -- warning
void M() { }
}
/// <typeparam name=""T""/>
/// <typeparam name=""U""/> -- warning
class C<T>
{
/// <typeparam name=""U""/>
/// <typeparam name=""V""/> -- warning
void M<U>() { }
}
/// <typeparam name=""U""/> -- warning
partial class P<T>
{
/// <typeparam name=""V""/> -- warning
partial void M1<U>();
}
/// <typeparam name=""V""/> -- warning
partial class P<T>
{
/// <typeparam name=""U""/> -- warning
partial void M1<V>() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (29,18): warning CS8826: Partial method declarations 'void P<T>.M1<U>()' and 'void P<T>.M1<V>()' have signature differences.
// partial void M1<V>() { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M1").WithArguments("void P<T>.M1<U>()", "void P<T>.M1<V>()").WithLocation(29, 18),
// (2,22): warning CS1711: XML comment has a typeparam tag for 'T', but there is no type parameter by that name
// /// <typeparam name="T"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "T").WithArguments("T"),
// (5,26): warning CS1711: XML comment has a typeparam tag for 'T', but there is no type parameter by that name
// /// <typeparam name="T"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "T").WithArguments("T"),
// (10,22): warning CS1711: XML comment has a typeparam tag for 'U', but there is no type parameter by that name
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "U").WithArguments("U"),
// (14,26): warning CS1711: XML comment has a typeparam tag for 'V', but there is no type parameter by that name
// /// <typeparam name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "V").WithArguments("V"),
// (18,22): warning CS1711: XML comment has a typeparam tag for 'U', but there is no type parameter by that name
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "U").WithArguments("U"),
// (25,22): warning CS1711: XML comment has a typeparam tag for 'V', but there is no type parameter by that name
// /// <typeparam name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "V").WithArguments("V"),
// (28,26): warning CS1711: XML comment has a typeparam tag for 'U', but there is no type parameter by that name
// /// <typeparam name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "U").WithArguments("U"),
// (21,26): warning CS1711: XML comment has a typeparam tag for 'V', but there is no type parameter by that name
// /// <typeparam name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "V").WithArguments("V"),
// (29,21): warning CS1712: Type parameter 'V' has no matching typeparam tag in the XML comment on 'P<T>.M1<V>()' (but other type parameters do)
// partial void M1<V>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "V").WithArguments("V", "P<T>.M1<V>()"),
// (19,17): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'P<T>' (but other type parameters do)
// partial class P<T>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "P<T>"),
// (22,21): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'P<T>.M1<U>()' (but other type parameters do)
// partial void M1<U>();
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "P<T>.M1<U>()"));
}
[Fact]
public void WRN_MissingTypeParamTag()
{
var source = @"
/// <typeparam name=""T""/>
class C<T, U>
{
/// <typeparam name=""V""/>
void M<V, W, X>() { }
}
/// <typeparam name=""Q""/>
class C<T>
{
/// <typeparam name=""Q""/>
void M<U>() { }
}
/// <typeparam name=""T""/>
partial class P<T, U>
{
/// <typeparam name=""V""/>
partial void M1<V, W>();
}
/// <typeparam name=""U""/>
partial class P<T, U>
{
/// <typeparam name=""W""/>
partial void M1<V, W>() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (3,12): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'C<T, U>' (but other type parameters do)
// class C<T, U>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "C<T, U>"),
// (6,15): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'C<T, U>.M<V, W, X>()' (but other type parameters do)
// void M<V, W, X>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "W").WithArguments("W", "C<T, U>.M<V, W, X>()"),
// (6,18): warning CS1712: Type parameter 'X' has no matching typeparam tag in the XML comment on 'C<T, U>.M<V, W, X>()' (but other type parameters do)
// void M<V, W, X>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "X").WithArguments("X", "C<T, U>.M<V, W, X>()"),
// (9,22): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (10,9): warning CS1712: Type parameter 'T' has no matching typeparam tag in the XML comment on 'C<T>' (but other type parameters do)
// class C<T>
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "T").WithArguments("T", "C<T>"),
// (12,26): warning CS1711: XML comment has a typeparam tag for 'Q', but there is no type parameter by that name
// /// <typeparam name="Q"/>
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "Q").WithArguments("Q"),
// (13,12): warning CS1712: Type parameter 'U' has no matching typeparam tag in the XML comment on 'C<T>.M<U>()' (but other type parameters do)
// void M<U>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "U").WithArguments("U", "C<T>.M<U>()"),
// (27,21): warning CS1712: Type parameter 'V' has no matching typeparam tag in the XML comment on 'P<T, U>.M1<V, W>()' (but other type parameters do)
// partial void M1<V, W>() { }
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "V").WithArguments("V", "P<T, U>.M1<V, W>()"),
// (20,24): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'P<T, U>.M1<V, W>()' (but other type parameters do)
// partial void M1<V, W>();
Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "W").WithArguments("W", "P<T, U>.M1<V, W>()"));
}
[Fact]
public void WRN_UnmatchedTypeParamRefTag()
{
var source = @"
/// <typeparamref name=""T""/> -- warning
class C
{
/// <typeparamref name=""T""/> -- warning
void M() { }
}
/// <typeparamref name=""T""/>
/// <typeparamref name=""U""/> -- warning
class C<T>
{
/// <typeparamref name=""U""/>
/// <typeparamref name=""V""/> -- warning
void M<U>() { }
}
/// <typeparamref name=""U""/> -- warning
partial class P<T>
{
/// <typeparamref name=""V""/> -- warning
partial void M1<U>();
}
/// <typeparamref name=""V""/> -- warning
partial class P<T>
{
/// <typeparamref name=""U""/> -- warning
partial void M1<V>() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (29,18): warning CS8826: Partial method declarations 'void P<T>.M1<U>()' and 'void P<T>.M1<V>()' have signature differences.
// partial void M1<V>() { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M1").WithArguments("void P<T>.M1<U>()", "void P<T>.M1<V>()").WithLocation(29, 18),
// (2,25): warning CS1735: XML comment on 'C' has a typeparamref tag for 'T', but there is no type parameter by that name
// /// <typeparamref name="T"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "T").WithArguments("T", "C"),
// (5,29): warning CS1735: XML comment on 'C.M()' has a typeparamref tag for 'T', but there is no type parameter by that name
// /// <typeparamref name="T"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "T").WithArguments("T", "C.M()"),
// (10,25): warning CS1735: XML comment on 'C<T>' has a typeparamref tag for 'U', but there is no type parameter by that name
// /// <typeparamref name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "U").WithArguments("U", "C<T>"),
// (14,29): warning CS1735: XML comment on 'C<T>.M<U>()' has a typeparamref tag for 'V', but there is no type parameter by that name
// /// <typeparamref name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "V").WithArguments("V", "C<T>.M<U>()"),
// (18,25): warning CS1735: XML comment on 'P<T>' has a typeparamref tag for 'U', but there is no type parameter by that name
// /// <typeparamref name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "U").WithArguments("U", "P<T>"),
// (25,25): warning CS1735: XML comment on 'P<T>' has a typeparamref tag for 'V', but there is no type parameter by that name
// /// <typeparamref name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "V").WithArguments("V", "P<T>"),
// (28,29): warning CS1735: XML comment on 'P<T>.M1<V>()' has a typeparamref tag for 'U', but there is no type parameter by that name
// /// <typeparamref name="U"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "U").WithArguments("U", "P<T>.M1<V>()"),
// (21,29): warning CS1735: XML comment on 'P<T>.M1<U>()' has a typeparamref tag for 'V', but there is no type parameter by that name
// /// <typeparamref name="V"/> -- warning
Diagnostic(ErrorCode.WRN_UnmatchedTypeParamRefTag, "V").WithArguments("V", "P<T>.M1<U>()"));
}
[Fact]
public void WRN_MissingXMLComment_Accessibility()
{
var source = @"
/// <summary/>
public class C
{
public void M1() { }
protected internal void M2() { }
protected void M3() { }
internal void M4() { }
private void M5() { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (5,17): warning CS1591: Missing XML comment for publicly visible type or member 'C.M1()'
// public void M1() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M1").WithArguments("C.M1()"),
// (6,29): warning CS1591: Missing XML comment for publicly visible type or member 'C.M2()'
// protected internal void M2() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M2").WithArguments("C.M2()"),
// (7,20): warning CS1591: Missing XML comment for publicly visible type or member 'C.M3()'
// protected void M3() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M3").WithArguments("C.M3()"));
}
[Fact]
public void WRN_MissingXMLComment_EffectiveAccessibility()
{
var source = @"
/// <summary/>
public class A
{
/// <summary/>
public class B1
{
/// <summary/>
public class C
{
public void M1() { }
}
}
/// <summary/>
protected internal class B2
{
/// <summary/>
public class C
{
public void M2() { }
}
}
/// <summary/>
protected class B3
{
/// <summary/>
public class C
{
public void M3() { }
}
}
internal class B4
{
public class C
{
public void M4() { }
}
}
private class B5
{
public class C
{
public void M5() { }
}
}
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (11,25): warning CS1591: Missing XML comment for publicly visible type or member 'A.B1.C.M1()'
// public void M1() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M1").WithArguments("A.B1.C.M1()"),
// (21,25): warning CS1591: Missing XML comment for publicly visible type or member 'A.B2.C.M2()'
// public void M2() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M2").WithArguments("A.B2.C.M2()"),
// (31,25): warning CS1591: Missing XML comment for publicly visible type or member 'A.B3.C.M3()'
// public void M3() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "M3").WithArguments("A.B3.C.M3()"));
}
[Fact]
public void WRN_MissingXMLComment_Kind()
{
var source = @"
/// <summary/>
public class C
{
public class Class { }
public void Method() { }
public int Field;
public int Property { get; set; }
public int this[int x] { get { return 0; } set { } }
public event System.Action FieldLikeEvent;
public event System.Action Event { add { } remove { } }
public delegate void Delegate();
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (5,18): warning CS1591: Missing XML comment for publicly visible type or member 'C.Class'
// public class Class { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Class").WithArguments("C.Class"),
// (6,17): warning CS1591: Missing XML comment for publicly visible type or member 'C.Method()'
// public void Method() { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Method").WithArguments("C.Method()"),
// (7,16): warning CS1591: Missing XML comment for publicly visible type or member 'C.Field'
// public int Field;
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Field").WithArguments("C.Field"),
// (8,16): warning CS1591: Missing XML comment for publicly visible type or member 'C.Property'
// public int Property { get; set; }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Property").WithArguments("C.Property"),
// (9,16): warning CS1591: Missing XML comment for publicly visible type or member 'C.this[int]'
// public int this[int x] { get { return 0; } set { } }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "this").WithArguments("C.this[int]"),
// (10,32): warning CS1591: Missing XML comment for publicly visible type or member 'C.FieldLikeEvent'
// public event System.Action FieldLikeEvent;
Diagnostic(ErrorCode.WRN_MissingXMLComment, "FieldLikeEvent").WithArguments("C.FieldLikeEvent"),
// (11,32): warning CS1591: Missing XML comment for publicly visible type or member 'C.Event'
// public event System.Action Event { add { } remove { } }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Event").WithArguments("C.Event"),
// (12,26): warning CS1591: Missing XML comment for publicly visible type or member 'C.Delegate'
// public delegate void Delegate();
Diagnostic(ErrorCode.WRN_MissingXMLComment, "Delegate").WithArguments("C.Delegate"),
// (10,32): warning CS0067: The event 'C.FieldLikeEvent' is never used
// public event System.Action FieldLikeEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "FieldLikeEvent").WithArguments("C.FieldLikeEvent"));
}
[Fact]
public void WRN_MissingXMLComment_Interface()
{
var source = @"
interface I
{
void M();
}
";
// As in dev11, doesn't count since the *declared* accessibility is not public.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics();
}
[Fact]
public void WRN_MissingXMLComment_PartialClass()
{
var source = @"
/// <summary/>
public partial class C { }
public partial class C { }
public partial class D { }
public partial class D { }
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (6,22): warning CS1591: Missing XML comment for publicly visible type or member 'D'
// public partial class D { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "D").WithArguments("D"));
}
[Fact]
public void WRN_MissingXMLComment_DifferentOptions()
{
var source1 = @"
/// <summary/>
public partial class C { }
public partial class D { }
public partial class E { }
";
var source2 = @"
public partial class C { }
/// <summary/>
public partial class D { }
public partial class E { }
";
var tree1 = Parse(source1, options: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose).WithLanguageVersion(LanguageVersion.Latest));
var tree2 = Parse(source2, options: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None).WithLanguageVersion(LanguageVersion.Latest));
// This scenario does not exist in dev11, but the diagnostics seem reasonable.
CreateCompilation(new[] { tree1, tree2 }).VerifyDiagnostics(
// (5,22): warning CS1591: Missing XML comment for publicly visible type or member 'D'
// public partial class D { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "D").WithArguments("D").WithLocation(5, 22),
// (7,22): warning CS1591: Missing XML comment for publicly visible type or member 'E'
// public partial class E { }
Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E").WithLocation(7, 22));
}
[Fact]
public void WRN_BadXMLRefParamType()
{
var source = @"
/// <see cref=""M(Q)""/>
/// <see cref=""M(C{Q})""/>
/// <see cref=""M(Q[])""/>
/// <see cref=""M(Q*)""/>
class C
{
void M(int x) { }
}
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (2,16): warning CS1580: Invalid type for parameter 'Q' in XML comment cref attribute: 'M(Q)'
// /// <see cref="M(Q)"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "Q").WithArguments("Q", "M(Q)"),
// (2,16): warning CS1574: XML comment has cref attribute 'M(Q)' that could not be resolved
// /// <see cref="M(Q)"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "M(Q)").WithArguments("M(Q)"),
// (3,16): warning CS1580: Invalid type for parameter 'C{Q}' in XML comment cref attribute: 'M(C{Q})'
// /// <see cref="M(C{Q})"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "C{Q}").WithArguments("C{Q}", "M(C{Q})"),
// (3,16): warning CS1574: XML comment has cref attribute 'M(C{Q})' that could not be resolved
// /// <see cref="M(C{Q})"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "M(C{Q})").WithArguments("M(C{Q})"),
// (4,16): warning CS1580: Invalid type for parameter 'Q[]' in XML comment cref attribute: 'M(Q[])'
// /// <see cref="M(Q[])"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "Q[]").WithArguments("Q[]", "M(Q[])"),
// (4,16): warning CS1574: XML comment has cref attribute 'M(Q[])' that could not be resolved
// /// <see cref="M(Q[])"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "M(Q[])").WithArguments("M(Q[])"),
// (5,16): warning CS1580: Invalid type for parameter 'Q*' in XML comment cref attribute: 'M(Q*)'
// /// <see cref="M(Q*)"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "Q*").WithArguments("Q*", "M(Q*)"),
// (5,16): warning CS1574: XML comment has cref attribute 'M(Q*)' that could not be resolved
// /// <see cref="M(Q*)"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "M(Q*)").WithArguments("M(Q*)"));
}
[Fact]
public void WRN_BadXMLRefReturnType()
{
var source = @"
/// <see cref=""explicit operator Q""/>
/// <see cref=""explicit operator C{Q}""/>
/// <see cref=""explicit operator Q[]""/>
/// <see cref=""explicit operator Q*""/>
class C
{
public static explicit operator int(C c) { return 0; }
}
";
// BREAK: dev11 doesn't report CS1581 for "Q[]" or "Q*" because it only checks for error
// types and it finds an array type and a pointer type, respectively.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (2,16): warning CS1581: Invalid return type in XML comment cref attribute
// /// <see cref="explicit operator Q"/>
Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "Q").WithArguments("Q", "explicit operator Q"),
// (2,16): warning CS1574: XML comment has cref attribute 'explicit operator Q' that could not be resolved
// /// <see cref="explicit operator Q"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator Q").WithArguments("explicit operator Q"),
// (3,16): warning CS1581: Invalid return type in XML comment cref attribute
// /// <see cref="explicit operator C{Q}"/>
Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "C{Q}").WithArguments("C{Q}", "explicit operator C{Q}"),
// (3,16): warning CS1574: XML comment has cref attribute 'explicit operator C{Q}' that could not be resolved
// /// <see cref="explicit operator C{Q}"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator C{Q}").WithArguments("explicit operator C{Q}"),
// (4,16): warning CS1581: Invalid return type in XML comment cref attribute
// /// <see cref="explicit operator Q[]"/>
Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "Q[]").WithArguments("Q[]", "explicit operator Q[]"),
// (4,16): warning CS1574: XML comment has cref attribute 'explicit operator Q[]' that could not be resolved
// /// <see cref="explicit operator Q[]"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator Q[]").WithArguments("explicit operator Q[]"),
// (5,16): warning CS1581: Invalid return type in XML comment cref attribute
// /// <see cref="explicit operator Q*"/>
Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "Q*").WithArguments("Q*", "explicit operator Q*"),
// (5,16): warning CS1574: XML comment has cref attribute 'explicit operator Q*' that could not be resolved
// /// <see cref="explicit operator Q*"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "explicit operator Q*").WithArguments("explicit operator Q*"));
}
[Fact]
public void WRN_BadXMLRefTypeVar()
{
// NOTE: there isn't a corresponding case for indexers since they use an impossible member name.
var source = @"
class C<T, op_Explicit, op_Division>
{
/// <see cref=""T""/>
/// <see cref=""explicit operator int""/>
/// <see cref=""operator /""/>
void M() { }
}
";
// BREAK: Dev11 reports WRN_BadXMLRef, instead of WRN_BadXMLRefTypeVar, for the conversion operator.
// This seems like a bug; it binds to the type parameter, but throw it away because it's not a conversion
// method. On its own, this seems reasonable, but it actually performs this filtering *after* accepting
// type symbols for crefs without parameter lists (see Conversion_Type()). Therefore, conversion crefs
// can bind to aggregates, but not type parameters. To be both more consistent and more permissive,
// Roslyn binds to the type parameter and produces a more specific error messages.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (4,20): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter
// /// <see cref="T"/>
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T"),
// (5,20): warning CS1723: XML comment has cref attribute 'explicit operator int' that refers to a type parameter
// /// <see cref="explicit operator int"/>
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "explicit operator int").WithArguments("explicit operator int"),
// (6,20): warning CS1723: XML comment has cref attribute 'operator /' that refers to a type parameter
// /// <see cref="operator /"/>
Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "operator /").WithArguments("operator /"));
}
[WorkItem(530970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530970")]
[Fact]
public void DanglingDocComment()
{
var source = @"
/// <summary>
/// See <see cref=""C""/>.
/// </summary>
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
Assert.Equal(SyntaxKind.EndOfFileToken, crefSyntax.Ancestors().First(n => n.IsStructuredTrivia).ParentTrivia.Token.Kind());
model.GetSymbolInfo(crefSyntax);
}
[WorkItem(530969, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530969")]
[Fact]
public void MissingCrefTypeParameter()
{
var source = @"
/// <summary>
/// See <see cref=""C{}""/>.
/// </summary>
class C<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
model.GetSymbolInfo(crefSyntax);
model.GetSymbolInfo(((GenericNameSyntax)crefSyntax.Name).TypeArgumentList.Arguments.Single());
}
[WorkItem(530969, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530969")]
[Fact]
public void InvalidCrefTypeParameter()
{
var source = @"
/// <summary>
/// See <see cref=""C{&}""/>.
/// </summary>
class C<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
model.GetSymbolInfo(crefSyntax);
model.GetSymbolInfo(((GenericNameSyntax)crefSyntax.Name).TypeArgumentList.Arguments.Single());
}
[Fact]
public void GenericTypeArgument()
{
var source = @"
/// <summary>
/// See <see cref=""C{C{T}}""/>.
/// </summary>
class C<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
model.GetSymbolInfo(crefSyntax);
model.GetSymbolInfo(((GenericNameSyntax)crefSyntax.Name).TypeArgumentList.Arguments.Single());
}
[Fact]
public void CrefAttributeNameCaseMismatch()
{
var source = @"
/// <summary>
/// See <see Cref=""C{C{T}}""/>.
/// </summary>
class C<T> { }
";
// Element names don't have to be lowercase, but "cref" does.
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
AssertEx.None(GetCrefSyntaxes(compilation), x => true);
}
[WorkItem(546965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546965")]
[Fact]
public void MultipleCrefs()
{
var source = @"
/// <summary>
/// See <see cref=""int""/>.
/// See <see cref=""C{T}""/>.
/// </summary>
class C<T> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(compilation);
// Make sure we're not reusing the binder from the first cref (no type parameters)
// for the second cref (has type parameters).
model.GetSymbolInfo(crefSyntaxes.ElementAt(0));
model.GetSymbolInfo(crefSyntaxes.ElementAt(1));
}
[WorkItem(546992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546992")]
[Fact]
public void NestedGenerics()
{
var source = @"
/// <summary>
/// Error <see cref=""A{A{T}}""/>.
/// Error <see cref=""A{T}.B{A{T}}""/>.
/// Error <see cref=""A{T}.B{U}.M{A{T}}""/>.
/// Fine <see cref=""A{T}.B{U}.M{V}(A{A{T}})""/>.
/// Fine <see cref=""A{T}.B{U}.explicit operator A{A{T}}""/>.
/// </summary>
class A<T>
{
class B<U>
{
internal void M<V>(A<A<T>> a) { }
public static explicit operator A<A<T>>(B<U> b) { throw null; }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{A{T}}'
// /// Error <see cref="A{A{T}}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{A{T}}").WithArguments("A{A{T}}"),
// (3,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{A{T}}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "A{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{T}.B{A{T}}'
// /// Error <see cref="A{T}.B{A{T}}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{T}.B{A{T}}").WithArguments("A{T}.B{A{T}}"),
// (4,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{T}.B{A{T}}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "A{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (5,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{T}.B{U}.M{A{T}}'
// /// Error <see cref="A{T}.B{U}.M{A{T}}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{T}.B{U}.M{A{T}}").WithArguments("A{T}.B{U}.M{A{T}}"),
// (5,34): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{T}.B{U}.M{A{T}}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "A{T}").WithArguments("Type parameter declaration must be an identifier not a type", "0081"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(compilation);
Assert.Equal(5, crefSyntaxes.Count());
var symbols = crefSyntaxes.Select(cref => model.GetSymbolInfo(cref).Symbol).ToArray();
Assert.Equal("A<A<T>>", symbols[0].ToTestDisplayString());
Assert.Equal("A<T>.B<A<T>>", symbols[1].ToTestDisplayString());
Assert.Equal("void A<T>.B<U>.M<A<T>>(A<A<T>> a)", symbols[2].ToTestDisplayString());
Assert.Equal("void A<T>.B<U>.M<V>(A<A<T>> a)", symbols[3].ToTestDisplayString());
Assert.Equal("A<A<T>> A<T>.B<U>.op_Explicit(A<T>.B<U> b)", symbols[4].ToTestDisplayString());
}
[WorkItem(546992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546992")]
[WorkItem(546993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546993")]
[Fact]
public void NestedPredefinedTypes()
{
var source = @"
/// <summary>
/// Error <see cref=""A{int}""/>.
/// Error <see cref=""A{T}.B{int}""/>.
/// Error <see cref=""A{T}.B{U}.M{int}""/>.
/// Fine <see cref=""A{T}.B{U}.M{V}(A{int})""/>.
/// Fine <see cref=""A{T}.B{U}.explicit operator A{int}""/>.
/// </summary>
class A<T>
{
class B<U>
{
internal void M<V>(A<int> a) { }
public static explicit operator A<int>(B<U> b) { throw null; }
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{int}'
// /// Error <see cref="A{int}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{int}").WithArguments("A{int}"),
// (3,24): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{int}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (4,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{T}.B{int}'
// /// Error <see cref="A{T}.B{int}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{T}.B{int}").WithArguments("A{T}.B{int}"),
// (4,29): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{T}.B{int}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"),
// (5,22): warning CS1584: XML comment has syntactically incorrect cref attribute 'A{T}.B{U}.M{int}'
// /// Error <see cref="A{T}.B{U}.M{int}"/>.
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "A{T}.B{U}.M{int}").WithArguments("A{T}.B{U}.M{int}"),
// (5,34): warning CS1658: Type parameter declaration must be an identifier not a type. See also error CS0081.
// /// Error <see cref="A{T}.B{U}.M{int}"/>.
Diagnostic(ErrorCode.WRN_ErrorOverride, "int").WithArguments("Type parameter declaration must be an identifier not a type", "0081"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(compilation);
Assert.Equal(5, crefSyntaxes.Count());
var symbols = crefSyntaxes.Select(cref => model.GetSymbolInfo(cref).Symbol).ToArray();
Assert.Equal("A<System.Int32>", symbols[0].ToTestDisplayString());
Assert.Equal("A<T>.B<System.Int32>", symbols[1].ToTestDisplayString());
Assert.Equal("void A<T>.B<U>.M<System.Int32>(A<System.Int32> a)", symbols[2].ToTestDisplayString());
Assert.Equal("void A<T>.B<U>.M<V>(A<System.Int32> a)", symbols[3].ToTestDisplayString());
Assert.Equal("A<System.Int32> A<T>.B<U>.op_Explicit(A<T>.B<U> b)", symbols[4].ToTestDisplayString());
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void NewMethods1()
{
var source = @"
class Base
{
public virtual void M() { }
}
/// <see cref=""Derived.M"" />
class Derived : Base
{
public new void M() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M");
Assert.Equal(overridingMethod, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void NewMethods2()
{
var source = @"
class Base
{
public virtual void M() { }
}
class Middle : Base
{
public new void M() { }
}
/// <see cref=""Derived.M"" />
class Derived : Middle
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (12,16): warning CS1574: XML comment has cref attribute 'Derived.M' that could not be resolved
// /// <see cref="Derived.M" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "Derived.M").WithArguments("M"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Middle").GetMember<MethodSymbol>("M");
Assert.Null(model.GetSymbolInfo(cref).Symbol); // As in dev11.
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[WorkItem(547037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547037")]
[Fact]
public void NewMethods3()
{
var source = @"
class Base
{
public virtual void M() { }
}
/// <see cref=""M"" />
class Derived : Base
{
public new void M() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M");
Assert.Equal(overridingMethod, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void Overrides1()
{
var source = @"
class Base
{
public virtual void M() { }
}
/// <see cref=""Derived.M"" />
class Derived : Base
{
public override void M() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M");
Assert.Equal(overridingMethod, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void Overrides2()
{
var source = @"
class Base
{
public virtual void M() { }
}
class Middle : Base
{
public override void M() { }
}
/// <see cref=""Derived.M"" />
class Derived : Middle
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (12,16): warning CS1574: XML comment has cref attribute 'Derived.M' that could not be resolved
// /// <see cref="Derived.M" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "Derived.M").WithArguments("M"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol); // As in dev11.
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[WorkItem(547037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547037")]
[Fact]
public void Overrides3()
{
var source = @"
class Base
{
public virtual void M() { }
}
/// <see cref=""M"" />
class Derived : Base
{
public override void M() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var overridingMethod = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M");
Assert.Equal(overridingMethod, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546991")]
[Fact]
public void ExtensionMethod()
{
var source = @"
static class Extensions
{
public static void M1(this Derived d) { }
public static void M2(this Derived d) { }
public static void M3(this Derived d) { }
}
class Base
{
public void M2() { }
}
/// <see cref=""Derived.M1"" />
/// <see cref=""Derived.M2"" />
/// <see cref=""Derived.M3"" />
class Derived : Base
{
public void M1() { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source, parseOptions: TestOptions.RegularWithDocumentationComments);
compilation.VerifyDiagnostics(
// (15,16): warning CS1574: XML comment has cref attribute 'Derived.M2' that could not be resolved
// /// <see cref="Derived.M2" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "Derived.M2").WithArguments("M2"),
// (16,16): warning CS1574: XML comment has cref attribute 'Derived.M3' that could not be resolved
// /// <see cref="Derived.M3" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "Derived.M3").WithArguments("M3"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
var global = compilation.GlobalNamespace;
var derivedM1 = global.GetMember<INamedTypeSymbol>("Derived").GetMember<IMethodSymbol>("M1");
var baseM2 = global.GetMember<INamedTypeSymbol>("Base").GetMember<IMethodSymbol>("M2");
Assert.Equal(derivedM1, model.GetSymbolInfo(crefs[0]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[1]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[2]).Symbol);
}
[WorkItem(546990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546990")]
[Fact]
public void ConstructorOfGenericTypeWithinThatType()
{
var source = @"
/// Fine <see cref=""G()""/>.
/// Fine <see cref=""G{T}()""/>.
class G<T> { }
/// Error <see cref=""G()""/>.
/// Fine <see cref=""G{T}()""/>.
class Other { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (6,22): warning CS1574: XML comment has cref attribute 'G()' that could not be resolved
// /// Error <see cref="G()"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "G()").WithArguments("G()"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
var constructor = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("G").InstanceConstructors.Single();
Assert.Equal(constructor, model.GetSymbolInfo(crefs[0]).Symbol.OriginalDefinition);
Assert.Equal(constructor, model.GetSymbolInfo(crefs[1]).Symbol.OriginalDefinition);
Assert.Null(model.GetSymbolInfo(crefs[2]).Symbol);
Assert.Equal(constructor, model.GetSymbolInfo(crefs[3]).Symbol.OriginalDefinition);
}
[WorkItem(546990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546990")]
[Fact]
public void ConstructorOfGenericTypeWithinNestedType()
{
var source = @"
class Outer<T>
{
class Inner<U>
{
/// <see cref=""Outer()""/>
void M()
{
}
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (6,24): warning CS1574: XML comment has cref attribute 'Outer()' that could not be resolved
// /// <see cref="Outer()"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Outer()").WithArguments("Outer()"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(546990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546990")]
[WorkItem(554077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554077")]
[Fact]
public void QualifiedConstructorOfGenericTypeWithinNestedType()
{
var source = @"
/// <see cref=""Outer{T}.Outer""/>
class Outer<T>
{
/// <see cref=""Outer{T}.Outer""/>
void M()
{
}
/// <see cref=""Outer{T}.Outer""/>
class Inner<U>
{
/// <see cref=""Outer{T}.Outer""/>
void M()
{
}
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'Outer{T}.Outer' that could not be resolved
// /// <see cref="Outer{T}.Outer"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Outer{T}.Outer").WithArguments("Outer"),
// (5,20): warning CS1574: XML comment has cref attribute 'Outer{T}.Outer' that could not be resolved
// /// <see cref="Outer{T}.Outer"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Outer{T}.Outer").WithArguments("Outer"));
var outerCtor = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Outer").InstanceConstructors.Single();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation);
var expectedSymbols = new ISymbol[] { null, null, outerCtor, outerCtor };
var actualSymbols = GetCrefOriginalDefinitions(model, crefs);
AssertEx.Equal(expectedSymbols, actualSymbols);
}
// VB had some problems with these cases between dev10 and dev11.
[WorkItem(546989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546989")]
[Fact]
public void GenericTypeWithoutTypeParameters()
{
var source = @"
class GenericClass<T>
{
internal void NormalSub()
{
}
internal void GenericSub<T2>()
{
}
}
/// <summary>This is other class</summary>
/// <remarks>
/// You may also like <see cref=""GenericClass""/>. <see cref=""GenericClass{T}""/> provides you some interesting methods.
/// <see cref=""GenericClass{T}.NormalSub""/> is normal. <see cref=""GenericClass.NormalSub""/> performs a normal operation.
/// <see cref=""GenericClass{T}.GenericSub""/> is generic. <see cref=""GenericClass.GenericSub""/> performs a generic operation.
/// <see cref=""GenericClass{T}.GenericSub{T}""/> has a generic parameter.
/// <see cref=""GenericClass.GenericSub{T}""/> 's parameters is called <c>T2</c>.
/// </remarks>
class SomeOtherClass
{
}
";
var tree = Parse(source, options: TestOptions.RegularWithDocumentationComments);
var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(new[] { tree });
compilation.VerifyDiagnostics(
// (15,34): warning CS1574: XML comment has cref attribute 'GenericClass' that could not be resolved
// /// You may also like <see cref="GenericClass"/>. <see cref="GenericClass{T}"/> provides you some interesting methods.
Diagnostic(ErrorCode.WRN_BadXMLRef, "GenericClass").WithArguments("GenericClass"),
// (16,67): warning CS1574: XML comment has cref attribute 'GenericClass.NormalSub' that could not be resolved
// /// <see cref="GenericClass{T}.NormalSub"/> is normal. <see cref="GenericClass.NormalSub"/> performs a normal operation.
Diagnostic(ErrorCode.WRN_BadXMLRef, "GenericClass.NormalSub").WithArguments("NormalSub"),
// (17,69): warning CS1574: XML comment has cref attribute 'GenericClass.GenericSub' that could not be resolved
// /// <see cref="GenericClass{T}.GenericSub"/> is generic. <see cref="GenericClass.GenericSub"/> performs a generic operation.
Diagnostic(ErrorCode.WRN_BadXMLRef, "GenericClass.GenericSub").WithArguments("GenericSub"),
// (19,16): warning CS1574: XML comment has cref attribute 'GenericClass.GenericSub{T}' that could not be resolved
// /// <see cref="GenericClass.GenericSub{T}"/> 's parameters is called <c>T2</c>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "GenericClass.GenericSub{T}").WithArguments("GenericSub{T}"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("GenericClass");
var nonGenericMethod = type.GetMember<IMethodSymbol>("NormalSub");
var genericMethod = type.GetMember<IMethodSymbol>("GenericSub");
Assert.Null(model.GetSymbolInfo(crefs[0]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[3]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[5]).Symbol);
Assert.Null(model.GetSymbolInfo(crefs[7]).Symbol);
Assert.Equal(type, model.GetSymbolInfo(crefs[1]).Symbol.OriginalDefinition);
Assert.Equal(nonGenericMethod, model.GetSymbolInfo(crefs[2]).Symbol.OriginalDefinition);
Assert.Equal(genericMethod, model.GetSymbolInfo(crefs[4]).Symbol.OriginalDefinition);
Assert.Equal(genericMethod, model.GetSymbolInfo(crefs[6]).Symbol.OriginalDefinition);
}
[WorkItem(546990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546990")]
[Fact]
public void Dynamic()
{
// This can't bind to the type "dynamic" because it is not a type-only context
// (e.g. a method called "dynamic" would be fine).
var source = @"
/// <see cref=""dynamic""/>
class C
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'dynamic' that could not be resolved
// /// <see cref="dynamic"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "dynamic").WithArguments("dynamic"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[Fact]
public void DynamicConstructor()
{
var source = @"
/// <see cref=""dynamic()""/>
class C
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source, new[] { SystemCoreRef });
compilation.VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'dynamic()' that could not be resolved
// /// <see cref="dynamic()"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "dynamic()").WithArguments("dynamic()"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[Fact]
public void DynamicInParameters()
{
// BREAK: Dev11 drops candidates with "dynamic" anywhere in their parameter lists.
// As a result, it does not match the first two or last two crefs.
var source = @"
/// <see cref=""M1(dynamic)""/>
/// <see cref=""M1(C{dynamic})""/>
/// <see cref=""M2(object)""/>
/// <see cref=""M2(C{object})""/>
///
/// <see cref=""M1(object)""/>
/// <see cref=""M1(C{object})""/>
/// <see cref=""M2(dynamic)""/>
/// <see cref=""M2(C{dynamic})""/>
class C<T>
{
void M1(dynamic p) { }
void M1(C<dynamic> p) { }
void M2(object p) { }
void M2(C<object> p) { }
}
";
SyntaxTree tree = Parse(source, options: TestOptions.RegularWithDocumentationComments);
var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(new[] { tree });
compilation.VerifyDiagnostics();
var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
//NOTE: deterministic, since GetMembers respects syntax order.
var m1a = type.GetMembers("M1").First();
var m1b = type.GetMembers("M1").Last();
var m2a = type.GetMembers("M2").First();
var m2b = type.GetMembers("M2").Last();
var model = compilation.GetSemanticModel(tree);
var crefs = GetCrefSyntaxes(compilation).ToArray();
Assert.Equal(8, crefs.Length);
Assert.Equal(m1a, model.GetSymbolInfo(crefs[0]).Symbol.OriginalDefinition);
Assert.Equal(m1b, model.GetSymbolInfo(crefs[1]).Symbol.OriginalDefinition);
Assert.Equal(m2a, model.GetSymbolInfo(crefs[2]).Symbol.OriginalDefinition);
Assert.Equal(m2b, model.GetSymbolInfo(crefs[3]).Symbol.OriginalDefinition);
Assert.Equal(m1a, model.GetSymbolInfo(crefs[4]).Symbol.OriginalDefinition);
Assert.Equal(m1b, model.GetSymbolInfo(crefs[5]).Symbol.OriginalDefinition);
Assert.Equal(m2a, model.GetSymbolInfo(crefs[6]).Symbol.OriginalDefinition);
Assert.Equal(m2b, model.GetSymbolInfo(crefs[7]).Symbol.OriginalDefinition);
}
[WorkItem(531152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531152")]
[Fact]
public void MissingArgumentTypes()
{
var source = @"
using System;
/// <see cref=""Console.WriteLine(,,)""/>
class Program
{
}
";
// Note: using is unused because syntactically invalid cref is never bound.
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (4,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'Console.WriteLine(,,)'
// /// <see cref="Console.WriteLine(,,)"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "Console.WriteLine(,,)").WithArguments("Console.WriteLine(,,)"),
// (4,34): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref="Console.WriteLine(,,)"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, ",").WithArguments("Identifier expected", "1001"),
// (4,35): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref="Console.WriteLine(,,)"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, ",").WithArguments("Identifier expected", "1001"),
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531135")]
[Fact]
public void NonOverloadableOperator()
{
var source = @"
/// <see cref=""operator =""/>
class Program
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator ='
// /// <see cref="operator ="/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator").WithArguments("operator ="),
// (2,25): warning CS1658: Overloadable operator expected. See also error CS1037.
// /// <see cref="operator ="/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "=").WithArguments("Overloadable operator expected", "1037"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531135")]
[Fact]
public void InvalidOperator()
{
var source = @"
/// <see cref=""operator q""/>
class Program
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (4,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator q'
// /// <see cref="operator q"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator").WithArguments("operator q"),
// (4,25): warning CS1658: Overloadable operator expected. See also error CS1037.
// /// <see cref="operator q"/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "q").WithArguments("Overloadable operator expected", "1037"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(547041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547041")]
[Fact]
public void EmptyVerbatimIdentifier()
{
var source = @"
/// <see cref=""@""/>
class Program
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute '@'
// /// <see cref="@"/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "@").WithArguments("@"),
// (2,16): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
// /// <see cref="@"/>
Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, ""));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531161")]
[Fact]
public void AttributeNameHasPrefix()
{
var source = @"
/// <see xmlns:cref=""Invalid""/>
class Program
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
Assert.Equal(0, GetCrefSyntaxes(compilation).Count());
}
[WorkItem(531160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531160")]
[Fact]
public void DuplicateAttribute()
{
var source = @"
/// <see cref=""int"" cref=""long""/>
class Program
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,20): warning CS1570: XML comment has badly formed XML -- 'Duplicate 'cref' attribute'
// /// <see cref="int" cref="long"/>
Diagnostic(ErrorCode.WRN_XMLParseError, @" cref=""long").WithArguments("cref"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(compilation).ToArray();
Assert.Equal(compilation.GetSpecialType(SpecialType.System_Int32), model.GetSymbolInfo(crefSyntaxes[0]).Symbol);
Assert.Equal(compilation.GetSpecialType(SpecialType.System_Int64), model.GetSymbolInfo(crefSyntaxes[1]).Symbol);
}
[WorkItem(531157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531157")]
[Fact]
public void IntPtrConversion()
{
var source = @"
using System;
/// <see cref=""IntPtr.op_Explicit(void*)""/>
class C
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Equal("System.IntPtr System.IntPtr.op_Explicit(System.Void* value)", model.GetSymbolInfo(cref).Symbol.ToTestDisplayString());
}
[WorkItem(531233, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531233")]
[Fact]
public void CrefInOtherElement()
{
var source = @"
/// <other cref=""C""/>
class C
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531162")]
[Fact]
public void OuterVersusInheritedFromOuter()
{
var source = @"
class C<T>
{
public void Goo(T x) { }
class D : C<int>
{
/// <see cref=""Goo(T)""/>
void Bar() { }
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("Goo");
Assert.Equal(expectedSymbol, model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(531344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531344")]
[Fact]
public void ConstraintsInCrefs()
{
var source = @"
/// <see cref=""Outer{Q}.Inner""/>
class Outer<T> where T: System.IFormattable
{
class Inner { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Outer").GetMember<INamedTypeSymbol>("Inner");
Assert.Equal(expectedSymbol, model.GetSymbolInfo(cref).Symbol.OriginalDefinition);
}
[Fact]
public void CrefTypeParameterEquality1()
{
var source = @"
/// <see cref=""C{Q}""/>
class C<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
Func<Symbol> lookupSymbol = () =>
{
var factory = new BinderFactory(compilation, tree, ignoreAccessibility: false);
var binder = factory.GetBinder(cref);
var lookupResult = LookupResult.GetInstance();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
binder.LookupSymbolsSimpleName(
lookupResult,
qualifierOpt: null,
plainName: "Q",
arity: 0,
basesBeingResolved: null,
options: LookupOptions.Default,
diagnose: false,
useSiteDiagnostics: ref useSiteDiagnostics);
Assert.Equal(LookupResultKind.Viable, lookupResult.Kind);
var symbol = lookupResult.Symbols.Single();
lookupResult.Free();
Assert.NotNull(symbol);
Assert.IsType<CrefTypeParameterSymbol>(symbol);
return symbol;
};
var symbol1 = lookupSymbol();
var symbol2 = lookupSymbol();
Assert.Equal(symbol1, symbol2); // Required for correctness.
Assert.NotSame(symbol1, symbol2); // Not required, just documenting.
}
[Fact]
public void CrefTypeParameterEquality2()
{
var source = @"
/// <see cref=""C{T}""/>
class C<T>
{
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(tree);
var referencedType = (INamedTypeSymbol)model.GetSymbolInfo(cref).Symbol;
Assert.NotNull(referencedType);
var crefTypeParam = referencedType.TypeArguments.Single();
Assert.IsType<CrefTypeParameterSymbol>(crefTypeParam.GetSymbol());
var sourceTypeParam = referencedType.TypeParameters.Single();
Assert.IsType<SourceTypeParameterSymbol>(sourceTypeParam.GetSymbol());
Assert.NotEqual(crefTypeParam, sourceTypeParam);
Assert.NotEqual(sourceTypeParam, crefTypeParam);
}
[WorkItem(531337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531337")]
[Fact]
public void CrefInMethodBody()
{
var source = @"
class C
{
void M()
{
/// <see cref=""C""/>
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (6,9): warning CS1587: XML comment is not placed on a valid language element
// /// <see cref="C"/>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(tree);
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(531337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531337")]
[Fact]
public void CrefOnAccessor()
{
var source = @"
class C
{
int P
{
/// <see cref=""C""/>
get { return 0; }
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (6,9): warning CS1587: XML comment is not placed on a valid language element
// /// <see cref="C"/>
Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/"));
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(tree);
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(531391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531391")]
[Fact]
public void IncompleteGenericCrefMissingName()
{
var source = @"
/// <see cref=' {'/>
class C { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute ' {'
// /// <see cref=' {'/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, " {").WithArguments(" {"),
// (2,17): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref=' {'/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "{").WithArguments("Identifier expected", "1001"),
// (2,18): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref=' {'/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "'").WithArguments("Identifier expected", "1001"),
// (2,18): warning CS1658: Syntax error, '>' expected. See also error CS1003.
// /// <see cref=' {'/>
Diagnostic(ErrorCode.WRN_ErrorOverride, "'").WithArguments("Syntax error, '>' expected", "1003"));
var tree = compilation.SyntaxTrees.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(tree);
Assert.Null(model.GetSymbolInfo(cref).Symbol);
}
[WorkItem(548900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/548900")]
[Fact]
public void InvalidOperatorCref()
{
var source = @"
/// <see cref=""operator@""/>
class C
{
public static C operator +(C x, C y) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var cref = GetCrefSyntaxes(compilation).Single();
AssertEx.None(cref.DescendantTokens(descendIntoTrivia: true), token => token.ValueText == null);
}
[WorkItem(549210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/549210")]
[Fact]
public void InvalidGenericCref()
{
var source = @"
///<see cref=""X{@
///
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var cref = GetCrefSyntaxes(compilation).Single();
AssertEx.None(cref.DescendantTokens(descendIntoTrivia: true), token => token.ValueText == null);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
foreach (var id in cref.DescendantNodes().OfType<NameSyntax>())
{
Assert.Null(model.GetSymbolInfo(id).Symbol); //Used to assert/throw.
}
}
[WorkItem(549351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/549351")]
[Fact]
public void CrefNotOnMember()
{
var source = @"
/// <see cref=""decimal.operator
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var cref = GetCrefSyntaxes(compilation).Single();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var symbol = model.GetSymbolInfo(cref).Symbol;
Assert.NotNull(symbol);
Assert.Equal(MethodKind.UserDefinedOperator, ((IMethodSymbol)symbol).MethodKind);
Assert.Equal(WellKnownMemberNames.AdditionOperatorName, symbol.Name);
Assert.Equal(SpecialType.System_Decimal, symbol.ContainingType.SpecialType);
}
[WorkItem(551354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551354")]
[Fact]
public void DotIntoTypeParameter1()
{
var source = @"
/// <see cref=""F{T}(T.C)""/>
class C
{
void F<T>(T t) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1580: Invalid type for parameter 'T.C' in XML comment cref attribute: 'F{T}(T.C)'
// /// <see cref="F{T}(T.C)"/>
Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "T.C").WithArguments("T.C", "F{T}(T.C)"),
// (2,16): warning CS1574: XML comment has cref attribute 'F{T}(T.C)' that could not be resolved
// /// <see cref="F{T}(T.C)"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "F{T}(T.C)").WithArguments("F{T}(T.C)"));
var cref = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var parameterType = cref.Parameters.Parameters.Single().Type;
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var info = model.GetSymbolInfo(parameterType);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
var parameterTypeContainingType = parameterType.DescendantNodes().OfType<SimpleNameSyntax>().First();
var containingTypeInfo = model.GetSymbolInfo(parameterTypeContainingType);
Assert.IsType<CrefTypeParameterSymbol>(containingTypeInfo.Symbol.GetSymbol());
}
[WorkItem(551354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551354")]
[WorkItem(552759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552759")]
[Fact]
public void DotIntoTypeParameter2()
{
var source = @"
/// <see cref=""C{C}""/>
/// <see cref=""C.D{C}""/>
/// <see cref=""C.D.E{C}""/>
class C
{
class D
{
class E
{
}
}
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'C{C}' that could not be resolved
// /// <see cref="C{C}"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "C{C}").WithArguments("C{C}"),
// (2,16): warning CS1574: XML comment has cref attribute 'C.D{C}' that could not be resolved
// /// <see cref="C.D{C}"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "C.D{C}").WithArguments("D{C}"),
// (3,16): warning CS1574: XML comment has cref attribute 'C.D.E{C}' that could not be resolved
// /// <see cref="C.D.E{C}"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "C.D.E{C}").WithArguments("E{C}"));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var crefs = GetCrefSyntaxes(compilation).ToArray();
foreach (var cref in crefs)
{
var typeSyntax = cref.DescendantNodes().OfType<SimpleNameSyntax>().First();
var typeSymbol = model.GetSymbolInfo(typeSyntax).Symbol;
if (typeSyntax.Parent.Kind() == SyntaxKind.NameMemberCref)
{
Assert.Null(typeSymbol);
}
else
{
Assert.IsType<CrefTypeParameterSymbol>(typeSymbol.GetSymbol());
}
}
}
[WorkItem(549351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/549351")]
[WorkItem(675600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675600")]
[Fact]
public void OperatorGreaterThanGreaterThanEquals()
{
var source = @"
/// <see cref=""operator }}=""/>
class C { }
";
// Just don't blow up.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'operator }}='
// /// <see cref="operator }}="/>
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "operator").WithArguments("operator }}="),
// (2,24): warning CS1658: Overloadable operator expected. See also error CS1037.
// /// <see cref="operator }}="/>
Diagnostic(ErrorCode.WRN_ErrorOverride, " }}").WithArguments("Overloadable operator expected", "1037"));
}
[WorkItem(554077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554077")]
[Fact]
public void GenericDelegateConstructor()
{
var source = @"
using System;
/// <summary>
/// <see cref=""Action{T}.Action""/>
/// </summary>
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var delegateConstructor = compilation.GlobalNamespace.
GetMember<INamespaceSymbol>("System").GetMembers("Action").OfType<INamedTypeSymbol>().
Single(t => t.Arity == 1).
InstanceConstructors.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var symbol = model.GetSymbolInfo(cref).Symbol;
Assert.NotNull(symbol);
Assert.False(symbol.IsDefinition);
Assert.Equal(delegateConstructor, symbol.OriginalDefinition);
}
[WorkItem(553394, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553394")]
[Fact]
public void InaccessibleViaImports()
{
var source = @"
using System;
/// <see cref=""RuntimeType.Equals""/>
enum E { }
";
// Restore compat: include inaccessible members in cref lookup
var comp = CreateEmptyCompilation(
new[] { Parse(source, options: TestOptions.RegularWithDocumentationComments) },
new[] { MscorlibRef },
TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default));
comp.VerifyDiagnostics();
}
[WorkItem(554086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554086")]
[Fact]
public void InheritedInterfaceMember()
{
var source = @"
using System.Collections;
class GetEnumerator
{
/// <summary>
/// <see cref=""GetEnumerator""/>
/// </summary>
interface I : IEnumerable { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("GetEnumerator");
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void StringConstructor()
{
var source = @"
/// <summary>
/// <see cref=""string(char[])""/>
/// </summary>
enum E { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var expectedSymbol = compilation.GetSpecialType(SpecialType.System_String).
InstanceConstructors.Single(ctor => ctor.Parameters.Length == 1 && ctor.GetParameterType(0).Kind == SymbolKind.ArrayType);
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void InvalidStringConstructor()
{
var source = @"
/// <summary>
/// <see cref=""string(float[])""/>
/// </summary>
enum E { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,16): warning CS1574: XML comment has cref attribute 'string(float[])' that could not be resolved
// /// <see cref="string(float[])"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "string(float[])").WithArguments("string(float[])"));
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var info = model.GetSymbolInfo(cref);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void AliasQualifiedTypeConstructor()
{
var source = @"
/// <summary>
/// <see cref=""global::C()""/>
/// </summary>
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var expectedSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.Equal(expectedSymbol, actualSymbol);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void InvalidAliasQualifiedTypeConstructor()
{
var source = @"
/// <summary>
/// <see cref=""global::D()""/>
/// </summary>
class C { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,16): warning CS1574: XML comment has cref attribute 'global::D()' that could not be resolved
// /// <see cref="global::D()"/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "global::D()").WithArguments("global::D()"));
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var info = model.GetSymbolInfo(cref);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
}
[WorkItem(553609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553609")]
[Fact]
public void AliasQualifiedGenericTypeConstructor()
{
var source = @"
/// <summary>
/// <see cref=""global::C{Q}(Q)""/>
/// </summary>
class C<T>
{
C(T t) { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var expectedSymbolOriginalDefinition = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single();
var cref = GetCrefSyntaxes(compilation).Single();
var model = compilation.GetSemanticModel(cref.SyntaxTree);
var actualSymbol = model.GetSymbolInfo(cref).Symbol;
Assert.NotEqual(expectedSymbolOriginalDefinition, actualSymbol);
Assert.Equal(expectedSymbolOriginalDefinition, actualSymbol.OriginalDefinition);
}
[WorkItem(553592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553592")]
[Fact]
public void CrefTypeParameterMemberLookup1()
{
var source = @"
/// <see cref=""C{T}""/>
class C<U> { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var typeParameterSyntax = crefSyntax.DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("T", typeParameterSyntax.ToString());
var model = compilation.GetSemanticModel(typeParameterSyntax.SyntaxTree);
var typeParameterSymbol = model.GetSymbolInfo(typeParameterSyntax).Symbol;
Assert.IsType<CrefTypeParameterSymbol>(((CSharp.Symbols.PublicModel.Symbol)typeParameterSymbol).UnderlyingSymbol);
var members = model.LookupSymbols(typeParameterSyntax.SpanStart, (ITypeSymbol)typeParameterSymbol);
Assert.Equal(0, members.Length);
}
[WorkItem(553592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553592")]
[Fact]
public void CrefTypeParameterMemberLookup2()
{
var source = @"
/// <see cref=""System.Nullable{T}.GetValueOrDefault()""/>
enum E { }
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var methodNameSyntax = crefSyntax.DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("GetValueOrDefault", methodNameSyntax.ToString());
var model = compilation.GetSemanticModel(methodNameSyntax.SyntaxTree);
var methodSymbol = model.GetSymbolInfo(methodNameSyntax).Symbol;
Assert.Equal(SymbolKind.Method, methodSymbol.Kind);
var members = model.LookupSymbols(methodNameSyntax.SpanStart, ((IMethodSymbol)methodSymbol).ReturnType);
Assert.Equal(0, members.Length);
}
[WorkItem(598371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598371")]
[Fact]
public void CrefParameterOrReturnTypeLookup1()
{
var source = @"
class X
{
/// <summary>
/// <see cref=""Y.implicit operator Y.Y""/>
/// </summary>
public class Y : X
{
public static implicit operator Y(int x)
{
return null;
}
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var returnTypeSyntax = ((ConversionOperatorMemberCrefSyntax)(((QualifiedCrefSyntax)crefSyntax).Member)).Type;
var expectedReturnTypeSymbol = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("X").GetMember<INamedTypeSymbol>("Y");
var actualReturnTypeSymbol = model.GetSymbolInfo(returnTypeSyntax).Symbol;
Assert.Equal(expectedReturnTypeSymbol, actualReturnTypeSymbol);
var expectedCrefSymbol = expectedReturnTypeSymbol.GetMember<IMethodSymbol>(WellKnownMemberNames.ImplicitConversionName);
var actualCrefSymbol = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedCrefSymbol, actualCrefSymbol);
}
[WorkItem(586815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586815")]
[Fact]
public void CrefParameterOrReturnTypeLookup2()
{
var source = @"
class A<T>
{
class B : A<B>
{
/// <summary>
/// <see cref=""Goo(B)""/>
/// </summary>
void Goo(B x) { }
}
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var classA = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
var classB = classA.GetMember<INamedTypeSymbol>("B");
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var parameterTypeSyntax = ((NameMemberCrefSyntax)crefSyntax).Parameters.Parameters[0].Type;
var expectedParameterTypeSymbol = classA.Construct(classB).GetMember<INamedTypeSymbol>("B");
var actualParameterTypeSymbol = model.GetSymbolInfo(parameterTypeSyntax).Symbol;
Assert.Equal(expectedParameterTypeSymbol, actualParameterTypeSymbol);
var expectedCrefSymbol = classB.GetMember<IMethodSymbol>("Goo");
var actualCrefSymbol = model.GetSymbolInfo(crefSyntax).Symbol;
Assert.Equal(expectedCrefSymbol, actualCrefSymbol);
}
[WorkItem(743425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743425")]
[Fact]
public void NestedTypeInParameterList()
{
var source = @"
class Outer<T>
{
class Inner { }
/// <see cref='Outer{Q}.M(Inner)'/>
void M() { }
void M(Inner i) { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (6,31): warning CS8018: Within cref attributes, nested types of generic types should be qualified.
// /// <see cref='Outer{Q}.M(Inner)'/>
Diagnostic(ErrorCode.WRN_UnqualifiedNestedTypeInCref, "Inner"),
// (6,20): warning CS1574: XML comment has cref attribute 'Outer{Q}.M(Inner)' that could not be resolved
// /// <see cref='Outer{Q}.M(Inner)'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Outer{Q}.M(Inner)").WithArguments("M(Inner)"));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var outer = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Outer");
var inner = outer.GetMember<INamedTypeSymbol>("Inner");
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var parameterTypeSyntax = crefSyntax.DescendantNodes().OfType<CrefParameterSyntax>().Single().Type;
var parameterTypeSymbol = model.GetSymbolInfo(parameterTypeSyntax).Symbol;
Assert.True(parameterTypeSymbol.IsDefinition);
Assert.Equal(inner, parameterTypeSymbol);
}
[WorkItem(653402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653402")]
[Fact]
public void CrefAliasInfo_TopLevel()
{
var source = @"
using A = System.Int32;
/// <see cref=""A""/>
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var info = model.GetSymbolInfo(crefSyntax);
var alias = model.GetAliasInfo(crefSyntax.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().Single());
Assert.Equal(compilation.GetSpecialType(SpecialType.System_Int32), info.Symbol);
Assert.Equal(info.Symbol, alias.Target);
Assert.Equal("A", alias.Name);
}
[WorkItem(653402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653402")]
[Fact]
public void CrefAliasInfo_Parameter()
{
var source = @"
using A = System.Int32;
/// <see cref=""M(A)""/>
class C
{
void M(A a) { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var crefSyntax = GetCrefSyntaxes(compilation).Single();
var parameterSyntax = crefSyntax.
DescendantNodes().OfType<CrefParameterSyntax>().Single().
DescendantNodes().OfType<IdentifierNameSyntax>().Single();
var info = model.GetSymbolInfo(parameterSyntax);
var alias = model.GetAliasInfo(parameterSyntax);
Assert.Equal(compilation.GetSpecialType(SpecialType.System_Int32), info.Symbol);
Assert.Equal(info.Symbol, alias.Target);
Assert.Equal("A", alias.Name);
}
[Fact]
[WorkItem(760850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760850")]
public void TestGetSpeculativeSymbolInfoInsideCref()
{
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"
using System;
class P
{
Action<int> b = (int x) => { };
class B
{
/// <see cref=""b""/>
void a()
{
}
}
}
");
var tree = compilation.SyntaxTrees[0];
var cref = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var crefName = cref.Name;
var model = compilation.GetSemanticModel(tree);
var symbolInfo = model.GetSymbolInfo(crefName);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind);
Assert.Equal("System.Action<System.Int32> P.b", symbolInfo.Symbol.ToTestDisplayString());
var speculatedName = SyntaxFactory.ParseName("b");
symbolInfo = model.GetSpeculativeSymbolInfo(crefName.Position, speculatedName, SpeculativeBindingOption.BindAsExpression);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind);
Assert.Equal("System.Action<System.Int32> P.b", symbolInfo.Symbol.ToTestDisplayString());
SemanticModel speculativeModel;
var success = model.TryGetSpeculativeSemanticModel(crefName.Position, speculatedName, out speculativeModel);
Assert.True(success);
Assert.NotNull(speculativeModel);
symbolInfo = speculativeModel.GetSymbolInfo(speculatedName);
Assert.NotNull(symbolInfo.Symbol);
Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind);
Assert.Equal("System.Action<System.Int32> P.b", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact]
[WorkItem(760850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760850")]
public void TestGetSpeculativeSymbolInfoInsideCrefParameterOrReturnType()
{
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(@"
class Base
{
class Inherited { }
}
class Outer
{
class Inner : Base
{
int P { get; set; };
/// <see cref=""explicit operator Return(Param)""/>
void M()
{
}
}
}
");
var tree = compilation.SyntaxTrees.First();
var cref = (ConversionOperatorMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var crefReturnType = cref.Type;
var crefParameterType = cref.Parameters.Parameters.Single().Type;
var crefPosition = cref.SpanStart;
var crefReturnTypePosition = crefReturnType.SpanStart;
var crefParameterTypePosition = crefParameterType.SpanStart;
var nonCrefPosition = tree.GetRoot().DescendantTrivia().Single(t => t.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)).SpanStart;
var accessor = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Outer").GetMember<INamedTypeSymbol>("Inner").GetMember<IPropertySymbol>("P").GetMethod;
var inheritedType = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Base").GetMember<INamedTypeSymbol>("Inherited");
var model = compilation.GetSemanticModel(tree);
// Try a non-type. Should work in a cref, unless it's in a parameter or return type.
// Should not work outside a cref, because the accessor cannot be referenced by name.
var accessorName = SyntaxFactory.ParseName(accessor.Name);
var crefInfo = model.GetSpeculativeSymbolInfo(crefPosition, accessorName, SpeculativeBindingOption.BindAsExpression);
var returnInfo = model.GetSpeculativeSymbolInfo(crefReturnTypePosition, accessorName, SpeculativeBindingOption.BindAsExpression);
var paramInfo = model.GetSpeculativeSymbolInfo(crefParameterTypePosition, accessorName, SpeculativeBindingOption.BindAsExpression);
var nonCrefInfo = model.GetSpeculativeSymbolInfo(nonCrefPosition, accessorName, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(accessor, crefInfo.Symbol);
Assert.Equal(SymbolInfo.None, returnInfo);
Assert.Equal(SymbolInfo.None, paramInfo);
Assert.Equal(accessor, nonCrefInfo.CandidateSymbols.Single());
Assert.Equal(CandidateReason.NotReferencable, nonCrefInfo.CandidateReason);
// Try an inaccessible inherited types. Should work in a cref, but only if it's in a parameter or return type (since it's inherited).
// Should not work outside a cref, because it's inaccessible.
// NOTE: SpeculativeBindingOptions are ignored when the position is inside a cref.
var inheritedTypeName = SyntaxFactory.ParseName(inheritedType.Name);
crefInfo = model.GetSpeculativeSymbolInfo(crefPosition, inheritedTypeName, SpeculativeBindingOption.BindAsExpression);
returnInfo = model.GetSpeculativeSymbolInfo(crefReturnTypePosition, inheritedTypeName, SpeculativeBindingOption.BindAsExpression);
paramInfo = model.GetSpeculativeSymbolInfo(crefParameterTypePosition, inheritedTypeName, SpeculativeBindingOption.BindAsExpression);
nonCrefInfo = model.GetSpeculativeSymbolInfo(nonCrefPosition, inheritedTypeName, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, crefInfo);
Assert.Equal(inheritedType, returnInfo.Symbol);
Assert.Equal(inheritedType, paramInfo.Symbol);
Assert.Equal(inheritedType, nonCrefInfo.CandidateSymbols.Single());
Assert.Equal(CandidateReason.Inaccessible, nonCrefInfo.CandidateReason);
}
[WorkItem(768624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768624")]
[Fact]
public void CrefsOnDelegate()
{
var source = @"
/// <see cref='T'/>
/// <see cref='t'/>
/// <see cref='Invoke'/>
/// <see cref='ToString'/>
delegate void D< T > (T t);
";
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics(
// (2,16): warning CS1574: XML comment has cref attribute 'T' that could not be resolved
// /// <see cref='T'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "T").WithArguments("T"),
// (3,16): warning CS1574: XML comment has cref attribute 't' that could not be resolved
// /// <see cref='t'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "t").WithArguments("t"),
// (4,16): warning CS1574: XML comment has cref attribute 'Invoke' that could not be resolved
// /// <see cref='Invoke'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "Invoke").WithArguments("Invoke"),
// (5,16): warning CS1574: XML comment has cref attribute 'ToString' that could not be resolved
// /// <see cref='ToString'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "ToString").WithArguments("ToString"));
}
[WorkItem(924473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924473")]
[Fact]
public void InterfaceInheritedMembersInSemanticModelLookup()
{
var source = @"
interface IBase
{
int P { get; set; }
}
interface IDerived : IBase
{
}
/// <see cref='IDerived.P'/>
class C
{
}
";
var comp = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
// Not expected to bind, since we don't consider inherited members.
comp.VerifyDiagnostics(
// (11,16): warning CS1574: XML comment has cref attribute 'IDerived.P' that could not be resolved
// /// <see cref='IDerived.P'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "IDerived.P").WithArguments("P").WithLocation(11, 16));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = GetCrefSyntaxes(comp).Single();
// No info, since it doesn't bind.
var info = model.GetSymbolInfo(syntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
// No lookup results.
var derivedInterface = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("IDerived");
Assert.Equal(0, model.LookupSymbols(syntax.SpanStart, derivedInterface).Length);
}
[WorkItem(924473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924473")]
[Fact]
public void InterfaceObjectMembers()
{
var source = @"
interface I
{
}
/// <see cref='I.ToString'/>
class C
{
}
";
var comp = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
// Not expected to bind, since we don't consider inherited members.
comp.VerifyDiagnostics(
// (6,16): warning CS1574: XML comment has cref attribute 'I.ToString' that could not be resolved
// /// <see cref='I.ToString'/>
Diagnostic(ErrorCode.WRN_BadXMLRef, "I.ToString").WithArguments("ToString").WithLocation(6, 16));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = GetCrefSyntaxes(comp).Single();
// No info, since it doesn't bind.
var info = model.GetSymbolInfo(syntax);
Assert.Null(info.Symbol);
Assert.Equal(CandidateReason.None, info.CandidateReason);
Assert.Equal(0, info.CandidateSymbols.Length);
// No lookup results.
var symbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("I");
Assert.Equal(0, model.LookupSymbols(syntax.SpanStart, symbol).Length);
}
#region Dev10 bugs from KevinH
[Fact]
public void Dev10_461967()
{
// Can use anything we want as the name of the type parameter.
var source = @"
/// <see cref=""C{Blah}"" />
/// <see cref=""C{Blah}.Inner"" />
class C<T>
{
class Inner { }
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
Assert.Equal(2, crefs.Length);
var outer = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var inner = outer.GetMember<INamedTypeSymbol>("Inner");
Assert.Equal(outer, model.GetSymbolInfo(crefs[0]).Symbol.OriginalDefinition);
Assert.Equal(inner, model.GetSymbolInfo(crefs[1]).Symbol.OriginalDefinition);
}
[Fact]
public void Dev10_461974()
{
// Can't omit type parameters.
var source = @"
/// <see cref=""C"" />
/// <see cref=""C{}"" />
class C<T>
{
}
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (3,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'C{}'
// /// <see cref="C{}" />
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C{}").WithArguments("C{}").WithLocation(3, 16),
// (3,18): warning CS1658: Identifier expected. See also error CS1001.
// /// <see cref="C{}" />
Diagnostic(ErrorCode.WRN_ErrorOverride, "}").WithArguments("Identifier expected", "1001").WithLocation(3, 18),
// (2,16): warning CS1574: XML comment has cref attribute 'C' that could not be resolved
// /// <see cref="C" />
Diagnostic(ErrorCode.WRN_BadXMLRef, "C").WithArguments("C").WithLocation(2, 16));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var crefs = GetCrefSyntaxes(compilation).ToArray();
Assert.Equal(2, crefs.Length);
var actualSymbol0 = model.GetSymbolInfo(crefs[0]).Symbol;
Assert.Null(actualSymbol0);
var actualSymbol1 = model.GetSymbolInfo(crefs[1]).Symbol;
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), actualSymbol1.OriginalDefinition);
Assert.Equal(TypeKind.Error, ((INamedTypeSymbol)actualSymbol1).TypeArguments.Single().TypeKind);
}
[Fact]
public void Dev10_461986()
{
// Can't cref an array type.
var source = @"
/// <see cref=""C[]"" />
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'C[]'
// /// <see cref="C[]" />
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C").WithArguments("C[]"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
// Once the square brackets are skipped, binding works just fine.
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), model.GetSymbolInfo(cref).Symbol);
}
[Fact]
public void Dev10_461988()
{
// Can't cref a nullable type (unless you use the generic type syntax).
var source = @"
/// <see cref=""C?"" />
class C { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'C?'
// /// <see cref="C?" />
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "C").WithArguments("C?"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
// Once the question mark is skipped, binding works just fine.
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"), model.GetSymbolInfo(cref).Symbol);
}
[Fact]
public void Dev10_461990()
{
// Can't put a smiley face at the end of a cref.
// NOTE: if we had used a type named "C", this would have been accepted as a verbatim cref.
var source = @"
/// <see cref=""Cat:-)"" />
class Cat { }
";
var compilation = (Compilation)CreateCompilationWithMscorlib40AndDocumentationComments(source);
compilation.VerifyDiagnostics(
// (2,16): warning CS1584: XML comment has syntactically incorrect cref attribute 'Cat:-)'
// /// <see cref="Cat:-)" />
Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "Cat").WithArguments("Cat:-)"));
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = GetCrefSyntaxes(compilation).Single();
// Once the smiley is skipped, binding works just fine.
Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("Cat"), model.GetSymbolInfo(cref).Symbol);
}
#endregion Dev10 bugs from KevinH
private static IEnumerable<CrefSyntax> GetCrefSyntaxes(Compilation compilation) => GetCrefSyntaxes((CSharpCompilation)compilation);
private static IEnumerable<CrefSyntax> GetCrefSyntaxes(CSharpCompilation compilation)
{
return compilation.SyntaxTrees.SelectMany(tree =>
{
var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>();
return docComments.SelectMany(docComment => docComment.DescendantNodes().OfType<XmlCrefAttributeSyntax>().Select(attr => attr.Cref));
});
}
private static Symbol GetReferencedSymbol(CrefSyntax crefSyntax, CSharpCompilation compilation, params DiagnosticDescription[] expectedDiagnostics)
{
Symbol ambiguityWinner;
var references = GetReferencedSymbols(crefSyntax, compilation, out ambiguityWinner, expectedDiagnostics);
Assert.Null(ambiguityWinner);
Assert.InRange(references.Length, 0, 1); //Otherwise, call GetReferencedSymbols
return references.FirstOrDefault();
}
private static ImmutableArray<Symbol> GetReferencedSymbols(CrefSyntax crefSyntax, CSharpCompilation compilation, out Symbol ambiguityWinner, params DiagnosticDescription[] expectedDiagnostics)
{
var binderFactory = compilation.GetBinderFactory(crefSyntax.SyntaxTree);
var binder = binderFactory.GetBinder(crefSyntax);
DiagnosticBag diagnostics = DiagnosticBag.GetInstance();
var references = binder.BindCref(crefSyntax, out ambiguityWinner, diagnostics);
diagnostics.Verify(expectedDiagnostics);
diagnostics.Free();
return references;
}
private static ISymbol[] GetCrefOriginalDefinitions(SemanticModel model, IEnumerable<CrefSyntax> crefs)
{
return crefs.Select(syntax => model.GetSymbolInfo(syntax).Symbol).Select(symbol => (object)symbol == null ? null : symbol.OriginalDefinition).ToArray();
}
[Fact]
[WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")]
public void LookupOnCrefTypeParameter()
{
var source = @"
class Test
{
T F<T>()
{
}
/// <summary>
/// <see cref=""F{U}()""/>
/// </summary>
void S()
{ }
}
";
var compilation = CreateCompilationWithMscorlib40AndDocumentationComments(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var crefSyntax = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var name = ((GenericNameSyntax)crefSyntax.Name).TypeArgumentList.Arguments.Single();
Assert.Equal("U", name.ToString());
var typeParameter = (ITypeParameterSymbol)model.GetSymbolInfo(name).Symbol;
Assert.Empty(model.LookupSymbols(name.SpanStart, typeParameter, "GetAwaiter"));
}
[Fact]
[WorkItem(23957, "https://github.com/dotnet/roslyn/issues/23957")]
public void CRef_InParameter()
{
var source = @"
class Test
{
void M(in int x)
{
}
/// <summary>
/// <see cref=""M(in int)""/>
/// </summary>
void S()
{
}
}
";
var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments).VerifyDiagnostics();
var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single());
var cref = (NameMemberCrefSyntax)GetCrefSyntaxes(compilation).Single();
var parameter = cref.Parameters.Parameters.Single();
Assert.Equal(SyntaxKind.InKeyword, parameter.RefKindKeyword.Kind());
var parameterSymbol = ((IMethodSymbol)model.GetSymbolInfo(cref).Symbol).Parameters.Single();
Assert.Equal(RefKind.In, parameterSymbol.RefKind);
}
[Fact]
public void Cref_TupleType()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""ValueTuple{T,T}""/>.
/// </summary>
class C
{
}
";
var parseOptions = TestOptions.RegularWithDocumentationComments;
var options = TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default);
var compilation = CreateCompilation(source, parseOptions: parseOptions, options: options, targetFramework: TargetFramework.StandardAndCSharp);
var cMember = compilation.GetMember<NamedTypeSymbol>("C");
var xmlDocumentationString = cMember.GetDocumentationCommentXml();
var xml = System.Xml.Linq.XDocument.Parse(xmlDocumentationString);
var cref = xml.Descendants("see").Single().Attribute("cref").Value;
Assert.Equal("T:System.ValueTuple`2", cref);
}
[Fact]
public void Cref_TupleTypeField()
{
var source = @"
using System;
/// <summary>
/// See <see cref=""ValueTuple{Int32,Int32}.Item1""/>.
/// </summary>
class C
{
}
";
var parseOptions = TestOptions.RegularWithDocumentationComments;
var options = TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default);
var compilation = CreateCompilation(source, parseOptions: parseOptions, options: options, targetFramework: TargetFramework.StandardAndCSharp);
var cMember = compilation.GetMember<NamedTypeSymbol>("C");
var xmlDocumentationString = cMember.GetDocumentationCommentXml();
var xml = System.Xml.Linq.XDocument.Parse(xmlDocumentationString);
var cref = xml.Descendants("see").Single().Attribute("cref").Value;
Assert.Equal("F:System.ValueTuple`2.Item1", cref);
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
[WorkItem(50330, "https://github.com/dotnet/roslyn/issues/50330")]
public void OnRecord(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// See also <see cref=""RelativePathBase""/>.
/// See also <see cref=""InvalidCref""/>.
/// </summary>
record CacheContext(string RelativePathBase)" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (6,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(6, 25),
// (6,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(6, 25));
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
[WorkItem(50330, "https://github.com/dotnet/roslyn/issues/50330")]
public void OnRecordStruct(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// See also <see cref=""RelativePathBase""/>.
/// See also <see cref=""InvalidCref""/>.
/// </summary>
record struct CacheContext(string RelativePathBase)" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments.WithLanguageVersion(LanguageVersion.CSharp10), targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (6,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(6, 25),
// (6,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(6, 25));
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
[WorkItem(50330, "https://github.com/dotnet/roslyn/issues/50330")]
public void OnRecord_WithoutPrimaryCtor(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// See also <see cref=""InvalidCref""/>.
/// </summary>
record CacheContext" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (5,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(5, 25));
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
[WorkItem(50330, "https://github.com/dotnet/roslyn/issues/50330")]
public void OnRecordStruct_WithoutPrimaryCtor(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// See also <see cref=""InvalidCref""/>.
/// </summary>
record struct CacheContext" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments.WithLanguageVersion(LanguageVersion.CSharp10), targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (5,25): warning CS1574: XML comment has cref attribute 'InvalidCref' that could not be resolved
// /// See also <see cref="InvalidCref"/>.
Diagnostic(ErrorCode.WRN_BadXMLRef, "InvalidCref").WithArguments("InvalidCref").WithLocation(5, 25));
}
[Theory]
[InlineData(" { }")]
[InlineData(";")]
public void Record_TypeAndPropertyWithSameNameInScope(string terminator)
{
var source = @"using System;
/// <summary>
/// Something with a <see cref=""String""/> instance.
/// </summary>
record CacheContext(string String)" + terminator;
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (1,1): hidden CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1));
var model = comp.GetSemanticModel(comp.SyntaxTrees.Single());
var crefSyntaxes = GetCrefSyntaxes(comp);
var symbol = model.GetSymbolInfo(crefSyntaxes.Single()).Symbol;
Assert.Equal(SymbolKind.Property, symbol.Kind);
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/WithoutCSharpTargetsImported.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 ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CSharpProject</RootNamespace>
<AssemblyName>CSharpProject</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="CSharpClass.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<!-- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />-->
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</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 ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CSharpProject</RootNamespace>
<AssemblyName>CSharpProject</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="CSharpClass.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<!-- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />-->
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/Core/Portable/Operations/BinaryOperatorKind.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>
/// Kind of binary operator.
/// </summary>
public enum BinaryOperatorKind
{
/// <summary>
/// Represents unknown or error operator kind.
/// </summary>
None = 0x0,
/// <summary>
/// Represents the '+' operator.
/// </summary>
Add = 0x1,
/// <summary>
/// Represents the '-' operator.
/// </summary>
Subtract = 0x2,
/// <summary>
/// Represents the '*' operator.
/// </summary>
Multiply = 0x3,
/// <summary>
/// Represents the '/' operator.
/// </summary>
Divide = 0x4,
/// <summary>
/// Represents the VB '\' integer divide operator.
/// </summary>
IntegerDivide = 0x5,
/// <summary>
/// Represents the C# '%' operator and VB 'Mod' operator.
/// </summary>
Remainder = 0x6,
/// <summary>
/// Represents the VB '^' exponentiation operator.
/// </summary>
Power = 0x7,
/// <summary>
/// Represents the <![CDATA['<<']]> operator.
/// </summary>
LeftShift = 0x8,
/// <summary>
/// Represents the <![CDATA['>>']]> operator.
/// </summary>
RightShift = 0x9,
/// <summary>
/// Represents the C# <![CDATA['&']]> operator and VB 'And' operator.
/// </summary>
And = 0xa,
/// <summary>
/// Represents the C# <![CDATA['|']]> operator and VB 'Or' operator.
/// </summary>
Or = 0xb,
/// <summary>
/// Represents the C# '^' operator and VB 'Xor' operator.
/// </summary>
ExclusiveOr = 0xc,
/// <summary>
/// Represents the C# <![CDATA['&&']]> operator and VB 'AndAlso' operator.
/// </summary>
ConditionalAnd = 0xd,
/// <summary>
/// Represents the C# <![CDATA['||']]> operator and VB 'OrElse' operator.
/// </summary>
ConditionalOr = 0xe,
/// <summary>
/// Represents the VB <![CDATA['&']]> operator for string concatenation.
/// </summary>
Concatenate = 0xf,
// Relational operations.
/// <summary>
/// Represents the C# '==' operator and VB 'Is' operator and '=' operator for non-object typed operands.
/// </summary>
Equals = 0x10,
/// <summary>
/// Represents the VB '=' operator for object typed operands.
/// </summary>
ObjectValueEquals = 0x11,
/// <summary>
/// Represents the C# '!=' operator and VB 'IsNot' operator and <![CDATA['<>']]> operator for non-object typed operands.
/// </summary>
NotEquals = 0x12,
/// <summary>
/// Represents the VB <![CDATA['<>']]> operator for object typed operands.
/// </summary>
ObjectValueNotEquals = 0x13,
/// <summary>
/// Represents the <![CDATA['<']]> operator.
/// </summary>
LessThan = 0x14,
/// <summary>
/// Represents the <![CDATA['<=']]> operator.
/// </summary>
LessThanOrEqual = 0x15,
/// <summary>
/// Represents the <![CDATA['>=']]> operator.
/// </summary>
GreaterThanOrEqual = 0x16,
/// <summary>
/// Represents the <![CDATA['>']]> operator.
/// </summary>
GreaterThan = 0x17,
/// <summary>
/// Represents the VB 'Like' operator.
/// </summary>
Like = 0x18
}
}
| // Licensed to the .NET Foundation under one or more 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>
/// Kind of binary operator.
/// </summary>
public enum BinaryOperatorKind
{
/// <summary>
/// Represents unknown or error operator kind.
/// </summary>
None = 0x0,
/// <summary>
/// Represents the '+' operator.
/// </summary>
Add = 0x1,
/// <summary>
/// Represents the '-' operator.
/// </summary>
Subtract = 0x2,
/// <summary>
/// Represents the '*' operator.
/// </summary>
Multiply = 0x3,
/// <summary>
/// Represents the '/' operator.
/// </summary>
Divide = 0x4,
/// <summary>
/// Represents the VB '\' integer divide operator.
/// </summary>
IntegerDivide = 0x5,
/// <summary>
/// Represents the C# '%' operator and VB 'Mod' operator.
/// </summary>
Remainder = 0x6,
/// <summary>
/// Represents the VB '^' exponentiation operator.
/// </summary>
Power = 0x7,
/// <summary>
/// Represents the <![CDATA['<<']]> operator.
/// </summary>
LeftShift = 0x8,
/// <summary>
/// Represents the <![CDATA['>>']]> operator.
/// </summary>
RightShift = 0x9,
/// <summary>
/// Represents the C# <![CDATA['&']]> operator and VB 'And' operator.
/// </summary>
And = 0xa,
/// <summary>
/// Represents the C# <![CDATA['|']]> operator and VB 'Or' operator.
/// </summary>
Or = 0xb,
/// <summary>
/// Represents the C# '^' operator and VB 'Xor' operator.
/// </summary>
ExclusiveOr = 0xc,
/// <summary>
/// Represents the C# <![CDATA['&&']]> operator and VB 'AndAlso' operator.
/// </summary>
ConditionalAnd = 0xd,
/// <summary>
/// Represents the C# <![CDATA['||']]> operator and VB 'OrElse' operator.
/// </summary>
ConditionalOr = 0xe,
/// <summary>
/// Represents the VB <![CDATA['&']]> operator for string concatenation.
/// </summary>
Concatenate = 0xf,
// Relational operations.
/// <summary>
/// Represents the C# '==' operator and VB 'Is' operator and '=' operator for non-object typed operands.
/// </summary>
Equals = 0x10,
/// <summary>
/// Represents the VB '=' operator for object typed operands.
/// </summary>
ObjectValueEquals = 0x11,
/// <summary>
/// Represents the C# '!=' operator and VB 'IsNot' operator and <![CDATA['<>']]> operator for non-object typed operands.
/// </summary>
NotEquals = 0x12,
/// <summary>
/// Represents the VB <![CDATA['<>']]> operator for object typed operands.
/// </summary>
ObjectValueNotEquals = 0x13,
/// <summary>
/// Represents the <![CDATA['<']]> operator.
/// </summary>
LessThan = 0x14,
/// <summary>
/// Represents the <![CDATA['<=']]> operator.
/// </summary>
LessThanOrEqual = 0x15,
/// <summary>
/// Represents the <![CDATA['>=']]> operator.
/// </summary>
GreaterThanOrEqual = 0x16,
/// <summary>
/// Represents the <![CDATA['>']]> operator.
/// </summary>
GreaterThan = 0x17,
/// <summary>
/// Represents the VB 'Like' operator.
/// </summary>
Like = 0x18
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/Core/Def/Implementation/CallHierarchy/CallHierarchyPresenter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.CallHierarchy.Package.Definitions;
using Microsoft.VisualStudio.Language.CallHierarchy;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CallHierarchy
{
[Export(typeof(ICallHierarchyPresenter))]
internal class CallHierarchyPresenter : ICallHierarchyPresenter
{
private readonly IServiceProvider _serviceProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CallHierarchyPresenter(SVsServiceProvider serviceProvider)
=> _serviceProvider = (IServiceProvider)serviceProvider;
public void PresentRoot(CallHierarchyItem root)
{
var callHierarchy = _serviceProvider.GetService(typeof(SCallHierarchy)) as ICallHierarchy;
callHierarchy.ShowToolWindow();
callHierarchy.AddRootItem((ICallHierarchyMemberItem)root);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.CallHierarchy.Package.Definitions;
using Microsoft.VisualStudio.Language.CallHierarchy;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CallHierarchy
{
[Export(typeof(ICallHierarchyPresenter))]
internal class CallHierarchyPresenter : ICallHierarchyPresenter
{
private readonly IServiceProvider _serviceProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CallHierarchyPresenter(SVsServiceProvider serviceProvider)
=> _serviceProvider = (IServiceProvider)serviceProvider;
public void PresentRoot(CallHierarchyItem root)
{
var callHierarchy = _serviceProvider.GetService(typeof(SCallHierarchy)) as ICallHierarchy;
callHierarchy.ShowToolWindow();
callHierarchy.AddRootItem((ICallHierarchyMemberItem)root);
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/Core/Def/Implementation/GenerateType/GenerateTypeDialog.xaml.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.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType
{
/// <summary>
/// Interaction logic for GenerateTypeDialog.xaml
/// </summary>
internal partial class GenerateTypeDialog : DialogWindow
{
private readonly GenerateTypeDialogViewModel _viewModel;
// Expose localized strings for binding
public string GenerateTypeDialogTitle { get { return ServicesVSResources.Generate_Type; } }
public string TypeDetails { get { return ServicesVSResources.Type_Details_colon; } }
public string Access { get { return ServicesVSResources.Access_colon; } }
public string Kind { get { return ServicesVSResources.Kind_colon; } }
public string NameLabel { get { return ServicesVSResources.Name_colon1; } }
public string Location { get { return ServicesVSResources.Location_colon; } }
public string Project { get { return ServicesVSResources.Project_colon; } }
public string FileName { get { return ServicesVSResources.File_Name_colon; } }
public string CreateNewFile { get { return ServicesVSResources.Create_new_file; } }
public string AddToExistingFile { get { return ServicesVSResources.Add_to_existing_file; } }
public string OK { get { return ServicesVSResources.OK; } }
public string Cancel { get { return ServicesVSResources.Cancel; } }
public GenerateTypeDialog(GenerateTypeDialogViewModel viewModel)
: base("vsl.GenerateFromUsage")
{
_viewModel = viewModel;
SetCommandBindings();
InitializeComponent();
DataContext = viewModel;
}
private void SetCommandBindings()
{
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectAccessKind",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.A, ModifierKeys.Alt) })),
Select_Access_Kind));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectTypeKind",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.K, ModifierKeys.Alt) })),
Select_Type_Kind));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectProject",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.P, ModifierKeys.Alt) })),
Select_Project));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"CreateNewFile",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.C, ModifierKeys.Alt) })),
Create_New_File));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"AddToExistingFile",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.X, ModifierKeys.Alt) })),
Add_To_Existing_File));
}
private void Select_Access_Kind(object sender, RoutedEventArgs e)
=> accessListComboBox.Focus();
private void Select_Type_Kind(object sender, RoutedEventArgs e)
=> kindListComboBox.Focus();
private void Select_Project(object sender, RoutedEventArgs e)
=> projectListComboBox.Focus();
private void Create_New_File(object sender, RoutedEventArgs e)
=> createNewFileRadioButton.Focus();
private void Add_To_Existing_File(object sender, RoutedEventArgs e)
=> addToExistingFileRadioButton.Focus();
private void FileNameTextBox_LostFocus(object sender, RoutedEventArgs e)
=> _viewModel.UpdateFileNameExtension();
private void OK_Click(object sender, RoutedEventArgs e)
{
_viewModel.UpdateFileNameExtension();
if (_viewModel.TrySubmit())
{
DialogResult = true;
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly GenerateTypeDialog _dialog;
public TestAccessor(GenerateTypeDialog dialog)
=> _dialog = dialog;
public Button OKButton => _dialog.OKButton;
public Button CancelButton => _dialog.CancelButton;
public ComboBox AccessListComboBox => _dialog.accessListComboBox;
public ComboBox KindListComboBox => _dialog.kindListComboBox;
public TextBox TypeNameTextBox => _dialog.TypeNameTextBox;
public ComboBox ProjectListComboBox => _dialog.projectListComboBox;
public RadioButton AddToExistingFileRadioButton => _dialog.addToExistingFileRadioButton;
public ComboBox AddToExistingFileComboBox => _dialog.AddToExistingFileComboBox;
public RadioButton CreateNewFileRadioButton => _dialog.createNewFileRadioButton;
public ComboBox CreateNewFileComboBox => _dialog.CreateNewFileComboBox;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType
{
/// <summary>
/// Interaction logic for GenerateTypeDialog.xaml
/// </summary>
internal partial class GenerateTypeDialog : DialogWindow
{
private readonly GenerateTypeDialogViewModel _viewModel;
// Expose localized strings for binding
public string GenerateTypeDialogTitle { get { return ServicesVSResources.Generate_Type; } }
public string TypeDetails { get { return ServicesVSResources.Type_Details_colon; } }
public string Access { get { return ServicesVSResources.Access_colon; } }
public string Kind { get { return ServicesVSResources.Kind_colon; } }
public string NameLabel { get { return ServicesVSResources.Name_colon1; } }
public string Location { get { return ServicesVSResources.Location_colon; } }
public string Project { get { return ServicesVSResources.Project_colon; } }
public string FileName { get { return ServicesVSResources.File_Name_colon; } }
public string CreateNewFile { get { return ServicesVSResources.Create_new_file; } }
public string AddToExistingFile { get { return ServicesVSResources.Add_to_existing_file; } }
public string OK { get { return ServicesVSResources.OK; } }
public string Cancel { get { return ServicesVSResources.Cancel; } }
public GenerateTypeDialog(GenerateTypeDialogViewModel viewModel)
: base("vsl.GenerateFromUsage")
{
_viewModel = viewModel;
SetCommandBindings();
InitializeComponent();
DataContext = viewModel;
}
private void SetCommandBindings()
{
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectAccessKind",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.A, ModifierKeys.Alt) })),
Select_Access_Kind));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectTypeKind",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.K, ModifierKeys.Alt) })),
Select_Type_Kind));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectProject",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.P, ModifierKeys.Alt) })),
Select_Project));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"CreateNewFile",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.C, ModifierKeys.Alt) })),
Create_New_File));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"AddToExistingFile",
typeof(GenerateTypeDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.X, ModifierKeys.Alt) })),
Add_To_Existing_File));
}
private void Select_Access_Kind(object sender, RoutedEventArgs e)
=> accessListComboBox.Focus();
private void Select_Type_Kind(object sender, RoutedEventArgs e)
=> kindListComboBox.Focus();
private void Select_Project(object sender, RoutedEventArgs e)
=> projectListComboBox.Focus();
private void Create_New_File(object sender, RoutedEventArgs e)
=> createNewFileRadioButton.Focus();
private void Add_To_Existing_File(object sender, RoutedEventArgs e)
=> addToExistingFileRadioButton.Focus();
private void FileNameTextBox_LostFocus(object sender, RoutedEventArgs e)
=> _viewModel.UpdateFileNameExtension();
private void OK_Click(object sender, RoutedEventArgs e)
{
_viewModel.UpdateFileNameExtension();
if (_viewModel.TrySubmit())
{
DialogResult = true;
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly GenerateTypeDialog _dialog;
public TestAccessor(GenerateTypeDialog dialog)
=> _dialog = dialog;
public Button OKButton => _dialog.OKButton;
public Button CancelButton => _dialog.CancelButton;
public ComboBox AccessListComboBox => _dialog.accessListComboBox;
public ComboBox KindListComboBox => _dialog.kindListComboBox;
public TextBox TypeNameTextBox => _dialog.TypeNameTextBox;
public ComboBox ProjectListComboBox => _dialog.projectListComboBox;
public RadioButton AddToExistingFileRadioButton => _dialog.addToExistingFileRadioButton;
public ComboBox AddToExistingFileComboBox => _dialog.AddToExistingFileComboBox;
public RadioButton CreateNewFileRadioButton => _dialog.createNewFileRadioButton;
public ComboBox CreateNewFileComboBox => _dialog.CreateNewFileComboBox;
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/EditorFeatures/Core.Wpf/NavigateTo/DefaultNavigateToPreviewService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
internal sealed class DefaultNavigateToPreviewService : INavigateToPreviewService
{
public int GetProvisionalViewingStatus(Document document)
=> 0;
public bool CanPreview(Document document)
=> true;
public void PreviewItem(INavigateToItemDisplay itemDisplay)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
internal sealed class DefaultNavigateToPreviewService : INavigateToPreviewService
{
public int GetProvisionalViewingStatus(Document document)
=> 0;
public bool CanPreview(Document document)
=> true;
public void PreviewItem(INavigateToItemDisplay itemDisplay)
{
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/Test/Utilities/CSharp/LocalVariableDeclaratorsCollector.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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
internal sealed class LocalVariableDeclaratorsCollector : CSharpSyntaxWalker
{
private readonly ArrayBuilder<SyntaxNode> _builder;
private LocalVariableDeclaratorsCollector(ArrayBuilder<SyntaxNode> builder)
{
_builder = builder;
}
internal static ImmutableArray<SyntaxNode> GetDeclarators(SourceMemberMethodSymbol method)
{
var builder = ArrayBuilder<SyntaxNode>.GetInstance();
var visitor = new LocalVariableDeclaratorsCollector(builder);
var bodies = method.Bodies;
visitor.Visit(bodies.Item1 ?? (SyntaxNode)bodies.Item2);
return builder.ToImmutableAndFree();
}
public sealed override void VisitForEachStatement(ForEachStatementSyntax node)
{
_builder.Add(node);
base.VisitForEachStatement(node);
}
public sealed override void VisitLockStatement(LockStatementSyntax node)
{
_builder.Add(node);
base.VisitLockStatement(node);
}
public sealed override void VisitUsingStatement(UsingStatementSyntax node)
{
if (node.Expression != null)
{
_builder.Add(node);
}
base.VisitUsingStatement(node);
}
public override void VisitSwitchStatement(SwitchStatementSyntax node)
{
_builder.Add(node);
base.VisitSwitchStatement(node);
}
public override void VisitIfStatement(IfStatementSyntax node)
{
_builder.Add(node);
base.VisitIfStatement(node);
}
public override void VisitWhileStatement(WhileStatementSyntax node)
{
_builder.Add(node);
base.VisitWhileStatement(node);
}
public override void VisitDoStatement(DoStatementSyntax node)
{
_builder.Add(node);
base.VisitDoStatement(node);
}
public override void VisitForStatement(ForStatementSyntax node)
{
if (node.Condition != null)
{
_builder.Add(node);
}
base.VisitForStatement(node);
}
public override void VisitVariableDeclarator(VariableDeclaratorSyntax node)
{
_builder.Add(node);
base.VisitVariableDeclarator(node);
}
public override void VisitSingleVariableDesignation(SingleVariableDesignationSyntax node)
{
_builder.Add(node);
base.VisitSingleVariableDesignation(node);
}
public override void VisitCatchDeclaration(CatchDeclarationSyntax node)
{
_builder.Add(node);
base.VisitCatchDeclaration(node);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
internal sealed class LocalVariableDeclaratorsCollector : CSharpSyntaxWalker
{
private readonly ArrayBuilder<SyntaxNode> _builder;
private LocalVariableDeclaratorsCollector(ArrayBuilder<SyntaxNode> builder)
{
_builder = builder;
}
internal static ImmutableArray<SyntaxNode> GetDeclarators(SourceMemberMethodSymbol method)
{
var builder = ArrayBuilder<SyntaxNode>.GetInstance();
var visitor = new LocalVariableDeclaratorsCollector(builder);
var bodies = method.Bodies;
visitor.Visit(bodies.Item1 ?? (SyntaxNode)bodies.Item2);
return builder.ToImmutableAndFree();
}
public sealed override void VisitForEachStatement(ForEachStatementSyntax node)
{
_builder.Add(node);
base.VisitForEachStatement(node);
}
public sealed override void VisitLockStatement(LockStatementSyntax node)
{
_builder.Add(node);
base.VisitLockStatement(node);
}
public sealed override void VisitUsingStatement(UsingStatementSyntax node)
{
if (node.Expression != null)
{
_builder.Add(node);
}
base.VisitUsingStatement(node);
}
public override void VisitSwitchStatement(SwitchStatementSyntax node)
{
_builder.Add(node);
base.VisitSwitchStatement(node);
}
public override void VisitIfStatement(IfStatementSyntax node)
{
_builder.Add(node);
base.VisitIfStatement(node);
}
public override void VisitWhileStatement(WhileStatementSyntax node)
{
_builder.Add(node);
base.VisitWhileStatement(node);
}
public override void VisitDoStatement(DoStatementSyntax node)
{
_builder.Add(node);
base.VisitDoStatement(node);
}
public override void VisitForStatement(ForStatementSyntax node)
{
if (node.Condition != null)
{
_builder.Add(node);
}
base.VisitForStatement(node);
}
public override void VisitVariableDeclarator(VariableDeclaratorSyntax node)
{
_builder.Add(node);
base.VisitVariableDeclarator(node);
}
public override void VisitSingleVariableDesignation(SingleVariableDesignationSyntax node)
{
_builder.Add(node);
base.VisitSingleVariableDesignation(node);
}
public override void VisitCatchDeclaration(CatchDeclarationSyntax node)
{
_builder.Add(node);
base.VisitCatchDeclaration(node);
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/VisualBasic/Portable/Symbols/ErrorTypeSymbol.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 System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Class ErrorTypeSymbol
Inherits NamedTypeSymbol
Implements IErrorTypeSymbol
Friend Shared ReadOnly UnknownResultType As ErrorTypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' Returns information about the reason that this type is in error.
''' </summary>
Friend Overridable ReadOnly Property ErrorInfo As DiagnosticInfo
Get
Return Nothing
End Get
End Property
Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol)
If Me.IsDefinition Then
Return New UseSiteInfo(Of AssemblySymbol)(Me.ErrorInfo)
End If
' Base class handles constructed types.
Return MyBase.GetUseSiteInfo()
End Function
Friend Overrides Function GetUnificationUseSiteDiagnosticRecursive(owner As Symbol, ByRef checkedTypes As HashSet(Of TypeSymbol)) As DiagnosticInfo
Return Nothing
End Function
Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol
Return Nothing
End Function
Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol
Return Nothing
End Function
Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides ReadOnly Property IsReferenceType As Boolean
Get
' TODO: Consider returning False.
Return True
End Get
End Property
Public Overrides ReadOnly Property IsValueType As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String)
Get
Return SpecializedCollections.EmptyEnumerable(Of String)()
End Get
End Property
Public Overrides Function GetMembers() As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol)
Return SpecializedCollections.EmptyEnumerable(Of FieldSymbol)()
End Function
Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.ErrorType
End Get
End Property
Public NotOverridable Overrides ReadOnly Property TypeKind As TypeKind
Get
Return TypeKind.Error
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property IsInterface As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return String.Empty
End Get
End Property
Friend Overrides ReadOnly Property MangleName As Boolean
Get
Debug.Assert(Arity = 0)
Return False
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsSerializable As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property Layout As TypeLayout
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property MarshallingCharSet As CharSet
Get
Return DefaultMarshallingCharSet
End Get
End Property
Friend Overrides ReadOnly Property TypeArgumentsNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol)
Get
Return ImmutableArray(Of TypeSymbol).Empty
End Get
End Property
Friend Overrides ReadOnly Property HasTypeArgumentsCustomModifiers As Boolean
Get
Return False
End Get
End Property
Public Overrides Function GetTypeArgumentCustomModifiers(ordinal As Integer) As ImmutableArray(Of CustomModifier)
Return GetEmptyTypeArgumentCustomModifiers(ordinal)
End Function
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property ConstructedFrom As NamedTypeSymbol
Get
Return Me
End Get
End Property
Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Return visitor.VisitErrorType(Me, arg)
End Function
' Only compiler creates an error symbol.
Friend Sub New()
End Sub
Public NotOverridable Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Public
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsMustInherit As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsNotInheritable As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsComImport As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property CoClassType As TypeSymbol
Get
Return Nothing
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
''' <summary>
''' Substitute the given type substitution within this type, returning a new type. If the
''' substitution had no effect, return Me.
''' !!! Only code implementing construction of generic types is allowed to call this method !!!
''' !!! All other code should use Construct methods. !!!
''' </summary>
Friend Overrides Function InternalSubstituteTypeParameters(substitution As TypeSubstitution) As TypeWithModifiers
Return New TypeWithModifiers(Me)
End Function
Friend Overrides ReadOnly Property TypeSubstitution As TypeSubstitution
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property CanConstruct As Boolean
Get
Return False
End Get
End Property
Public Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As NamedTypeSymbol
' An error symbol has no type parameters, so construction isn't allowed.
' TDOD: Remove temporary workaround from constructor of ArrayTypeSymbol.
Throw New InvalidOperationException()
End Function
Friend Overrides ReadOnly Property DefaultPropertyName As String
Get
Return Nothing
End Get
End Property
''' <summary>
''' If we believe we know which symbol the user intended, then we should retain that information
''' in the corresponding error symbol - it can be useful for deciding how to handle the error.
''' </summary>
Friend ReadOnly Property NonErrorGuessType As NamedTypeSymbol
Get
Dim candidates = Me.CandidateSymbols
If candidates.Length = 1 Then ' Only return a guess if its unambiguous.
Return TryCast(candidates(0), NamedTypeSymbol)
Else
Return Nothing
End If
End Get
End Property
''' <summary>
''' Return why the candidate symbols were bad.
''' </summary>
Friend Overridable ReadOnly Property ResultKind As LookupResultKind
Get
Return LookupResultKind.Empty
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
''' <summary>
''' When constructing this ErrorTypeSymbol, there may have been symbols that seemed to
''' be what the user intended, but were unsuitable. For example, a type might have been
''' inaccessible, or ambiguous. This property returns the possible symbols that the user
''' might have intended. It will return no symbols if no possible symbols were found.
''' See the CandidateReason property to understand why the symbols were unsuitable.
''' </summary>
Public Overridable ReadOnly Property CandidateSymbols As ImmutableArray(Of Symbol)
Get
Return ImmutableArray(Of Symbol).Empty
End Get
End Property
Public ReadOnly Property CandidateReason As CandidateReason Implements IErrorTypeSymbol.CandidateReason
Get
If CandidateSymbols.IsEmpty Then
Return Microsoft.CodeAnalysis.CandidateReason.None
Else
Debug.Assert(ResultKind <> LookupResultKind.Good, "Shouldn't have good result kind on error symbol")
Return ResultKind.ToCandidateReason()
End If
End Get
End Property
Public Overrides Function Equals(obj As TypeSymbol, comparison As TypeCompareKind) As Boolean
Return Me Is obj
End Function
Public Overrides Function GetHashCode() As Integer
Return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(Me)
End Function
''' <summary>
''' Force all declaration errors to be generated.
''' </summary>
Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken)
Throw ExceptionUtilities.Unreachable
End Sub
Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol)
Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)()
End Function
#Region "IErrorTypeSymbol members"
Public ReadOnly Property IErrorTypeSymbol_CandidateSymbols As ImmutableArray(Of ISymbol) Implements IErrorTypeSymbol.CandidateSymbols
Get
Return StaticCast(Of ISymbol).From(Me.CandidateSymbols)
End Get
End Property
#End Region
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 System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Class ErrorTypeSymbol
Inherits NamedTypeSymbol
Implements IErrorTypeSymbol
Friend Shared ReadOnly UnknownResultType As ErrorTypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' Returns information about the reason that this type is in error.
''' </summary>
Friend Overridable ReadOnly Property ErrorInfo As DiagnosticInfo
Get
Return Nothing
End Get
End Property
Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol)
If Me.IsDefinition Then
Return New UseSiteInfo(Of AssemblySymbol)(Me.ErrorInfo)
End If
' Base class handles constructed types.
Return MyBase.GetUseSiteInfo()
End Function
Friend Overrides Function GetUnificationUseSiteDiagnosticRecursive(owner As Symbol, ByRef checkedTypes As HashSet(Of TypeSymbol)) As DiagnosticInfo
Return Nothing
End Function
Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol
Return Nothing
End Function
Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol
Return Nothing
End Function
Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides ReadOnly Property IsReferenceType As Boolean
Get
' TODO: Consider returning False.
Return True
End Get
End Property
Public Overrides ReadOnly Property IsValueType As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String)
Get
Return SpecializedCollections.EmptyEnumerable(Of String)()
End Get
End Property
Public Overrides Function GetMembers() As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol)
Return SpecializedCollections.EmptyEnumerable(Of FieldSymbol)()
End Function
Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.ErrorType
End Get
End Property
Public NotOverridable Overrides ReadOnly Property TypeKind As TypeKind
Get
Return TypeKind.Error
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property IsInterface As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return String.Empty
End Get
End Property
Friend Overrides ReadOnly Property MangleName As Boolean
Get
Debug.Assert(Arity = 0)
Return False
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsSerializable As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property Layout As TypeLayout
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property MarshallingCharSet As CharSet
Get
Return DefaultMarshallingCharSet
End Get
End Property
Friend Overrides ReadOnly Property TypeArgumentsNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol)
Get
Return ImmutableArray(Of TypeSymbol).Empty
End Get
End Property
Friend Overrides ReadOnly Property HasTypeArgumentsCustomModifiers As Boolean
Get
Return False
End Get
End Property
Public Overrides Function GetTypeArgumentCustomModifiers(ordinal As Integer) As ImmutableArray(Of CustomModifier)
Return GetEmptyTypeArgumentCustomModifiers(ordinal)
End Function
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property ConstructedFrom As NamedTypeSymbol
Get
Return Me
End Get
End Property
Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Return visitor.VisitErrorType(Me, arg)
End Function
' Only compiler creates an error symbol.
Friend Sub New()
End Sub
Public NotOverridable Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Public
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsMustInherit As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property IsNotInheritable As Boolean
Get
Return False
End Get
End Property
Public NotOverridable Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property IsComImport As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property CoClassType As TypeSymbol
Get
Return Nothing
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
''' <summary>
''' Substitute the given type substitution within this type, returning a new type. If the
''' substitution had no effect, return Me.
''' !!! Only code implementing construction of generic types is allowed to call this method !!!
''' !!! All other code should use Construct methods. !!!
''' </summary>
Friend Overrides Function InternalSubstituteTypeParameters(substitution As TypeSubstitution) As TypeWithModifiers
Return New TypeWithModifiers(Me)
End Function
Friend Overrides ReadOnly Property TypeSubstitution As TypeSubstitution
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property CanConstruct As Boolean
Get
Return False
End Get
End Property
Public Overrides Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As NamedTypeSymbol
' An error symbol has no type parameters, so construction isn't allowed.
' TDOD: Remove temporary workaround from constructor of ArrayTypeSymbol.
Throw New InvalidOperationException()
End Function
Friend Overrides ReadOnly Property DefaultPropertyName As String
Get
Return Nothing
End Get
End Property
''' <summary>
''' If we believe we know which symbol the user intended, then we should retain that information
''' in the corresponding error symbol - it can be useful for deciding how to handle the error.
''' </summary>
Friend ReadOnly Property NonErrorGuessType As NamedTypeSymbol
Get
Dim candidates = Me.CandidateSymbols
If candidates.Length = 1 Then ' Only return a guess if its unambiguous.
Return TryCast(candidates(0), NamedTypeSymbol)
Else
Return Nothing
End If
End Get
End Property
''' <summary>
''' Return why the candidate symbols were bad.
''' </summary>
Friend Overridable ReadOnly Property ResultKind As LookupResultKind
Get
Return LookupResultKind.Empty
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
''' <summary>
''' When constructing this ErrorTypeSymbol, there may have been symbols that seemed to
''' be what the user intended, but were unsuitable. For example, a type might have been
''' inaccessible, or ambiguous. This property returns the possible symbols that the user
''' might have intended. It will return no symbols if no possible symbols were found.
''' See the CandidateReason property to understand why the symbols were unsuitable.
''' </summary>
Public Overridable ReadOnly Property CandidateSymbols As ImmutableArray(Of Symbol)
Get
Return ImmutableArray(Of Symbol).Empty
End Get
End Property
Public ReadOnly Property CandidateReason As CandidateReason Implements IErrorTypeSymbol.CandidateReason
Get
If CandidateSymbols.IsEmpty Then
Return Microsoft.CodeAnalysis.CandidateReason.None
Else
Debug.Assert(ResultKind <> LookupResultKind.Good, "Shouldn't have good result kind on error symbol")
Return ResultKind.ToCandidateReason()
End If
End Get
End Property
Public Overrides Function Equals(obj As TypeSymbol, comparison As TypeCompareKind) As Boolean
Return Me Is obj
End Function
Public Overrides Function GetHashCode() As Integer
Return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(Me)
End Function
''' <summary>
''' Force all declaration errors to be generated.
''' </summary>
Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken)
Throw ExceptionUtilities.Unreachable
End Sub
Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol)
Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)()
End Function
#Region "IErrorTypeSymbol members"
Public ReadOnly Property IErrorTypeSymbol_CandidateSymbols As ImmutableArray(Of ISymbol) Implements IErrorTypeSymbol.CandidateSymbols
Get
Return StaticCast(Of ISymbol).From(Me.CandidateSymbols)
End Get
End Property
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/VisualStudio/Core/Impl/CodeModel/ExternalElements/ExternalCodeClass.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE.CodeClass))]
public sealed class ExternalCodeClass : AbstractExternalCodeType, EnvDTE80.CodeClass2, EnvDTE.CodeClass, EnvDTE.CodeType, EnvDTE.CodeElement, EnvDTE80.CodeElement2
{
internal static EnvDTE.CodeClass Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
{
var newElement = new ExternalCodeClass(state, projectId, typeSymbol);
return (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(newElement);
}
private ExternalCodeClass(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
: base(state, projectId, typeSymbol)
{
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementClass; }
}
public EnvDTE80.vsCMClassKind ClassKind
{
get
{
return EnvDTE80.vsCMClassKind.vsCMClassKindMainClass;
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE80.vsCMDataTypeKind DataTypeKind
{
get
{
return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain;
}
set
{
throw Exceptions.ThrowEFail();
}
}
public override EnvDTE.CodeElements ImplementedInterfaces
{
get { return ExternalTypeCollection.Create(this.State, this, this.ProjectId, TypeSymbol.AllInterfaces); }
}
public EnvDTE80.vsCMInheritanceKind InheritanceKind
{
get
{
if (IsAbstract)
{
return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract;
}
else if (IsSealed)
{
return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed;
}
else
{
return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone;
}
}
set
{
throw Exceptions.ThrowEFail();
}
}
public new bool IsAbstract
{
get
{
return base.IsAbstract;
}
set
{
throw new NotImplementedException();
}
}
public bool IsGeneric
{
get { return TypeSymbol is INamedTypeSymbol && ((INamedTypeSymbol)TypeSymbol).IsGenericType; }
}
public EnvDTE.CodeElements PartialClasses
{
get { throw Exceptions.ThrowEFail(); }
}
public EnvDTE.CodeElements Parts
{
get { throw Exceptions.ThrowEFail(); }
}
public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access, object location)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access, object location)
=> throw Exceptions.ThrowEFail();
public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object location, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public void RemoveInterface(object element)
=> throw Exceptions.ThrowEFail();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE.CodeClass))]
public sealed class ExternalCodeClass : AbstractExternalCodeType, EnvDTE80.CodeClass2, EnvDTE.CodeClass, EnvDTE.CodeType, EnvDTE.CodeElement, EnvDTE80.CodeElement2
{
internal static EnvDTE.CodeClass Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
{
var newElement = new ExternalCodeClass(state, projectId, typeSymbol);
return (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(newElement);
}
private ExternalCodeClass(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
: base(state, projectId, typeSymbol)
{
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementClass; }
}
public EnvDTE80.vsCMClassKind ClassKind
{
get
{
return EnvDTE80.vsCMClassKind.vsCMClassKindMainClass;
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE80.vsCMDataTypeKind DataTypeKind
{
get
{
return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain;
}
set
{
throw Exceptions.ThrowEFail();
}
}
public override EnvDTE.CodeElements ImplementedInterfaces
{
get { return ExternalTypeCollection.Create(this.State, this, this.ProjectId, TypeSymbol.AllInterfaces); }
}
public EnvDTE80.vsCMInheritanceKind InheritanceKind
{
get
{
if (IsAbstract)
{
return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract;
}
else if (IsSealed)
{
return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed;
}
else
{
return EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone;
}
}
set
{
throw Exceptions.ThrowEFail();
}
}
public new bool IsAbstract
{
get
{
return base.IsAbstract;
}
set
{
throw new NotImplementedException();
}
}
public bool IsGeneric
{
get { return TypeSymbol is INamedTypeSymbol && ((INamedTypeSymbol)TypeSymbol).IsGenericType; }
}
public EnvDTE.CodeElements PartialClasses
{
get { throw Exceptions.ThrowEFail(); }
}
public EnvDTE.CodeElements Parts
{
get { throw Exceptions.ThrowEFail(); }
}
public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access, object location)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access, object location)
=> throw Exceptions.ThrowEFail();
public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object location, EnvDTE.vsCMAccess access)
=> throw Exceptions.ThrowEFail();
public void RemoveInterface(object element)
=> throw Exceptions.ThrowEFail();
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/UnitTestingIncrementalAnalyzerProvider.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.ExternalAccess.UnitTesting.Api;
using Microsoft.CodeAnalysis.SolutionCrawler;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting
{
[Obsolete]
internal class UnitTestingIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider
{
private readonly IUnitTestingIncrementalAnalyzerProviderImplementation _incrementalAnalyzerProvider;
private IIncrementalAnalyzer _analyzer;
public UnitTestingIncrementalAnalyzerProvider(IUnitTestingIncrementalAnalyzerProviderImplementation incrementalAnalyzerProvider)
=> _incrementalAnalyzerProvider = incrementalAnalyzerProvider;
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
{
// NOTE: We're currently expecting the analyzer to be singleton, so that
// analyzers returned when calling this method twice would pass a reference equality check.
// One instance should be created by SolutionCrawler, another one by us, when calling the
// UnitTestingSolutionCrawlerServiceAccessor.Reanalyze method.
if (_analyzer == null)
{
_analyzer = new UnitTestingIncrementalAnalyzer(_incrementalAnalyzerProvider.CreateIncrementalAnalyzer());
}
return _analyzer;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.ExternalAccess.UnitTesting.Api;
using Microsoft.CodeAnalysis.SolutionCrawler;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting
{
[Obsolete]
internal class UnitTestingIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider
{
private readonly IUnitTestingIncrementalAnalyzerProviderImplementation _incrementalAnalyzerProvider;
private IIncrementalAnalyzer _analyzer;
public UnitTestingIncrementalAnalyzerProvider(IUnitTestingIncrementalAnalyzerProviderImplementation incrementalAnalyzerProvider)
=> _incrementalAnalyzerProvider = incrementalAnalyzerProvider;
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
{
// NOTE: We're currently expecting the analyzer to be singleton, so that
// analyzers returned when calling this method twice would pass a reference equality check.
// One instance should be created by SolutionCrawler, another one by us, when calling the
// UnitTestingSolutionCrawlerServiceAccessor.Reanalyze method.
if (_analyzer == null)
{
_analyzer = new UnitTestingIncrementalAnalyzer(_incrementalAnalyzerProvider.CreateIncrementalAnalyzer());
}
return _analyzer;
}
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.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.CodeActions;
using Microsoft.CodeAnalysis.Packaging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddPackage
{
internal class InstallPackageDirectlyCodeAction : CodeAction
{
private readonly CodeActionOperation _installPackageOperation;
public override string Title { get; }
public InstallPackageDirectlyCodeAction(
IPackageInstallerService installerService,
Document document,
string source,
string packageName,
string versionOpt,
bool includePrerelease,
bool isLocal)
{
Title = versionOpt == null
? FeaturesResources.Find_and_install_latest_version
: isLocal
? string.Format(FeaturesResources.Use_local_version_0, versionOpt)
: string.Format(FeaturesResources.Install_version_0, versionOpt);
_installPackageOperation = new InstallPackageDirectlyCodeActionOperation(
installerService, document, source, packageName,
versionOpt, includePrerelease, isLocal);
}
protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
=> Task.FromResult(SpecializedCollections.SingletonEnumerable(_installPackageOperation));
}
}
| // Licensed to the .NET Foundation under one or more 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.CodeActions;
using Microsoft.CodeAnalysis.Packaging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddPackage
{
internal class InstallPackageDirectlyCodeAction : CodeAction
{
private readonly CodeActionOperation _installPackageOperation;
public override string Title { get; }
public InstallPackageDirectlyCodeAction(
IPackageInstallerService installerService,
Document document,
string source,
string packageName,
string versionOpt,
bool includePrerelease,
bool isLocal)
{
Title = versionOpt == null
? FeaturesResources.Find_and_install_latest_version
: isLocal
? string.Format(FeaturesResources.Use_local_version_0, versionOpt)
: string.Format(FeaturesResources.Install_version_0, versionOpt);
_installPackageOperation = new InstallPackageDirectlyCodeActionOperation(
installerService, document, source, packageName,
versionOpt, includePrerelease, isLocal);
}
protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
=> Task.FromResult(SpecializedCollections.SingletonEnumerable(_installPackageOperation));
}
}
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/LoopKeywordRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Loop" statement.
''' </summary>
Friend Class LoopKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Dim targetToken = context.TargetToken
If context.IsSingleLineStatementContext Then
Dim doBlock = targetToken.GetAncestor(Of DoLoopBlockSyntax)()
If doBlock Is Nothing OrElse Not doBlock.LoopStatement.IsMissing Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
If doBlock.Kind <> SyntaxKind.SimpleDoLoopBlock Then
Return ImmutableArray.Create(New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement))
Else
Return ImmutableArray.Create(
New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement),
New RecommendedKeyword("Loop Until", VBFeaturesResources.Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition),
New RecommendedKeyword("Loop While", VBFeaturesResources.Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition))
End If
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
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Loop" statement.
''' </summary>
Friend Class LoopKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Dim targetToken = context.TargetToken
If context.IsSingleLineStatementContext Then
Dim doBlock = targetToken.GetAncestor(Of DoLoopBlockSyntax)()
If doBlock Is Nothing OrElse Not doBlock.LoopStatement.IsMissing Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
If doBlock.Kind <> SyntaxKind.SimpleDoLoopBlock Then
Return ImmutableArray.Create(New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement))
Else
Return ImmutableArray.Create(
New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement),
New RecommendedKeyword("Loop Until", VBFeaturesResources.Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition),
New RecommendedKeyword("Loop While", VBFeaturesResources.Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition))
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,148 | Remove experimentation for imports on paste | We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ryzngard | 2021-07-27T20:19:14Z | 2021-07-28T00:47:31Z | db1cd11f5ad961a08d3a1cac027eab332b8c9f5e | b2f11d77681ad4dbdb80fb40e8362eea07a3d48a | Remove experimentation for imports on paste. We've enabled this by default with experimentation in Preview 2. This removes the experimentation altogether in Preview 3 | ./src/Compilers/Server/VBCSCompilerTests/BuildClientTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
extern alias csc;
extern alias vbc;
using System;
using System.IO;
using Microsoft.CodeAnalysis.CommandLine;
using System.Runtime.InteropServices;
using Moq;
using Xunit;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System.Threading;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
public abstract class BuildClientTests : TestBase
{
public sealed class ServerTests : BuildClientTests
{
private readonly string _pipeName = Guid.NewGuid().ToString("N");
private readonly BuildPaths _buildPaths;
private readonly List<ServerData> _serverDataList = new List<ServerData>();
private readonly XunitCompilerServerLogger _logger;
private bool _allowServer = true;
private int _failedCreatedServerCount = 0;
public ServerTests(ITestOutputHelper testOutputHelper)
{
_buildPaths = ServerUtil.CreateBuildPaths(
workingDir: Temp.CreateDirectory().Path,
tempDir: Temp.CreateDirectory().Path);
_logger = new XunitCompilerServerLogger(testOutputHelper);
}
public override void Dispose()
{
foreach (var serverData in _serverDataList)
{
serverData.CancellationTokenSource.Cancel();
serverData.ServerTask.Wait();
}
base.Dispose();
}
private BuildClient CreateClient(
RequestLanguage? language = null,
CompileFunc compileFunc = null,
CreateServerFunc createServerFunc = null)
{
language ??= RequestLanguage.CSharpCompile;
compileFunc ??= delegate { return 0; };
createServerFunc ??= ((_, pipeName, _) => TryCreateServer(pipeName));
return new BuildClient(language.Value, compileFunc, _logger, createServerFunc);
}
private ServerData CreateServer(string pipeName)
{
var serverData = ServerUtil.CreateServer(_logger, pipeName).GetAwaiter().GetResult();
_serverDataList.Add(serverData);
return serverData;
}
private bool TryCreateServer(string pipeName)
{
if (!_allowServer)
{
_failedCreatedServerCount++;
return false;
}
CreateServer(pipeName);
return true;
}
[Fact]
public void ConnectToServerFails()
{
// Create and grab the mutex for the server. This should make
// the client believe that a server is active and it will try
// to connect. When it fails it should fall back to in-proc
// compilation.
bool holdsMutex;
using (var serverMutex = new Mutex(initiallyOwned: true,
name: BuildServerConnection.GetServerMutexName(_pipeName),
createdNew: out holdsMutex))
{
Assert.True(holdsMutex);
var ranLocal = false;
// Note: Connecting to a server can take up to a second to time out
var client = CreateClient(
compileFunc: delegate
{
ranLocal = true;
return 0;
});
var exitCode = client.RunCompilation(new[] { "/shared" }, _buildPaths, pipeName: _pipeName).ExitCode;
Assert.Equal(0, exitCode);
Assert.True(ranLocal);
}
}
#if NET472
[Fact]
public void TestMutexConstructorException()
{
using (var outer = new Mutex(initiallyOwned: true, name: BuildServerConnection.GetClientMutexName(_pipeName), out bool createdNew))
{
Assert.True(createdNew);
var mutexSecurity = outer.GetAccessControl();
mutexSecurity.AddAccessRule(new MutexAccessRule(WindowsIdentity.GetCurrent().Owner, MutexRights.FullControl, AccessControlType.Deny));
outer.SetAccessControl(mutexSecurity);
var ranLocal = false;
var client = CreateClient(
compileFunc: delegate
{
ranLocal = true;
return 0;
});
var exitCode = client.RunCompilation(new[] { "/shared" }, _buildPaths, pipeName: _pipeName).ExitCode;
Assert.Equal(0, exitCode);
Assert.True(ranLocal);
}
}
#endif
[Fact]
public async Task ConnectToPipe()
{
string pipeName = ServerUtil.GetPipeName();
var oneSec = TimeSpan.FromSeconds(1);
Assert.False(await tryConnectToNamedPipe((int)oneSec.TotalMilliseconds, cancellationToken: default));
// Try again with infinite timeout and cancel
var cts = new CancellationTokenSource();
var connection = tryConnectToNamedPipe(Timeout.Infinite, cts.Token);
Assert.False(connection.IsCompleted);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(
async () => await connection);
// Create server and try again
Assert.True(TryCreateServer(pipeName));
Assert.True(await tryConnectToNamedPipe(Timeout.Infinite, cancellationToken: default));
async Task<bool> tryConnectToNamedPipe(int timeoutMs, CancellationToken cancellationToken)
{
using var pipeStream = await BuildServerConnection.TryConnectToServerAsync(pipeName, timeoutMs, _logger, cancellationToken);
return pipeStream != null;
}
}
[ConditionalFact(typeof(DesktopOnly))]
public void OnlyStartsOneServer()
{
var ranLocal = false;
var client = CreateClient(
compileFunc: delegate
{
ranLocal = true;
throw new Exception();
});
for (var i = 0; i < 5; i++)
{
client.RunCompilation(new[] { "/shared" }, _buildPaths, new StringWriter(), pipeName: _pipeName);
}
Assert.Equal(1, _serverDataList.Count);
Assert.False(ranLocal);
}
[Fact]
public void FallbackToCsc()
{
_allowServer = false;
var ranLocal = false;
var client = CreateClient(compileFunc: delegate
{
ranLocal = true;
return 0;
});
var exitCode = client.RunCompilation(new[] { "/shared" }, _buildPaths, pipeName: _pipeName).ExitCode;
Assert.Equal(0, exitCode);
Assert.True(ranLocal);
Assert.Equal(1, _failedCreatedServerCount);
Assert.Equal(0, _serverDataList.Count);
}
}
public sealed class TryParseClientArgsTest : BuildClientTests
{
private bool _hasShared;
private string _keepAlive;
private string _errorMessage;
private string _sessionKey;
private List<string> _parsedArgs;
private bool Parse(params string[] args)
{
return CommandLineParser.TryParseClientArgs(
args,
out _parsedArgs,
out _hasShared,
out _keepAlive,
out _sessionKey,
out _errorMessage);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void Shared(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "shared", "test.cs"));
Assert.True(_hasShared);
Assert.Null(_sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void SharedWithSessionKey(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "shared:pipe", "test.cs"));
Assert.True(_hasShared);
Assert.Equal("pipe", _sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(Parse(optionPrefix + "shared:1:2", "test.cs"));
Assert.True(_hasShared);
Assert.Equal("1:2", _sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(Parse(optionPrefix + "shared=1:2", "test.cs"));
Assert.True(_hasShared);
Assert.Equal("1:2", _sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void SharedWithEmptySessionKey(char optionPrefix)
{
Assert.False(Parse(optionPrefix + "shared:", "test.cs"));
Assert.False(_hasShared);
Assert.Equal(CodeAnalysisResources.SharedArgumentMissing, _errorMessage);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void SharedPrefix(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "sharedstart", "test.cs"));
Assert.False(_hasShared);
Assert.Equal(new[] { optionPrefix + "sharedstart", "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void Basic(char optionPrefix)
{
Assert.True(Parse("test.cs"));
Assert.False(_hasShared);
Assert.Null(_sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(Parse(optionPrefix + "keepalive:100", "/shared", "test.cs"));
Assert.True(_hasShared);
Assert.Null(_sessionKey);
Assert.Equal("100", _keepAlive);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void KeepAliveBad(char optionPrefix)
{
Assert.False(Parse(optionPrefix + "keepalive", "test.cs"));
Assert.Equal(CodeAnalysisResources.MissingKeepAlive, _errorMessage);
Assert.False(Parse(optionPrefix + "keepalive:", "test.cs"));
Assert.Equal(CodeAnalysisResources.MissingKeepAlive, _errorMessage);
Assert.False(Parse(optionPrefix + "keepalive:-100", "test.cs"));
Assert.Equal(CodeAnalysisResources.KeepAliveIsTooSmall, _errorMessage);
Assert.False(Parse(optionPrefix + "keepalive:100", "test.cs"));
Assert.Equal(CodeAnalysisResources.KeepAliveWithoutShared, _errorMessage);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void KeepAlivePrefix(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "keepalivestart", "test.cs"));
Assert.Null(_keepAlive);
Assert.Equal(new[] { optionPrefix + "keepalivestart", "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void KeepAlive(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "keepalive:100", optionPrefix + "shared", "test.cs"));
Assert.Equal("100", _keepAlive);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(_hasShared);
Assert.Null(_sessionKey);
Assert.True(Parse(optionPrefix + "keepalive=100", optionPrefix + "shared", "test.cs"));
Assert.Equal("100", _keepAlive);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(_hasShared);
Assert.Null(_sessionKey);
}
}
public class MiscTest
{
[Fact]
public void GetPipeNameForPathOptSlashes()
{
var path = string.Format(@"q:{0}the{0}path", Path.DirectorySeparatorChar);
var name = BuildServerConnection.GetPipeNameForPath(path);
Assert.Equal(name, BuildServerConnection.GetPipeNameForPath(path));
Assert.Equal(name, BuildServerConnection.GetPipeNameForPath(path + Path.DirectorySeparatorChar));
Assert.Equal(name, BuildServerConnection.GetPipeNameForPath(path + Path.DirectorySeparatorChar + Path.DirectorySeparatorChar));
}
[Fact]
public void GetPipeNameForPathOptLength()
{
var path = string.Format(@"q:{0}the{0}path", Path.DirectorySeparatorChar);
var name = BuildServerConnection.GetPipeNameForPath(path);
// We only have ~50 total bytes to work with on mac, so the base path must be small
Assert.Equal(43, name.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
extern alias csc;
extern alias vbc;
using System;
using System.IO;
using Microsoft.CodeAnalysis.CommandLine;
using System.Runtime.InteropServices;
using Moq;
using Xunit;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System.Threading;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
public abstract class BuildClientTests : TestBase
{
public sealed class ServerTests : BuildClientTests
{
private readonly string _pipeName = Guid.NewGuid().ToString("N");
private readonly BuildPaths _buildPaths;
private readonly List<ServerData> _serverDataList = new List<ServerData>();
private readonly XunitCompilerServerLogger _logger;
private bool _allowServer = true;
private int _failedCreatedServerCount = 0;
public ServerTests(ITestOutputHelper testOutputHelper)
{
_buildPaths = ServerUtil.CreateBuildPaths(
workingDir: Temp.CreateDirectory().Path,
tempDir: Temp.CreateDirectory().Path);
_logger = new XunitCompilerServerLogger(testOutputHelper);
}
public override void Dispose()
{
foreach (var serverData in _serverDataList)
{
serverData.CancellationTokenSource.Cancel();
serverData.ServerTask.Wait();
}
base.Dispose();
}
private BuildClient CreateClient(
RequestLanguage? language = null,
CompileFunc compileFunc = null,
CreateServerFunc createServerFunc = null)
{
language ??= RequestLanguage.CSharpCompile;
compileFunc ??= delegate { return 0; };
createServerFunc ??= ((_, pipeName, _) => TryCreateServer(pipeName));
return new BuildClient(language.Value, compileFunc, _logger, createServerFunc);
}
private ServerData CreateServer(string pipeName)
{
var serverData = ServerUtil.CreateServer(_logger, pipeName).GetAwaiter().GetResult();
_serverDataList.Add(serverData);
return serverData;
}
private bool TryCreateServer(string pipeName)
{
if (!_allowServer)
{
_failedCreatedServerCount++;
return false;
}
CreateServer(pipeName);
return true;
}
[Fact]
public void ConnectToServerFails()
{
// Create and grab the mutex for the server. This should make
// the client believe that a server is active and it will try
// to connect. When it fails it should fall back to in-proc
// compilation.
bool holdsMutex;
using (var serverMutex = new Mutex(initiallyOwned: true,
name: BuildServerConnection.GetServerMutexName(_pipeName),
createdNew: out holdsMutex))
{
Assert.True(holdsMutex);
var ranLocal = false;
// Note: Connecting to a server can take up to a second to time out
var client = CreateClient(
compileFunc: delegate
{
ranLocal = true;
return 0;
});
var exitCode = client.RunCompilation(new[] { "/shared" }, _buildPaths, pipeName: _pipeName).ExitCode;
Assert.Equal(0, exitCode);
Assert.True(ranLocal);
}
}
#if NET472
[Fact]
public void TestMutexConstructorException()
{
using (var outer = new Mutex(initiallyOwned: true, name: BuildServerConnection.GetClientMutexName(_pipeName), out bool createdNew))
{
Assert.True(createdNew);
var mutexSecurity = outer.GetAccessControl();
mutexSecurity.AddAccessRule(new MutexAccessRule(WindowsIdentity.GetCurrent().Owner, MutexRights.FullControl, AccessControlType.Deny));
outer.SetAccessControl(mutexSecurity);
var ranLocal = false;
var client = CreateClient(
compileFunc: delegate
{
ranLocal = true;
return 0;
});
var exitCode = client.RunCompilation(new[] { "/shared" }, _buildPaths, pipeName: _pipeName).ExitCode;
Assert.Equal(0, exitCode);
Assert.True(ranLocal);
}
}
#endif
[Fact]
public async Task ConnectToPipe()
{
string pipeName = ServerUtil.GetPipeName();
var oneSec = TimeSpan.FromSeconds(1);
Assert.False(await tryConnectToNamedPipe((int)oneSec.TotalMilliseconds, cancellationToken: default));
// Try again with infinite timeout and cancel
var cts = new CancellationTokenSource();
var connection = tryConnectToNamedPipe(Timeout.Infinite, cts.Token);
Assert.False(connection.IsCompleted);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(
async () => await connection);
// Create server and try again
Assert.True(TryCreateServer(pipeName));
Assert.True(await tryConnectToNamedPipe(Timeout.Infinite, cancellationToken: default));
async Task<bool> tryConnectToNamedPipe(int timeoutMs, CancellationToken cancellationToken)
{
using var pipeStream = await BuildServerConnection.TryConnectToServerAsync(pipeName, timeoutMs, _logger, cancellationToken);
return pipeStream != null;
}
}
[ConditionalFact(typeof(DesktopOnly))]
public void OnlyStartsOneServer()
{
var ranLocal = false;
var client = CreateClient(
compileFunc: delegate
{
ranLocal = true;
throw new Exception();
});
for (var i = 0; i < 5; i++)
{
client.RunCompilation(new[] { "/shared" }, _buildPaths, new StringWriter(), pipeName: _pipeName);
}
Assert.Equal(1, _serverDataList.Count);
Assert.False(ranLocal);
}
[Fact]
public void FallbackToCsc()
{
_allowServer = false;
var ranLocal = false;
var client = CreateClient(compileFunc: delegate
{
ranLocal = true;
return 0;
});
var exitCode = client.RunCompilation(new[] { "/shared" }, _buildPaths, pipeName: _pipeName).ExitCode;
Assert.Equal(0, exitCode);
Assert.True(ranLocal);
Assert.Equal(1, _failedCreatedServerCount);
Assert.Equal(0, _serverDataList.Count);
}
}
public sealed class TryParseClientArgsTest : BuildClientTests
{
private bool _hasShared;
private string _keepAlive;
private string _errorMessage;
private string _sessionKey;
private List<string> _parsedArgs;
private bool Parse(params string[] args)
{
return CommandLineParser.TryParseClientArgs(
args,
out _parsedArgs,
out _hasShared,
out _keepAlive,
out _sessionKey,
out _errorMessage);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void Shared(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "shared", "test.cs"));
Assert.True(_hasShared);
Assert.Null(_sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void SharedWithSessionKey(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "shared:pipe", "test.cs"));
Assert.True(_hasShared);
Assert.Equal("pipe", _sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(Parse(optionPrefix + "shared:1:2", "test.cs"));
Assert.True(_hasShared);
Assert.Equal("1:2", _sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(Parse(optionPrefix + "shared=1:2", "test.cs"));
Assert.True(_hasShared);
Assert.Equal("1:2", _sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void SharedWithEmptySessionKey(char optionPrefix)
{
Assert.False(Parse(optionPrefix + "shared:", "test.cs"));
Assert.False(_hasShared);
Assert.Equal(CodeAnalysisResources.SharedArgumentMissing, _errorMessage);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void SharedPrefix(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "sharedstart", "test.cs"));
Assert.False(_hasShared);
Assert.Equal(new[] { optionPrefix + "sharedstart", "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void Basic(char optionPrefix)
{
Assert.True(Parse("test.cs"));
Assert.False(_hasShared);
Assert.Null(_sessionKey);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(Parse(optionPrefix + "keepalive:100", "/shared", "test.cs"));
Assert.True(_hasShared);
Assert.Null(_sessionKey);
Assert.Equal("100", _keepAlive);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void KeepAliveBad(char optionPrefix)
{
Assert.False(Parse(optionPrefix + "keepalive", "test.cs"));
Assert.Equal(CodeAnalysisResources.MissingKeepAlive, _errorMessage);
Assert.False(Parse(optionPrefix + "keepalive:", "test.cs"));
Assert.Equal(CodeAnalysisResources.MissingKeepAlive, _errorMessage);
Assert.False(Parse(optionPrefix + "keepalive:-100", "test.cs"));
Assert.Equal(CodeAnalysisResources.KeepAliveIsTooSmall, _errorMessage);
Assert.False(Parse(optionPrefix + "keepalive:100", "test.cs"));
Assert.Equal(CodeAnalysisResources.KeepAliveWithoutShared, _errorMessage);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void KeepAlivePrefix(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "keepalivestart", "test.cs"));
Assert.Null(_keepAlive);
Assert.Equal(new[] { optionPrefix + "keepalivestart", "test.cs" }, _parsedArgs);
}
[Theory]
[InlineData('-')]
[InlineData('/')]
public void KeepAlive(char optionPrefix)
{
Assert.True(Parse(optionPrefix + "keepalive:100", optionPrefix + "shared", "test.cs"));
Assert.Equal("100", _keepAlive);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(_hasShared);
Assert.Null(_sessionKey);
Assert.True(Parse(optionPrefix + "keepalive=100", optionPrefix + "shared", "test.cs"));
Assert.Equal("100", _keepAlive);
Assert.Equal(new[] { "test.cs" }, _parsedArgs);
Assert.True(_hasShared);
Assert.Null(_sessionKey);
}
}
public class MiscTest
{
[Fact]
public void GetPipeNameForPathOptSlashes()
{
var path = string.Format(@"q:{0}the{0}path", Path.DirectorySeparatorChar);
var name = BuildServerConnection.GetPipeNameForPath(path);
Assert.Equal(name, BuildServerConnection.GetPipeNameForPath(path));
Assert.Equal(name, BuildServerConnection.GetPipeNameForPath(path + Path.DirectorySeparatorChar));
Assert.Equal(name, BuildServerConnection.GetPipeNameForPath(path + Path.DirectorySeparatorChar + Path.DirectorySeparatorChar));
}
[Fact]
public void GetPipeNameForPathOptLength()
{
var path = string.Format(@"q:{0}the{0}path", Path.DirectorySeparatorChar);
var name = BuildServerConnection.GetPipeNameForPath(path);
// We only have ~50 total bytes to work with on mac, so the base path must be small
Assert.Equal(43, name.Length);
}
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/EditorFeatures/CSharpTest/CodeActions/IntroduceParameter/IntroduceParameterTests.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.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.IntroduceVariable;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.IntroduceParameter
{
public class IntroduceParameterTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpIntroduceParameterCodeRefactoringProvider();
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> FlattenActions(actions);
private OptionsCollection UseExpressionBody =>
Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithNoMethodCallsCase()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z;|]
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithLocal()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int l = 5;
int m = [|l * y * z;|]
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestBasicComplexExpressionCase()
{
var code =
@"using System;
class TestClass
{
void M(string x, int y, int z)
{
int m = [|x.Length * y * z|];
}
void M1(string y)
{
M(y, 5, 2);
}
}";
var expected =
@"using System;
class TestClass
{
void M(string x, int y, int z, int m)
{
}
void M1(string y)
{
M(y, 5, 2, y.Length * 5 * 2);
}
}";
await TestInRegularAndScriptAsync(code, expected, 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithSingleMethodCall()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * z * z|];
}
void M1(int x, int y, int z)
{
M(z, x, z);
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
M(z, x, z, z * z * z);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestLocalDeclarationMultipleDeclarators()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * z * z|], y = 0;
}
void M1(int x, int y, int z)
{
M(z, x, z);
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int v)
{
int m = {|Rename:v|}, y = 0;
}
void M1(int x, int y, int z)
{
M(z, x, z, z * z * z);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestDeclarationInForLoop()
{
var code =
@"using System;
class TestClass
{
void M(int a, int b)
{
var v = () =>
{
for (var y = [|a * b|]; ;) { }
};
}
}";
await TestMissingAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithSingleMethodCallInLocalFunction()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = M2(x, z);
int M2(int x, int y)
{
int val = [|x * y|];
return val;
}
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = M2(x, z, x * z);
int M2(int x, int y, int val)
{
return val;
}
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithSingleMethodCallInStaticLocalFunction()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = M2(x, z);
static int M2(int x, int y)
{
int val = [|x * y|];
return val;
}
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = M2(x, z, x * z);
static int M2(int x, int y, int val)
{
return val;
}
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestHighlightIncompleteExpressionCaseWithSingleMethodCall()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = 5 * [|x * y * z|];
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithMultipleMethodCall()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z|];
}
void M1(int x, int y, int z)
{
M(a + b, 5, x);
M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
M(a + b, 5, x, (a + b) * 5 * x);
M(z, y, x, z * y * x);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionAllOccurrences()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = x * y * z;
int f = [|x * y * z|];
}
void M1(int x, int y, int z)
{
M(a + b, 5, x);
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int f)
{
int m = f;
}
void M1(int x, int y, int z)
{
M(a + b, 5, x, (a + b) * 5 * x);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestxpressionWithNoMethodCallTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z;|]
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y, int z)
{
return x * y * z;
}
void M(int x, int y, int z, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|y * x|];
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y)
{
return y * x;
}
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
M(z, y, x, GetM(z, y));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallAndAccessorsTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|y * x|];
}
void M1(int x, int y, int z)
{
this.M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y)
{
return y * x;
}
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
this.M(z, y, x, GetM(z, y));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallAndAccessorsConditionalTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|y * x|];
}
void M1(int x, int y, int z)
{
this?.M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y)
{
return y * x;
}
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
this?.M(z, y, x, this?.GetM(z, y));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallMultipleAccessorsTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a.Prop.ComputeAge(x, y);
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int ComputeAge(int x, int y)
{
var age = [|x + y|];
return age;
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a.Prop.ComputeAge(x, y, a.Prop.GetAge(x, y));
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int GetAge(int x, int y)
{
return x + y;
}
public int ComputeAge(int x, int y, int age)
{
return age;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallMultipleAccessorsConditionalTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a?.Prop?.ComputeAge(x, y);
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int ComputeAge(int x, int y)
{
var age = [|x + y|];
return age;
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a?.Prop?.ComputeAge(x, y, a?.Prop?.GetAge(x, y));
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int GetAge(int x, int y)
{
return x + y;
}
public int ComputeAge(int x, int y, int age)
{
return age;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallAccessorsMixedConditionalTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a.Prop?.ComputeAge(x, y);
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int ComputeAge(int x, int y)
{
var age = [|x + y|];
return age;
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a.Prop?.ComputeAge(x, y, a.Prop?.GetAge(x, y));
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int GetAge(int x, int y)
{
return x + y;
}
public int ComputeAge(int x, int y, int age)
{
return age;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallTrampolineAllOccurrences()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z|];
int l = x * y * z;
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y, int z)
{
return x * y * z;
}
void M(int x, int y, int z, int m)
{
int l = m;
}
void M1(int x, int y, int z)
{
M(z, y, x, GetM(z, y, x));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 4, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithNoMethodCallOverload()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z;|]
}
}";
var expected =
@"using System;
class TestClass
{
private void M(int x, int y, int z)
{
M(x, y, z, x * y * z);
}
void M(int x, int y, int z, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 2, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallOverload()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z|];
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private void M(int x, int y, int z)
{
M(x, y, z, x * y * z);
}
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 2, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionBodiedMemberOverload()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z) => [|x * y * z|];
void M1(int x, int y, int z)
{
int prod = M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int M(int x, int y, int z) => M(x, y, z, x * y * z);
int M(int x, int y, int z, int v) => {|Rename:v|};
void M1(int x, int y, int z)
{
int prod = M(z, y, x);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 2, options: UseExpressionBody, parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionBodiedMemberTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z) => [|x * y * z|];
void M1(int x, int y, int z)
{
int prod = M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetV(int x, int y, int z)
{
return x * y * z;
}
int M(int x, int y, int z, int v) => {|Rename:v|};
void M1(int x, int y, int z)
{
int prod = M(z, y, x, GetV(z, y, x));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithRecursiveCall()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z)
{
int m = [|x * y * z|];
return M(x, x, z);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int y, int z, int m)
{
return M(x, x, z, x * x * z);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithNestedRecursiveCall()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z)
{
int m = [|x * y * z|];
return M(x, x, M(x, y, z));
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int y, int z, int m)
{
return M(x, x, M(x, y, z, x * y * z), x * x * M(x, y, z, x * y * z));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithParamsArg()
{
var code =
@"using System;
class TestClass
{
int M(params int[] args)
{
int m = [|args[0] + args[1]|];
return m;
}
void M1()
{
M(5, 6, 7);
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParameters()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(5, 3);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(5, 5 * 3, 3);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParametersUsed()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(7, 7 * 5);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParametersUsedOverload()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7);
}
}";
var expected =
@"using System;
class TestClass
{
private int M(int x, int y = 5)
{
return M(x, x * y, y);
}
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(7);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParametersUsedTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y = 5)
{
return x * y;
}
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(7, GetM(7));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParametersUnusedTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7, 2);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y = 5)
{
return x * y;
}
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(7, GetM(7, 2), 2);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithCancellationToken()
{
var code =
@"using System;
using System.Threading;
class TestClass
{
int M(int x, CancellationToken cancellationToken)
{
int m = [|x * x|];
return m;
}
void M1(CancellationToken cancellationToken)
{
M(7, cancellationToken);
}
}";
var expected =
@"using System;
using System.Threading;
class TestClass
{
int M(int x, int m, CancellationToken cancellationToken)
{
return m;
}
void M1(CancellationToken cancellationToken)
{
M(7, 7 * 7, cancellationToken);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithRecursiveCallTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z)
{
int m = [|x * y * z|];
return M(x, x, z);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y, int z)
{
return x * y * z;
}
int M(int x, int y, int z, int m)
{
return M(x, x, z, GetM(x, x, z));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithNestedRecursiveCallTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z)
{
int m = [|x * y * z|];
return M(x, x, M(x, y, x));
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y, int z)
{
return x * y * z;
}
int M(int x, int y, int z, int m)
{
return M(x, x, M(x, y, x, GetM(x, y, x)), GetM(x, x, M(x, y, x, GetM(x, y, x))));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseInConstructor()
{
var code =
@"using System;
class TestClass
{
public TestClass(int x, int y)
{
Math.Max([|x + y|], x * y);
}
void TestMethod()
{
var test = new TestClass(5, 6);
}
}";
var expected =
@"using System;
class TestClass
{
public TestClass(int x, int y, int val1)
{
Math.Max({|Rename:val1|}, x * y);
}
void TestMethod()
{
var test = new TestClass(5, 6, 5 + 6);
}
}";
await TestInRegularAndScriptAsync(code, expected, 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestLambdaCaseNormal()
{
var code =
@"using System;
class TestClass
{
Func<int, int, int> mult = (x, y) => [|x * y|];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestLambdaCaseTrampoline()
{
var code =
@"using System;
class TestClass
{
Func<int, int, int> mult = (x, y) => [|x * y|];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestLambdaCaseOverload()
{
var code =
@"using System;
class TestClass
{
Func<int, int, int> mult = (x, y) => [|x * y|];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestTopLevelStatements()
{
var code =
@"using System;
Math.Max(5 + 5, [|6 + 7|]);";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestFieldInitializer()
{
var code =
@"using System;
class TestClass
{
int a = [|5 + 3|];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestIndexer()
{
var code =
@"using System;
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i] => arr[[|i + 5|]];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestPropertyGetter()
{
var code =
@"using System;
class TimePeriod
{
private double _seconds;
public double Hours
{
get { return [|_seconds / 3600|]; }
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestPropertySetter()
{
var code =
@"using System;
class TimePeriod
{
private double _seconds;
public double Hours
{
set {
_seconds = [|value * 3600|];
}
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestDestructor()
{
var code =
@"using System;
class TestClass
{
public ~TestClass()
{
Math.Max([|5 + 5|], 5 * 5);
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionInParameter()
{
var code =
@"using System;
class TestClass
{
public void M(int x = [|5 * 5|])
{
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestCrossLanguageInvocations()
{
var code =
@"<Workspace>
<Project Language= ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
public class Program
{
public Program() {}
public int M(int x, int y)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7, 2);
}
}
</Document>
</Project>
<Project Language= ""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<ProjectReference>Assembly1</ProjectReference>
<Document>
Class ProgramVB
Sub M2()
Dim programC = New Program()
programC.M(7, 2)
End Sub
End Class
</Document>
</Project>
</Workspace>
";
var expected =
@"<Workspace>
<Project Language= ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
public class Program
{
public Program() {}
public int M(int x, int y, int m)
{
return m;
}
void M1()
{
M(7, 2, 7 * 2);
}
}
</Document>
</Project>
<Project Language= ""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<ProjectReference>Assembly1</ProjectReference>
<Document>
Class ProgramVB
Sub M2()
Dim programC = New Program()
programC.M(7, 2)
End Sub
End Class
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(code, expected, 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestConvertedTypeInExpression()
{
var code =
@"using System;
class TestClass
{
void M(double x, double y)
{
int m = [|(int)(x * y);|]
}
}";
var expected =
@"using System;
class TestClass
{
void M(double x, double y, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestConvertedTypeInExpressionTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(double x, double y)
{
int m = [|(int)(x * y);|]
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(double x, double y)
{
return (int)(x * y);
}
void M(double x, double y, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestThisKeywordInExpression()
{
var code =
@"using System;
class TestClass
{
public int M1()
{
return 5;
}
public int M(int x, int y)
{
int m = [|x * this.M1();|]
return m;
}
}";
var expected =
@"using System;
class TestClass
{
public int M1()
{
return 5;
}
public int GetM(int x)
{
return x * this.M1();
}
public int M(int x, int y, int m)
{
return m;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestThisImplicitInExpression()
{
var code =
@"using System;
class TestClass
{
public int M1()
{
return 5;
}
public int M(int x, int y)
{
int m = [|x * M1();|]
return m;
}
}";
var expected =
@"using System;
class TestClass
{
public int M1()
{
return 5;
}
public int GetM(int x)
{
return x * M1();
}
public int M(int x, int y, int m)
{
return m;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestStaticMethodCallInExpression()
{
var code =
@"using System;
class TestClass
{
public static int M1()
{
return 5;
}
public int M(int x, int y)
{
int m = [|x * M1();|]
return m;
}
}";
var expected =
@"using System;
class TestClass
{
public static int M1()
{
return 5;
}
public int M(int x, int y, int m)
{
return m;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestBaseKeywordInExpression()
{
var code =
@"using System;
class Net
{
public int _value = 6;
}
class Perl : Net
{
public new int _value = 7;
public void Write()
{
int x = [|base._value + 1;|]
}
}";
var expected =
@"using System;
class Net
{
public int _value = 6;
}
class Perl : Net
{
public new int _value = 7;
public int GetX()
{
return base._value + 1;
}
public void Write(int x)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestFieldReferenceInOptionalParameter()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = int.MaxValue)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int m, int y = int.MaxValue)
{
return m;
}
void M1()
{
M(7, 7 * int.MaxValue);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestNamedParameterNecessary()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5, int z = 3)
{
int m = [|z * y|];
return m;
}
void M1()
{
M(z: 0, y: 2);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int m, int y = 5, int z = 3)
{
return m;
}
void M1()
{
M(z: 0, m: 0 * 2, y: 2);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestHighlightReturnType()
{
var code =
@"using System;
class TestClass
{
[|int|] M(int x)
{
return x;
}
void M1()
{
M(5);
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestTypeOfOnString()
{
var code =
@"using System;
class TestClass
{
void M()
{
var x = [|typeof(string);|]
}
}";
var expected =
@"using System;
class TestClass
{
void M(Type x)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 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.
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.IntroduceVariable;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.IntroduceParameter
{
public class IntroduceParameterTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpIntroduceParameterCodeRefactoringProvider();
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> FlattenActions(actions);
private OptionsCollection UseExpressionBody =>
Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithNoMethodCallsCase()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z;|]
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithLocal()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int l = 5;
int m = [|l * y * z;|]
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestBasicComplexExpressionCase()
{
var code =
@"using System;
class TestClass
{
void M(string x, int y, int z)
{
int m = [|x.Length * y * z|];
}
void M1(string y)
{
M(y, 5, 2);
}
}";
var expected =
@"using System;
class TestClass
{
void M(string x, int y, int z, int m)
{
}
void M1(string y)
{
M(y, 5, 2, y.Length * 5 * 2);
}
}";
await TestInRegularAndScriptAsync(code, expected, 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithSingleMethodCall()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * z * z|];
}
void M1(int x, int y, int z)
{
M(z, x, z);
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
M(z, x, z, z * z * z);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestLocalDeclarationMultipleDeclarators()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * z * z|], y = 0;
}
void M1(int x, int y, int z)
{
M(z, x, z);
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int v)
{
int m = {|Rename:v|}, y = 0;
}
void M1(int x, int y, int z)
{
M(z, x, z, z * z * z);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestDeclarationInForLoop()
{
var code =
@"using System;
class TestClass
{
void M(int a, int b)
{
var v = () =>
{
for (var y = [|a * b|]; ;) { }
};
}
}";
await TestMissingAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithSingleMethodCallInLocalFunction()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = M2(x, z);
int M2(int x, int y)
{
int val = [|x * y|];
return val;
}
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = M2(x, z, x * z);
int M2(int x, int y, int val)
{
return val;
}
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithSingleMethodCallInStaticLocalFunction()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = M2(x, z);
static int M2(int x, int y)
{
int val = [|x * y|];
return val;
}
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = M2(x, z, x * z);
static int M2(int x, int y, int val)
{
return val;
}
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestHighlightIncompleteExpressionCaseWithSingleMethodCall()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = 5 * [|x * y * z|];
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithMultipleMethodCall()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z|];
}
void M1(int x, int y, int z)
{
M(a + b, 5, x);
M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
M(a + b, 5, x, (a + b) * 5 * x);
M(z, y, x, z * y * x);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionAllOccurrences()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = x * y * z;
int f = [|x * y * z|];
}
void M1(int x, int y, int z)
{
M(a + b, 5, x);
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z, int f)
{
int m = f;
}
void M1(int x, int y, int z)
{
M(a + b, 5, x, (a + b) * 5 * x);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestxpressionWithNoMethodCallTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z;|]
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y, int z)
{
return x * y * z;
}
void M(int x, int y, int z, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|y * x|];
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y)
{
return y * x;
}
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
M(z, y, x, GetM(z, y));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallAndAccessorsTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|y * x|];
}
void M1(int x, int y, int z)
{
this.M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y)
{
return y * x;
}
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
this.M(z, y, x, GetM(z, y));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallAndAccessorsConditionalTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|y * x|];
}
void M1(int x, int y, int z)
{
this?.M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y)
{
return y * x;
}
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
this?.M(z, y, x, this?.GetM(z, y));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallMultipleAccessorsTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a.Prop.ComputeAge(x, y);
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int ComputeAge(int x, int y)
{
var age = [|x + y|];
return age;
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a.Prop.ComputeAge(x, y, a.Prop.GetAge(x, y));
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int GetAge(int x, int y)
{
return x + y;
}
public int ComputeAge(int x, int y, int age)
{
return age;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallMultipleAccessorsConditionalTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a?.Prop?.ComputeAge(x, y);
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int ComputeAge(int x, int y)
{
var age = [|x + y|];
return age;
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a?.Prop?.ComputeAge(x, y, a?.Prop?.GetAge(x, y));
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int GetAge(int x, int y)
{
return x + y;
}
public int ComputeAge(int x, int y, int age)
{
return age;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallAccessorsMixedConditionalTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a.Prop?.ComputeAge(x, y);
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int ComputeAge(int x, int y)
{
var age = [|x + y|];
return age;
}
}";
var expected =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
A a = new A();
var age = a.Prop?.ComputeAge(x, y, a.Prop?.GetAge(x, y));
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int GetAge(int x, int y)
{
return x + y;
}
public int ComputeAge(int x, int y, int age)
{
return age;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallTrampolineAllOccurrences()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z|];
int l = x * y * z;
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y, int z)
{
return x * y * z;
}
void M(int x, int y, int z, int m)
{
int l = m;
}
void M1(int x, int y, int z)
{
M(z, y, x, GetM(z, y, x));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 4, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithNoMethodCallOverload()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z;|]
}
}";
var expected =
@"using System;
class TestClass
{
private void M(int x, int y, int z)
{
M(x, y, z, x * y * z);
}
void M(int x, int y, int z, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 2, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionWithSingleMethodCallOverload()
{
var code =
@"using System;
class TestClass
{
void M(int x, int y, int z)
{
int m = [|x * y * z|];
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private void M(int x, int y, int z)
{
M(x, y, z, x * y * z);
}
void M(int x, int y, int z, int m)
{
}
void M1(int x, int y, int z)
{
M(z, y, x);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 2, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionBodiedMemberOverload()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z) => [|x * y * z|];
void M1(int x, int y, int z)
{
int prod = M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int M(int x, int y, int z) => M(x, y, z, x * y * z);
int M(int x, int y, int z, int v) => {|Rename:v|};
void M1(int x, int y, int z)
{
int prod = M(z, y, x);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 2, options: UseExpressionBody, parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionBodiedMemberTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z) => [|x * y * z|];
void M1(int x, int y, int z)
{
int prod = M(z, y, x);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetV(int x, int y, int z)
{
return x * y * z;
}
int M(int x, int y, int z, int v) => {|Rename:v|};
void M1(int x, int y, int z)
{
int prod = M(z, y, x, GetV(z, y, x));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithRecursiveCall()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z)
{
int m = [|x * y * z|];
return M(x, x, z);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int y, int z, int m)
{
return M(x, x, z, x * x * z);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithNestedRecursiveCall()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z)
{
int m = [|x * y * z|];
return M(x, x, M(x, y, z));
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int y, int z, int m)
{
return M(x, x, M(x, y, z, x * y * z), x * x * M(x, y, z, x * y * z));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithParamsArg()
{
var code =
@"using System;
class TestClass
{
int M(params int[] args)
{
int m = [|args[0] + args[1]|];
return m;
}
void M1()
{
M(5, 6, 7);
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParameters()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(5, 3);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(5, 5 * 3, 3);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParametersUsed()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(7, 7 * 5);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParametersUsedOverload()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7);
}
}";
var expected =
@"using System;
class TestClass
{
private int M(int x, int y = 5)
{
return M(x, x * y, y);
}
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(7);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParametersUsedTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y = 5)
{
return x * y;
}
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(7, GetM(7));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithOptionalParametersUnusedTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7, 2);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y = 5)
{
return x * y;
}
int M(int x, int m, int y = 5)
{
return m;
}
void M1()
{
M(7, GetM(7, 2), 2);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithCancellationToken()
{
var code =
@"using System;
using System.Threading;
class TestClass
{
int M(int x, CancellationToken cancellationToken)
{
int m = [|x * x|];
return m;
}
void M1(CancellationToken cancellationToken)
{
M(7, cancellationToken);
}
}";
var expected =
@"using System;
using System.Threading;
class TestClass
{
int M(int x, int m, CancellationToken cancellationToken)
{
return m;
}
void M1(CancellationToken cancellationToken)
{
M(7, 7 * 7, cancellationToken);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithRecursiveCallTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z)
{
int m = [|x * y * z|];
return M(x, x, z);
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y, int z)
{
return x * y * z;
}
int M(int x, int y, int z, int m)
{
return M(x, x, z, GetM(x, x, z));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseWithNestedRecursiveCallTrampoline()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y, int z)
{
int m = [|x * y * z|];
return M(x, x, M(x, y, x));
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(int x, int y, int z)
{
return x * y * z;
}
int M(int x, int y, int z, int m)
{
return M(x, x, M(x, y, x, GetM(x, y, x)), GetM(x, x, M(x, y, x, GetM(x, y, x))));
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1, options: new OptionsCollection(GetLanguage()), parseOptions: CSharpParseOptions.Default);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionCaseInConstructor()
{
var code =
@"using System;
class TestClass
{
public TestClass(int x, int y)
{
Math.Max([|x + y|], x * y);
}
void TestMethod()
{
var test = new TestClass(5, 6);
}
}";
var expected =
@"using System;
class TestClass
{
public TestClass(int x, int y, int val1)
{
Math.Max({|Rename:val1|}, x * y);
}
void TestMethod()
{
var test = new TestClass(5, 6, 5 + 6);
}
}";
await TestInRegularAndScriptAsync(code, expected, 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestLambdaCaseNormal()
{
var code =
@"using System;
class TestClass
{
Func<int, int, int> mult = (x, y) => [|x * y|];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestLambdaCaseTrampoline()
{
var code =
@"using System;
class TestClass
{
Func<int, int, int> mult = (x, y) => [|x * y|];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestLambdaCaseOverload()
{
var code =
@"using System;
class TestClass
{
Func<int, int, int> mult = (x, y) => [|x * y|];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestTopLevelStatements()
{
var code =
@"using System;
Math.Max(5 + 5, [|6 + 7|]);";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestFieldInitializer()
{
var code =
@"using System;
class TestClass
{
int a = [|5 + 3|];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestIndexer()
{
var code =
@"using System;
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i] => arr[[|i + 5|]];
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestPropertyGetter()
{
var code =
@"using System;
class TimePeriod
{
private double _seconds;
public double Hours
{
get { return [|_seconds / 3600|]; }
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestPropertySetter()
{
var code =
@"using System;
class TimePeriod
{
private double _seconds;
public double Hours
{
set {
_seconds = [|value * 3600|];
}
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestDestructor()
{
var code =
@"using System;
class TestClass
{
public ~TestClass()
{
Math.Max([|5 + 5|], 5 * 5);
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestExpressionInParameter()
{
var code =
@"using System;
class TestClass
{
public void M(int x = [|5 * 5|])
{
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestCrossLanguageInvocations()
{
var code =
@"<Workspace>
<Project Language= ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
public class Program
{
public Program() {}
public int M(int x, int y)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7, 2);
}
}
</Document>
</Project>
<Project Language= ""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<ProjectReference>Assembly1</ProjectReference>
<Document>
Class ProgramVB
Sub M2()
Dim programC = New Program()
programC.M(7, 2)
End Sub
End Class
</Document>
</Project>
</Workspace>
";
var expected =
@"<Workspace>
<Project Language= ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
public class Program
{
public Program() {}
public int M(int x, int y, int m)
{
return m;
}
void M1()
{
M(7, 2, 7 * 2);
}
}
</Document>
</Project>
<Project Language= ""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<ProjectReference>Assembly1</ProjectReference>
<Document>
Class ProgramVB
Sub M2()
Dim programC = New Program()
programC.M(7, 2)
End Sub
End Class
</Document>
</Project>
</Workspace>
";
await TestInRegularAndScriptAsync(code, expected, 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestConvertedTypeInExpression()
{
var code =
@"using System;
class TestClass
{
void M(double x, double y)
{
int m = [|(int)(x * y);|]
}
}";
var expected =
@"using System;
class TestClass
{
void M(double x, double y, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestConvertedTypeInExpressionTrampoline()
{
var code =
@"using System;
class TestClass
{
void M(double x, double y)
{
int m = [|(int)(x * y);|]
}
}";
var expected =
@"using System;
class TestClass
{
private int GetM(double x, double y)
{
return (int)(x * y);
}
void M(double x, double y, int m)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestThisKeywordInExpression()
{
var code =
@"using System;
class TestClass
{
public int M1()
{
return 5;
}
public int M(int x, int y)
{
int m = [|x * this.M1();|]
return m;
}
}";
var expected =
@"using System;
class TestClass
{
public int M1()
{
return 5;
}
public int GetM(int x)
{
return x * this.M1();
}
public int M(int x, int y, int m)
{
return m;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestThisImplicitInExpression()
{
var code =
@"using System;
class TestClass
{
public int M1()
{
return 5;
}
public int M(int x, int y)
{
int m = [|x * M1();|]
return m;
}
}";
var expected =
@"using System;
class TestClass
{
public int M1()
{
return 5;
}
public int GetM(int x)
{
return x * M1();
}
public int M(int x, int y, int m)
{
return m;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestStaticMethodCallInExpression()
{
var code =
@"using System;
class TestClass
{
public static int M1()
{
return 5;
}
public int M(int x, int y)
{
int m = [|x * M1();|]
return m;
}
}";
var expected =
@"using System;
class TestClass
{
public static int M1()
{
return 5;
}
public int M(int x, int y, int m)
{
return m;
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestBaseKeywordInExpression()
{
var code =
@"using System;
class Net
{
public int _value = 6;
}
class Perl : Net
{
public new int _value = 7;
public void Write()
{
int x = [|base._value + 1;|]
}
}";
var expected =
@"using System;
class Net
{
public int _value = 6;
}
class Perl : Net
{
public new int _value = 7;
public int GetX()
{
return base._value + 1;
}
public void Write(int x)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestFieldReferenceInOptionalParameter()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = int.MaxValue)
{
int m = [|x * y|];
return m;
}
void M1()
{
M(7);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int m, int y = int.MaxValue)
{
return m;
}
void M1()
{
M(7, 7 * int.MaxValue);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestNamedParameterNecessary()
{
var code =
@"using System;
class TestClass
{
int M(int x, int y = 5, int z = 3)
{
int m = [|z * y|];
return m;
}
void M1()
{
M(z: 0, y: 2);
}
}";
var expected =
@"using System;
class TestClass
{
int M(int x, int m, int y = 5, int z = 3)
{
return m;
}
void M1()
{
M(z: 0, m: 0 * 2, y: 2);
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestHighlightReturnType()
{
var code =
@"using System;
class TestClass
{
[|int|] M(int x)
{
return x;
}
void M1()
{
M(5);
}
}";
await TestMissingInRegularAndScriptAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestTypeOfOnString()
{
var code =
@"using System;
class TestClass
{
void M()
{
var x = [|typeof(string);|]
}
}";
var expected =
@"using System;
class TestClass
{
void M(Type x)
{
}
}";
await TestInRegularAndScriptAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)]
public async Task TestClassObject()
{
var code =
@"
class F
{
public int x;
public int y;
public F(int x, int y)
{
this.x = x;
this.y = y;
}
}
class TestClass
{
int N(F f)
{
return f.[|x|];
}
void M()
{
N(new F(1, 2));
}
}
";
await TestMissingInRegularAndScriptAsync(code);
}
}
}
| 1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/EditorFeatures/VisualBasicTest/CodeActions/IntroduceParameter/IntroduceParameterTests.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.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.IntroduceParameter
Public Class IntroduceParameterTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicIntroduceParameterCodeRefactoringProvider()
End Function
Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction)
Return GetNestedActions(actions)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithNoMethodCallsCase() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithLocal() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim l As Integer = 5
Dim num As Integer = [|l * x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestBasicComplexExpressionCase() As Task
Dim source =
"Class Program
Sub M(x As String, y As Integer, z As Integer)
Dim num As Integer = [|x.Length * y * z|]
End Sub
Sub M1(y As String)
M(y, 5, 2)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As String, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(y As String)
M(y, 5, 2, y.Length * 5 * 2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithSingleMethodCall() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, z * y * x)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithSingleMethodCallMultipleDeclarators() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num = [|x * y * z|], y = 0
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestHighlightIncompleteExpressionCaseWithSingleMethodCall() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = 5 * [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithMultipleMethodCall() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
M(a + b, 5, x)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, z * y * x)
M(a + b, 5, x, (a + b) * 5 * x)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionAllOccurrences() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num2 As Integer = x * y * z
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
Dim num2 As Integer = num
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, z * y * x)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithNoMethodCallsTrampoline() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallTrampoline() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, GetNum(z, y, x))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallTrampolineAllOccurrences() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
Dim num2 As Integer = x * y * z
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
Dim num2 As Integer = num
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, GetNum(z, y, x))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=4)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallAndAccessorsTrampoline() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
Me.M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
Me.M(z, y, x, GetNum(z, y, x))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallAndAccessorsConditionalTrampoline() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
Me?.M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
Me?.M(z, y, x, Me?.GetNum(z, y, x))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallMultipleAccessorsTrampoline() As Task
Dim source =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a.Prop.ComputeAge(5, 5)
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Function ComputeAge(x As Integer, y As Integer) As Integer
Dim age = [|x + y|]
Return age
End Function
End Class"
Dim expected =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a.Prop.ComputeAge(5, 5, a.Prop.GetAge(5, 5))
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Public Function GetAge(x As Integer, y As Integer) As Integer
Return x + y
End Function
Function ComputeAge(x As Integer, y As Integer, age As Integer) As Integer
Return age
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallMultipleAccessorsConditionalTrampoline() As Task
Dim source =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a?.Prop?.ComputeAge(5, 5)
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Function ComputeAge(x As Integer, y As Integer) As Integer
Dim age = [|x + y|]
Return age
End Function
End Class"
Dim expected =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a?.Prop?.ComputeAge(5, 5, a?.Prop?.GetAge(5, 5))
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Public Function GetAge(x As Integer, y As Integer) As Integer
Return x + y
End Function
Function ComputeAge(x As Integer, y As Integer, age As Integer) As Integer
Return age
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallAccessorsMixedConditionalTrampoline() As Task
Dim source =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a.Prop?.ComputeAge(5, 5)
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Function ComputeAge(x As Integer, y As Integer) As Integer
Dim age = [|x + y|]
Return age
End Function
End Class"
Dim expected =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a.Prop?.ComputeAge(5, 5, a.Prop?.GetAge(5, 5))
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Public Function GetAge(x As Integer, y As Integer) As Integer
Return x + y
End Function
Function ComputeAge(x As Integer, y As Integer, age As Integer) As Integer
Return age
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallAccessorsMixedConditionalTrampoline2() As Task
Dim source =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a?.Prop.ComputeAge(5, 5)
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Function ComputeAge(x As Integer, y As Integer) As Integer
Dim age = [|x + y|]
Return age
End Function
End Class"
Dim expected =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a?.Prop.ComputeAge(5, 5, a?.Prop.GetAge(5, 5))
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Public Function GetAge(x As Integer, y As Integer) As Integer
Return x + y
End Function
Function ComputeAge(x As Integer, y As Integer, age As Integer) As Integer
Return age
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithNoMethodCallOverload() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Sub M(x As Integer, y As Integer, z As Integer)
M(x, y, z, x * y * z)
End Sub
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithRecursiveCall() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
M(x, x, z)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
M(x, x, z, x * x * z)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithNestedRecursiveCall() As Task
Dim source =
"Class Program
Function M(x As Integer, y As Integer, z As Integer) As Integer
Dim num As Integer = [|x * y * z|]
return M(x, x, M(x, y, z))
End Function
End Class"
Dim expected =
"Class Program
Function M(x As Integer, y As Integer, z As Integer, num As Integer) As Integer
return M(x, x, M(x, y, z, x * y * z), x * x * M(x, y, z, x * y * z))
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithParamsArg() As Task
Dim source =
"Class Program
Function M(ParamArray args() As Integer) As Integer
Dim num As Integer = [|args(0) + args(1)|]
Return num
End Function
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParameters() As Task
Dim source =
"Class Program
Sub M(x As Integer, Optional y As Integer = 5)
Dim num As Integer = [|x * y|]
End Sub
Sub M1()
M(7, 2)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, num As Integer, Optional y As Integer = 5)
End Sub
Sub M1()
M(7, 7 * 2, 2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParametersUsed() As Task
Dim source =
"Class Program
Sub M(x As Integer, Optional y As Integer = 5)
Dim num As Integer = [|x * y|]
End Sub
Sub M1()
M(7)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, num As Integer, Optional y As Integer = 5)
End Sub
Sub M1()
M(7, 7 * 5)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParametersUsedOverload() As Task
Dim source =
"Class Program
Function M(x As Integer, Optional y As Integer = 5) As Integer
Dim num As Integer = [|x * y|]
Return num
End Function
Sub M1()
Dim x = M(7)
End Sub
End Class"
Dim expected =
"Class Program
Public Function M(x As Integer, Optional y As Integer = 5) As Integer
Return M(x, x * y, y)
End Function
Function M(x As Integer, num As Integer, Optional y As Integer = 5) As Integer
Return num
End Function
Sub M1()
Dim x = M(7)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParametersUsedTrampoline() As Task
Dim source =
"Class Program
Function M(x As Integer, Optional y As Integer = 5) As Integer
Dim num As Integer = [|x * y|]
Return num
End Function
Sub M1()
Dim x = M(7)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, Optional y As Integer = 5) As Integer
Return x * y
End Function
Function M(x As Integer, num As Integer, Optional y As Integer = 5) As Integer
Return num
End Function
Sub M1()
Dim x = M(7, GetNum(7))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParametersUnusedTrampoline() As Task
Dim source =
"Class Program
Function M(x As Integer, Optional y As Integer = 5) As Integer
Dim num As Integer = [|x * y|]
Return num
End Function
Sub M1()
Dim x = M(7, 2)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, Optional y As Integer = 5) As Integer
Return x * y
End Function
Function M(x As Integer, num As Integer, Optional y As Integer = 5) As Integer
Return num
End Function
Sub M1()
Dim x = M(7, GetNum(7, 2), 2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithCancellationToken() As Task
Dim source =
"Imports System.Threading
Class Program
Sub M(x As Integer, cancellationToken As CancellationToken)
Dim num As Integer = [|x * x|]
End Sub
Sub M1(cancellationToken As CancellationToken)
M(7, cancellationToken)
End Sub
End Class"
Dim expected =
"Imports System.Threading
Class Program
Sub M(x As Integer, num As Integer, cancellationToken As CancellationToken)
End Sub
Sub M1(cancellationToken As CancellationToken)
M(7, 7 * 7, cancellationToken)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionInConstructor() As Task
Dim source =
"Class Program
Public Sub New(x As Integer, y As Integer)
Dim prod = [|x * y|]
End Sub
Sub M1()
Dim test As New Program(5, 2)
End Sub
End Class"
Dim expected =
"Class Program
Public Sub New(x As Integer, y As Integer, prod As Integer)
End Sub
Sub M1()
Dim test As New Program(5, 2, 5 * 2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestFieldInitializer() As Task
Dim source =
"Class Program
Public val As Integer = [|5 * 2|]
Public Sub New(x As Integer, y As Integer)
Dim prod = x * y
End Sub
Sub M1()
Dim test As New Program(5, 2)
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestPropertyGetter() As Task
Dim source =
"Class TestClass
Dim seconds As Double
Property Hours() As Double
Get
Return [|seconds / 3600|]
End Get
Set(ByVal Value As Double)
seconds = Value * 3600
End Set
End Property
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestPropertySetter() As Task
Dim source =
"Class TestClass
Dim seconds As Double
Property Hours() As Double
Get
Return seconds / 3600
End Get
Set(ByVal Value As Double)
seconds = [|Value * 3600|]
End Set
End Property
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestDestructor() As Task
Dim source =
"Class Program
Protected Overrides Sub Finalize()
Dim prod = [|1 * 5|]
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionInParameter() As Task
Dim source =
"Class Program
Public Sub M(Optional y as Integer = [|5 * 5|])
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestMeKeywordInExpression() As Task
Dim source =
"Class Program
Dim f As Integer
Public Sub M(x As Integer)
Dim y = [|Me.f + x|]
End Sub
End Class"
Dim expected =
"Class Program
Dim f As Integer
Public Function GetY(x As Integer) As Integer
Return Me.f + x
End Function
Public Sub M(x As Integer, y As Integer)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestNamedParameterNecessary() As Task
Dim source =
"Class Program
Function M(x As Integer, Optional y As Integer = 5, Optional z As Integer = 3) As Integer
Dim num As Integer = [|y * z|]
Return num
End Function
Sub M1()
M(z:=0, y:=2)
End Sub
End Class"
Dim expected =
"Class Program
Function M(x As Integer, num As Integer, Optional y As Integer = 5, Optional z As Integer = 3) As Integer
Return num
End Function
Sub M1()
M(z:=0, num:=2 * 0, y:=2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestInvocationInWithBlock() As Task
Dim source =
"Class Program
Sub M1()
Dim a = New A()
With a
a.Mult(4, 7)
End With
End Sub
End Class
Class A
Sub Mult(x As Integer, y As Integer)
Dim m = [|x * y|]
End Sub
End Class"
Dim expected =
"Class Program
Sub M1()
Dim a = New A()
With a
a.Mult(4, 7, a.GetM(4, 7))
End With
End Sub
End Class
Class A
Public Function GetM(x As Integer, y As Integer) As Integer
Return x * y
End Function
Sub Mult(x As Integer, y As Integer, m As Integer)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestHighlightReturnType() As Task
Dim source =
"Class Program
Public Function M(x As Integer) As [|Integer|]
Return x
End Function
End Class"
Await TestMissingInRegularAndScriptAsync(source)
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.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.IntroduceParameter
Public Class IntroduceParameterTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicIntroduceParameterCodeRefactoringProvider()
End Function
Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction)
Return GetNestedActions(actions)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithNoMethodCallsCase() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithLocal() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim l As Integer = 5
Dim num As Integer = [|l * x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestBasicComplexExpressionCase() As Task
Dim source =
"Class Program
Sub M(x As String, y As Integer, z As Integer)
Dim num As Integer = [|x.Length * y * z|]
End Sub
Sub M1(y As String)
M(y, 5, 2)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As String, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(y As String)
M(y, 5, 2, y.Length * 5 * 2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithSingleMethodCall() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, z * y * x)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithSingleMethodCallMultipleDeclarators() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num = [|x * y * z|], y = 0
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestHighlightIncompleteExpressionCaseWithSingleMethodCall() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = 5 * [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithMultipleMethodCall() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
M(a + b, 5, x)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, z * y * x)
M(a + b, 5, x, (a + b) * 5 * x)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionAllOccurrences() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num2 As Integer = x * y * z
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
Dim num2 As Integer = num
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, z * y * x)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithNoMethodCallsTrampoline() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallTrampoline() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, GetNum(z, y, x))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallTrampolineAllOccurrences() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
Dim num2 As Integer = x * y * z
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
Dim num2 As Integer = num
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x, GetNum(z, y, x))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=4)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallAndAccessorsTrampoline() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
Me.M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
Me.M(z, y, x, GetNum(z, y, x))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallAndAccessorsConditionalTrampoline() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
Me?.M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, y As Integer, z As Integer) As Integer
Return x * y * z
End Function
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
Me?.M(z, y, x, Me?.GetNum(z, y, x))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallMultipleAccessorsTrampoline() As Task
Dim source =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a.Prop.ComputeAge(5, 5)
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Function ComputeAge(x As Integer, y As Integer) As Integer
Dim age = [|x + y|]
Return age
End Function
End Class"
Dim expected =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a.Prop.ComputeAge(5, 5, a.Prop.GetAge(5, 5))
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Public Function GetAge(x As Integer, y As Integer) As Integer
Return x + y
End Function
Function ComputeAge(x As Integer, y As Integer, age As Integer) As Integer
Return age
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallMultipleAccessorsConditionalTrampoline() As Task
Dim source =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a?.Prop?.ComputeAge(5, 5)
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Function ComputeAge(x As Integer, y As Integer) As Integer
Dim age = [|x + y|]
Return age
End Function
End Class"
Dim expected =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a?.Prop?.ComputeAge(5, 5, a?.Prop?.GetAge(5, 5))
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Public Function GetAge(x As Integer, y As Integer) As Integer
Return x + y
End Function
Function ComputeAge(x As Integer, y As Integer, age As Integer) As Integer
Return age
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallAccessorsMixedConditionalTrampoline() As Task
Dim source =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a.Prop?.ComputeAge(5, 5)
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Function ComputeAge(x As Integer, y As Integer) As Integer
Dim age = [|x + y|]
Return age
End Function
End Class"
Dim expected =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a.Prop?.ComputeAge(5, 5, a.Prop?.GetAge(5, 5))
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Public Function GetAge(x As Integer, y As Integer) As Integer
Return x + y
End Function
Function ComputeAge(x As Integer, y As Integer, age As Integer) As Integer
Return age
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithSingleMethodCallAccessorsMixedConditionalTrampoline2() As Task
Dim source =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a?.Prop.ComputeAge(5, 5)
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Function ComputeAge(x As Integer, y As Integer) As Integer
Dim age = [|x + y|]
Return age
End Function
End Class"
Dim expected =
"Class TestClass
Sub Main(args As String())
Dim a = New A()
a?.Prop.ComputeAge(5, 5, a?.Prop.GetAge(5, 5))
End Sub
End Class
Class A
Public Prop As B
End Class
Class B
Public Function GetAge(x As Integer, y As Integer) As Integer
Return x + y
End Function
Function ComputeAge(x As Integer, y As Integer, age As Integer) As Integer
Return age
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionWithNoMethodCallOverload() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Dim expected =
"Class Program
Public Sub M(x As Integer, y As Integer, z As Integer)
M(x, y, z, x * y * z)
End Sub
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
End Sub
Sub M1(x As Integer, y As Integer, z As Integer)
M(z, y, x)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithRecursiveCall() As Task
Dim source =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer)
Dim num As Integer = [|x * y * z|]
M(x, x, z)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, y As Integer, z As Integer, num As Integer)
M(x, x, z, x * x * z)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithNestedRecursiveCall() As Task
Dim source =
"Class Program
Function M(x As Integer, y As Integer, z As Integer) As Integer
Dim num As Integer = [|x * y * z|]
return M(x, x, M(x, y, z))
End Function
End Class"
Dim expected =
"Class Program
Function M(x As Integer, y As Integer, z As Integer, num As Integer) As Integer
return M(x, x, M(x, y, z, x * y * z), x * x * M(x, y, z, x * y * z))
End Function
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithParamsArg() As Task
Dim source =
"Class Program
Function M(ParamArray args() As Integer) As Integer
Dim num As Integer = [|args(0) + args(1)|]
Return num
End Function
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParameters() As Task
Dim source =
"Class Program
Sub M(x As Integer, Optional y As Integer = 5)
Dim num As Integer = [|x * y|]
End Sub
Sub M1()
M(7, 2)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, num As Integer, Optional y As Integer = 5)
End Sub
Sub M1()
M(7, 7 * 2, 2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParametersUsed() As Task
Dim source =
"Class Program
Sub M(x As Integer, Optional y As Integer = 5)
Dim num As Integer = [|x * y|]
End Sub
Sub M1()
M(7)
End Sub
End Class"
Dim expected =
"Class Program
Sub M(x As Integer, num As Integer, Optional y As Integer = 5)
End Sub
Sub M1()
M(7, 7 * 5)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParametersUsedOverload() As Task
Dim source =
"Class Program
Function M(x As Integer, Optional y As Integer = 5) As Integer
Dim num As Integer = [|x * y|]
Return num
End Function
Sub M1()
Dim x = M(7)
End Sub
End Class"
Dim expected =
"Class Program
Public Function M(x As Integer, Optional y As Integer = 5) As Integer
Return M(x, x * y, y)
End Function
Function M(x As Integer, num As Integer, Optional y As Integer = 5) As Integer
Return num
End Function
Sub M1()
Dim x = M(7)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParametersUsedTrampoline() As Task
Dim source =
"Class Program
Function M(x As Integer, Optional y As Integer = 5) As Integer
Dim num As Integer = [|x * y|]
Return num
End Function
Sub M1()
Dim x = M(7)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, Optional y As Integer = 5) As Integer
Return x * y
End Function
Function M(x As Integer, num As Integer, Optional y As Integer = 5) As Integer
Return num
End Function
Sub M1()
Dim x = M(7, GetNum(7))
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithOptionalParametersUnusedTrampoline() As Task
Dim source =
"Class Program
Function M(x As Integer, Optional y As Integer = 5) As Integer
Dim num As Integer = [|x * y|]
Return num
End Function
Sub M1()
Dim x = M(7, 2)
End Sub
End Class"
Dim expected =
"Class Program
Public Function GetNum(x As Integer, Optional y As Integer = 5) As Integer
Return x * y
End Function
Function M(x As Integer, num As Integer, Optional y As Integer = 5) As Integer
Return num
End Function
Sub M1()
Dim x = M(7, GetNum(7, 2), 2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionCaseWithCancellationToken() As Task
Dim source =
"Imports System.Threading
Class Program
Sub M(x As Integer, cancellationToken As CancellationToken)
Dim num As Integer = [|x * x|]
End Sub
Sub M1(cancellationToken As CancellationToken)
M(7, cancellationToken)
End Sub
End Class"
Dim expected =
"Imports System.Threading
Class Program
Sub M(x As Integer, num As Integer, cancellationToken As CancellationToken)
End Sub
Sub M1(cancellationToken As CancellationToken)
M(7, 7 * 7, cancellationToken)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionInConstructor() As Task
Dim source =
"Class Program
Public Sub New(x As Integer, y As Integer)
Dim prod = [|x * y|]
End Sub
Sub M1()
Dim test As New Program(5, 2)
End Sub
End Class"
Dim expected =
"Class Program
Public Sub New(x As Integer, y As Integer, prod As Integer)
End Sub
Sub M1()
Dim test As New Program(5, 2, 5 * 2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestFieldInitializer() As Task
Dim source =
"Class Program
Public val As Integer = [|5 * 2|]
Public Sub New(x As Integer, y As Integer)
Dim prod = x * y
End Sub
Sub M1()
Dim test As New Program(5, 2)
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestPropertyGetter() As Task
Dim source =
"Class TestClass
Dim seconds As Double
Property Hours() As Double
Get
Return [|seconds / 3600|]
End Get
Set(ByVal Value As Double)
seconds = Value * 3600
End Set
End Property
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestPropertySetter() As Task
Dim source =
"Class TestClass
Dim seconds As Double
Property Hours() As Double
Get
Return seconds / 3600
End Get
Set(ByVal Value As Double)
seconds = [|Value * 3600|]
End Set
End Property
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestDestructor() As Task
Dim source =
"Class Program
Protected Overrides Sub Finalize()
Dim prod = [|1 * 5|]
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestExpressionInParameter() As Task
Dim source =
"Class Program
Public Sub M(Optional y as Integer = [|5 * 5|])
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestMeKeywordInExpression() As Task
Dim source =
"Class Program
Dim f As Integer
Public Sub M(x As Integer)
Dim y = [|Me.f + x|]
End Sub
End Class"
Dim expected =
"Class Program
Dim f As Integer
Public Function GetY(x As Integer) As Integer
Return Me.f + x
End Function
Public Sub M(x As Integer, y As Integer)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestNamedParameterNecessary() As Task
Dim source =
"Class Program
Function M(x As Integer, Optional y As Integer = 5, Optional z As Integer = 3) As Integer
Dim num As Integer = [|y * z|]
Return num
End Function
Sub M1()
M(z:=0, y:=2)
End Sub
End Class"
Dim expected =
"Class Program
Function M(x As Integer, num As Integer, Optional y As Integer = 5, Optional z As Integer = 3) As Integer
Return num
End Function
Sub M1()
M(z:=0, num:=2 * 0, y:=2)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=0)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestInvocationInWithBlock() As Task
Dim source =
"Class Program
Sub M1()
Dim a = New A()
With a
a.Mult(4, 7)
End With
End Sub
End Class
Class A
Sub Mult(x As Integer, y As Integer)
Dim m = [|x * y|]
End Sub
End Class"
Dim expected =
"Class Program
Sub M1()
Dim a = New A()
With a
a.Mult(4, 7, a.GetM(4, 7))
End With
End Sub
End Class
Class A
Public Function GetM(x As Integer, y As Integer) As Integer
Return x * y
End Function
Sub Mult(x As Integer, y As Integer, m As Integer)
End Sub
End Class"
Await TestInRegularAndScriptAsync(source, expected, index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestHighlightReturnType() As Task
Dim source =
"Class Program
Public Function M(x As Integer) As [|Integer|]
Return x
End Function
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceParameter)>
Public Async Function TestClassObject() As Task
Dim source =
"Class F
Public x As Integer
Public y As Integer
Public Sub F(x As Integer, y As Integer)
Me.x = x
Me.y = y
End Sub
End Class
Class TestClass
Public Function N(f As F)
Return f.[|x|]
End Function
End Class"
Await TestMissingInRegularAndScriptAsync(source)
End Function
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceParameterService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal abstract partial class AbstractIntroduceParameterService<
TExpressionSyntax,
TInvocationExpressionSyntax,
TObjectCreationExpressionSyntax,
TIdentifierNameSyntax> : CodeRefactoringProvider
where TExpressionSyntax : SyntaxNode
where TInvocationExpressionSyntax : TExpressionSyntax
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TIdentifierNameSyntax : TExpressionSyntax
{
protected abstract SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol);
protected abstract SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments);
protected abstract SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl);
protected abstract bool IsDestructor(IMethodSymbol methodSymbol);
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var expression = await document.TryGetRelevantNodeAsync<TExpressionSyntax>(textSpan, cancellationToken).ConfigureAwait(false);
if (expression == null || CodeRefactoringHelpers.IsNodeUnderselected(expression, textSpan))
{
return;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
if (expressionType is null or IErrorTypeSymbol)
{
return;
}
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
// Need to special case for expressions that are contained within a parameter
// because it is technically "contained" within a method, but an expression in a parameter does not make
// sense to introduce.
var parameterNode = expression.FirstAncestorOrSelf<SyntaxNode>(node => syntaxFacts.IsParameter(node));
if (parameterNode is not null)
{
return;
}
// Need to special case for highlighting of method types because they are also "contained" within a method,
// but it does not make sense to introduce a parameter in that case.
if (syntaxFacts.IsInNamespaceOrTypeContext(expression))
{
return;
}
var generator = SyntaxGenerator.GetGenerator(document);
var containingMethod = expression.FirstAncestorOrSelf<SyntaxNode>(node => generator.GetParameterListNode(node) is not null);
if (containingMethod is null)
{
return;
}
var containingSymbol = semanticModel.GetDeclaredSymbol(containingMethod, cancellationToken);
if (containingSymbol is not IMethodSymbol methodSymbol)
{
return;
}
// Code actions for trampoline and overloads will not be offered if the method is a constructor.
// Code actions for overloads will not be offered if the method if the method is a local function.
var methodKind = methodSymbol.MethodKind;
if (methodKind is not (MethodKind.Ordinary or MethodKind.LocalFunction or MethodKind.Constructor))
{
return;
}
if (IsDestructor(methodSymbol))
{
return;
}
var actions = await GetActionsAsync(document, expression, methodSymbol, containingMethod, cancellationToken).ConfigureAwait(false);
if (actions is null)
{
return;
}
var singleLineExpression = syntaxFacts.ConvertToSingleLine(expression);
var nodeString = singleLineExpression.ToString();
if (actions.Value.actions.Length > 0)
{
context.RegisterRefactoring(new CodeActionWithNestedActions(
string.Format(FeaturesResources.Introduce_parameter_for_0, nodeString), actions.Value.actions, isInlinable: false), textSpan);
}
if (actions.Value.actionsAllOccurrences.Length > 0)
{
context.RegisterRefactoring(new CodeActionWithNestedActions(
string.Format(FeaturesResources.Introduce_parameter_for_all_occurrences_of_0, nodeString), actions.Value.actionsAllOccurrences, isInlinable: false), textSpan);
}
}
/// <summary>
/// Creates new code actions for each introduce parameter possibility.
/// Does not create actions for overloads/trampoline if there are optional parameters or if the methodSymbol
/// is a constructor.
/// </summary>
private async Task<(ImmutableArray<CodeAction> actions, ImmutableArray<CodeAction> actionsAllOccurrences)?> GetActionsAsync(Document document,
TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod,
CancellationToken cancellationToken)
{
var (shouldDisplay, containsClassExpression) = await ShouldExpressionDisplayCodeActionAsync(
document, expression, cancellationToken).ConfigureAwait(false);
if (!shouldDisplay)
{
return null;
}
using var actionsBuilder = TemporaryArray<CodeAction>.Empty;
using var actionsBuilderAllOccurrences = TemporaryArray<CodeAction>.Empty;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
if (!containsClassExpression)
{
actionsBuilder.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: false, IntroduceParameterCodeActionKind.Refactor));
actionsBuilderAllOccurrences.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: true, IntroduceParameterCodeActionKind.Refactor));
}
if (methodSymbol.MethodKind is not MethodKind.Constructor)
{
actionsBuilder.Add(CreateNewCodeAction(
FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: false, IntroduceParameterCodeActionKind.Trampoline));
actionsBuilderAllOccurrences.Add(CreateNewCodeAction(
FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: true, IntroduceParameterCodeActionKind.Trampoline));
if (methodSymbol.MethodKind is not MethodKind.LocalFunction)
{
actionsBuilder.Add(CreateNewCodeAction(
FeaturesResources.into_new_overload, allOccurrences: false, IntroduceParameterCodeActionKind.Overload));
actionsBuilderAllOccurrences.Add(CreateNewCodeAction(
FeaturesResources.into_new_overload, allOccurrences: true, IntroduceParameterCodeActionKind.Overload));
}
}
return (actionsBuilder.ToImmutableAndClear(), actionsBuilderAllOccurrences.ToImmutableAndClear());
// Local function to create a code action with more ease
MyCodeAction CreateNewCodeAction(string actionName, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction)
{
return new MyCodeAction(actionName, c => IntroduceParameterAsync(
document, expression, methodSymbol, containingMethod, allOccurrences, selectedCodeAction, c));
}
}
/// <summary>
/// Determines if the expression is something that should have code actions displayed for it.
/// Depends upon the identifiers in the expression mapping back to parameters.
/// Does not handle params parameters.
/// </summary>
private static async Task<(bool shouldDisplay, bool containsClassExpression)> ShouldExpressionDisplayCodeActionAsync(
Document document, TExpressionSyntax expression, CancellationToken cancellationToken)
{
var variablesInExpression = expression.DescendantNodes();
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var variable in variablesInExpression)
{
var symbol = semanticModel.GetSymbolInfo(variable, cancellationToken).Symbol;
// If the expression contains locals or range variables then we do not want to offer
// code actions since there will be errors at call sites.
if (symbol is IRangeVariableSymbol or ILocalSymbol)
{
return (false, false);
}
if (symbol is IParameterSymbol parameter)
{
// We do not want to offer code actions if the expressions contains references
// to params parameters because it is difficult to know what is being referenced
// at the callsites.
if (parameter.IsParams)
{
return (false, false);
}
}
}
// If expression contains this or base keywords, implicitly or explicitly,
// then we do not want to refactor call sites that are not overloads/trampolines
// because we do not know if the class specific information is available in other documents.
var operation = semanticModel.GetOperation(expression, cancellationToken);
var containsClassSpecificStatement = false;
if (operation is not null)
{
containsClassSpecificStatement = operation.Descendants().Any(op => op.Kind == OperationKind.InstanceReference);
}
return (true, containsClassSpecificStatement);
}
/// <summary>
/// Introduces a new parameter and refactors all the call sites based on the selected code action.
/// </summary>
private async Task<Solution> IntroduceParameterAsync(Document originalDocument, TExpressionSyntax expression,
IMethodSymbol methodSymbol, SyntaxNode containingMethod, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction,
CancellationToken cancellationToken)
{
var methodCallSites = await FindCallSitesAsync(originalDocument, methodSymbol, cancellationToken).ConfigureAwait(false);
var modifiedSolution = originalDocument.Project.Solution;
var rewriter = new IntroduceParameterDocumentRewriter(this, originalDocument,
expression, methodSymbol, containingMethod, selectedCodeAction, allOccurrences);
foreach (var (project, projectCallSites) in methodCallSites.GroupBy(kvp => kvp.Key.Project))
{
var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
foreach (var (document, invocations) in projectCallSites)
{
var newRoot = await rewriter.RewriteDocumentAsync(compilation, document, invocations, cancellationToken).ConfigureAwait(false);
modifiedSolution = modifiedSolution.WithDocumentSyntaxRoot(originalDocument.Id, newRoot);
}
}
return modifiedSolution;
}
/// <summary>
/// Locates all the call sites of the method that introduced the parameter
/// </summary>
protected static async Task<Dictionary<Document, List<SyntaxNode>>> FindCallSitesAsync(
Document document, IMethodSymbol methodSymbol, CancellationToken cancellationToken)
{
var methodCallSites = new Dictionary<Document, List<SyntaxNode>>();
var progress = new StreamingProgressCollector();
await SymbolFinder.FindReferencesAsync(
methodSymbol, document.Project.Solution, progress,
documents: null, FindReferencesSearchOptions.Default, cancellationToken).ConfigureAwait(false);
var referencedSymbols = progress.GetReferencedSymbols();
// Ordering by descending to sort invocations by starting span to account for nested invocations
var referencedLocations = referencedSymbols.SelectMany(referencedSymbol => referencedSymbol.Locations)
.Distinct().Where(reference => !reference.IsImplicit)
.OrderByDescending(reference => reference.Location.SourceSpan.Start);
// Adding the original document to ensure that it will be seen again when processing the call sites
// in order to update the original expression and containing method.
methodCallSites.Add(document, new List<SyntaxNode>());
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
foreach (var refLocation in referencedLocations)
{
// Does not support cross-language references currently
if (refLocation.Document.Project.Language == document.Project.Language)
{
var reference = refLocation.Location.FindNode(cancellationToken).GetRequiredParent();
if (reference is not (TObjectCreationExpressionSyntax or TInvocationExpressionSyntax))
{
reference = reference.GetRequiredParent();
}
// Only adding items that are of type InvocationExpressionSyntax or TObjectCreationExpressionSyntax
var invocationOrCreation = reference as TObjectCreationExpressionSyntax ?? (SyntaxNode?)(reference as TInvocationExpressionSyntax);
if (invocationOrCreation is null)
{
continue;
}
if (!methodCallSites.TryGetValue(refLocation.Document, out var list))
{
list = new List<SyntaxNode>();
methodCallSites.Add(refLocation.Document, list);
}
list.Add(invocationOrCreation);
}
}
return methodCallSites;
}
private class MyCodeAction : SolutionChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution)
: base(title, createChangedSolution, title)
{
}
}
private enum IntroduceParameterCodeActionKind
{
Refactor,
Trampoline,
Overload
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal abstract partial class AbstractIntroduceParameterService<
TExpressionSyntax,
TInvocationExpressionSyntax,
TObjectCreationExpressionSyntax,
TIdentifierNameSyntax> : CodeRefactoringProvider
where TExpressionSyntax : SyntaxNode
where TInvocationExpressionSyntax : TExpressionSyntax
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TIdentifierNameSyntax : TExpressionSyntax
{
protected abstract SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol);
protected abstract SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments);
protected abstract SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl);
protected abstract bool IsDestructor(IMethodSymbol methodSymbol);
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var expression = await document.TryGetRelevantNodeAsync<TExpressionSyntax>(textSpan, cancellationToken).ConfigureAwait(false);
if (expression == null || CodeRefactoringHelpers.IsNodeUnderselected(expression, textSpan))
{
return;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
if (expressionType is null or IErrorTypeSymbol)
{
return;
}
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
// Need to special case for expressions that are contained within a parameter
// because it is technically "contained" within a method, but an expression in a parameter does not make
// sense to introduce.
var parameterNode = expression.FirstAncestorOrSelf<SyntaxNode>(node => syntaxFacts.IsParameter(node));
if (parameterNode is not null)
{
return;
}
// Need to special case for highlighting of method types because they are also "contained" within a method,
// but it does not make sense to introduce a parameter in that case.
if (syntaxFacts.IsInNamespaceOrTypeContext(expression))
{
return;
}
// Need to special case for expressions whose direct parent is a MemberAccessExpression since they will
// never introduce a parameter that makes sense in that case.
if (syntaxFacts.IsNameOfAnyMemberAccessExpression(expression))
{
return;
}
var generator = SyntaxGenerator.GetGenerator(document);
var containingMethod = expression.FirstAncestorOrSelf<SyntaxNode>(node => generator.GetParameterListNode(node) is not null);
if (containingMethod is null)
{
return;
}
var containingSymbol = semanticModel.GetDeclaredSymbol(containingMethod, cancellationToken);
if (containingSymbol is not IMethodSymbol methodSymbol)
{
return;
}
// Code actions for trampoline and overloads will not be offered if the method is a constructor.
// Code actions for overloads will not be offered if the method if the method is a local function.
var methodKind = methodSymbol.MethodKind;
if (methodKind is not (MethodKind.Ordinary or MethodKind.LocalFunction or MethodKind.Constructor))
{
return;
}
if (IsDestructor(methodSymbol))
{
return;
}
var actions = await GetActionsAsync(document, expression, methodSymbol, containingMethod, cancellationToken).ConfigureAwait(false);
if (actions is null)
{
return;
}
var singleLineExpression = syntaxFacts.ConvertToSingleLine(expression);
var nodeString = singleLineExpression.ToString();
if (actions.Value.actions.Length > 0)
{
context.RegisterRefactoring(new CodeActionWithNestedActions(
string.Format(FeaturesResources.Introduce_parameter_for_0, nodeString), actions.Value.actions, isInlinable: false), textSpan);
}
if (actions.Value.actionsAllOccurrences.Length > 0)
{
context.RegisterRefactoring(new CodeActionWithNestedActions(
string.Format(FeaturesResources.Introduce_parameter_for_all_occurrences_of_0, nodeString), actions.Value.actionsAllOccurrences, isInlinable: false), textSpan);
}
}
/// <summary>
/// Creates new code actions for each introduce parameter possibility.
/// Does not create actions for overloads/trampoline if there are optional parameters or if the methodSymbol
/// is a constructor.
/// </summary>
private async Task<(ImmutableArray<CodeAction> actions, ImmutableArray<CodeAction> actionsAllOccurrences)?> GetActionsAsync(Document document,
TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod,
CancellationToken cancellationToken)
{
var (shouldDisplay, containsClassExpression) = await ShouldExpressionDisplayCodeActionAsync(
document, expression, cancellationToken).ConfigureAwait(false);
if (!shouldDisplay)
{
return null;
}
using var actionsBuilder = TemporaryArray<CodeAction>.Empty;
using var actionsBuilderAllOccurrences = TemporaryArray<CodeAction>.Empty;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
if (!containsClassExpression)
{
actionsBuilder.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: false, IntroduceParameterCodeActionKind.Refactor));
actionsBuilderAllOccurrences.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: true, IntroduceParameterCodeActionKind.Refactor));
}
if (methodSymbol.MethodKind is not MethodKind.Constructor)
{
actionsBuilder.Add(CreateNewCodeAction(
FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: false, IntroduceParameterCodeActionKind.Trampoline));
actionsBuilderAllOccurrences.Add(CreateNewCodeAction(
FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: true, IntroduceParameterCodeActionKind.Trampoline));
if (methodSymbol.MethodKind is not MethodKind.LocalFunction)
{
actionsBuilder.Add(CreateNewCodeAction(
FeaturesResources.into_new_overload, allOccurrences: false, IntroduceParameterCodeActionKind.Overload));
actionsBuilderAllOccurrences.Add(CreateNewCodeAction(
FeaturesResources.into_new_overload, allOccurrences: true, IntroduceParameterCodeActionKind.Overload));
}
}
return (actionsBuilder.ToImmutableAndClear(), actionsBuilderAllOccurrences.ToImmutableAndClear());
// Local function to create a code action with more ease
MyCodeAction CreateNewCodeAction(string actionName, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction)
{
return new MyCodeAction(actionName, c => IntroduceParameterAsync(
document, expression, methodSymbol, containingMethod, allOccurrences, selectedCodeAction, c));
}
}
/// <summary>
/// Determines if the expression is something that should have code actions displayed for it.
/// Depends upon the identifiers in the expression mapping back to parameters.
/// Does not handle params parameters.
/// </summary>
private static async Task<(bool shouldDisplay, bool containsClassExpression)> ShouldExpressionDisplayCodeActionAsync(
Document document, TExpressionSyntax expression, CancellationToken cancellationToken)
{
var variablesInExpression = expression.DescendantNodes();
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var variable in variablesInExpression)
{
var symbol = semanticModel.GetSymbolInfo(variable, cancellationToken).Symbol;
// If the expression contains locals or range variables then we do not want to offer
// code actions since there will be errors at call sites.
if (symbol is IRangeVariableSymbol or ILocalSymbol)
{
return (false, false);
}
if (symbol is IParameterSymbol parameter)
{
// We do not want to offer code actions if the expressions contains references
// to params parameters because it is difficult to know what is being referenced
// at the callsites.
if (parameter.IsParams)
{
return (false, false);
}
}
}
// If expression contains this or base keywords, implicitly or explicitly,
// then we do not want to refactor call sites that are not overloads/trampolines
// because we do not know if the class specific information is available in other documents.
var operation = semanticModel.GetOperation(expression, cancellationToken);
var containsClassSpecificStatement = false;
if (operation is not null)
{
containsClassSpecificStatement = operation.Descendants().Any(op => op.Kind == OperationKind.InstanceReference);
}
return (true, containsClassSpecificStatement);
}
/// <summary>
/// Introduces a new parameter and refactors all the call sites based on the selected code action.
/// </summary>
private async Task<Solution> IntroduceParameterAsync(Document originalDocument, TExpressionSyntax expression,
IMethodSymbol methodSymbol, SyntaxNode containingMethod, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction,
CancellationToken cancellationToken)
{
var methodCallSites = await FindCallSitesAsync(originalDocument, methodSymbol, cancellationToken).ConfigureAwait(false);
var modifiedSolution = originalDocument.Project.Solution;
var rewriter = new IntroduceParameterDocumentRewriter(this, originalDocument,
expression, methodSymbol, containingMethod, selectedCodeAction, allOccurrences);
foreach (var (project, projectCallSites) in methodCallSites.GroupBy(kvp => kvp.Key.Project))
{
var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
foreach (var (document, invocations) in projectCallSites)
{
var newRoot = await rewriter.RewriteDocumentAsync(compilation, document, invocations, cancellationToken).ConfigureAwait(false);
modifiedSolution = modifiedSolution.WithDocumentSyntaxRoot(originalDocument.Id, newRoot);
}
}
return modifiedSolution;
}
/// <summary>
/// Locates all the call sites of the method that introduced the parameter
/// </summary>
protected static async Task<Dictionary<Document, List<SyntaxNode>>> FindCallSitesAsync(
Document document, IMethodSymbol methodSymbol, CancellationToken cancellationToken)
{
var methodCallSites = new Dictionary<Document, List<SyntaxNode>>();
var progress = new StreamingProgressCollector();
await SymbolFinder.FindReferencesAsync(
methodSymbol, document.Project.Solution, progress,
documents: null, FindReferencesSearchOptions.Default, cancellationToken).ConfigureAwait(false);
var referencedSymbols = progress.GetReferencedSymbols();
// Ordering by descending to sort invocations by starting span to account for nested invocations
var referencedLocations = referencedSymbols.SelectMany(referencedSymbol => referencedSymbol.Locations)
.Distinct().Where(reference => !reference.IsImplicit)
.OrderByDescending(reference => reference.Location.SourceSpan.Start);
// Adding the original document to ensure that it will be seen again when processing the call sites
// in order to update the original expression and containing method.
methodCallSites.Add(document, new List<SyntaxNode>());
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
foreach (var refLocation in referencedLocations)
{
// Does not support cross-language references currently
if (refLocation.Document.Project.Language == document.Project.Language)
{
var reference = refLocation.Location.FindNode(cancellationToken).GetRequiredParent();
if (reference is not (TObjectCreationExpressionSyntax or TInvocationExpressionSyntax))
{
reference = reference.GetRequiredParent();
}
// Only adding items that are of type InvocationExpressionSyntax or TObjectCreationExpressionSyntax
var invocationOrCreation = reference as TObjectCreationExpressionSyntax ?? (SyntaxNode?)(reference as TInvocationExpressionSyntax);
if (invocationOrCreation is null)
{
continue;
}
if (!methodCallSites.TryGetValue(refLocation.Document, out var list))
{
list = new List<SyntaxNode>();
methodCallSites.Add(refLocation.Document, list);
}
list.Add(invocationOrCreation);
}
}
return methodCallSites;
}
private class MyCodeAction : SolutionChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution)
: base(title, createChangedSolution, title)
{
}
}
private enum IntroduceParameterCodeActionKind
{
Refactor,
Trampoline,
Overload
}
}
}
| 1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/EditorFeatures/Core/Options/ColorSchemeOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.ColorSchemes;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Options
{
internal static class ColorSchemeOptions
{
internal const string ColorSchemeSettingKey = "TextEditor.Roslyn.ColorScheme";
public static readonly Option2<SchemeName> ColorScheme = new(nameof(ColorSchemeOptions),
nameof(ColorScheme),
defaultValue: SchemeName.VisualStudio2019,
storageLocations: new RoamingProfileStorageLocation(ColorSchemeSettingKey));
public static readonly Option2<UseEnhancedColors> LegacyUseEnhancedColors = new(nameof(ColorSchemeOptions),
nameof(LegacyUseEnhancedColors),
defaultValue: UseEnhancedColors.Default,
storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages"));
public enum UseEnhancedColors
{
Migrated = -2,
DoNotUse = -1,
Default = 0,
Use = 1
}
}
[ExportOptionProvider, Shared]
internal class ColorSchemeOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ColorSchemeOptionsProvider()
{
}
public ImmutableArray<IOption> Options => ImmutableArray.Create<IOption>(
ColorSchemeOptions.ColorScheme,
ColorSchemeOptions.LegacyUseEnhancedColors);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.ColorSchemes;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Options
{
internal static class ColorSchemeOptions
{
internal const string ColorSchemeSettingKey = "TextEditor.Roslyn.ColorScheme";
public static readonly Option2<SchemeName> ColorScheme = new(nameof(ColorSchemeOptions),
nameof(ColorScheme),
defaultValue: SchemeName.VisualStudio2019,
storageLocations: new RoamingProfileStorageLocation(ColorSchemeSettingKey));
public static readonly Option2<UseEnhancedColors> LegacyUseEnhancedColors = new(nameof(ColorSchemeOptions),
nameof(LegacyUseEnhancedColors),
defaultValue: UseEnhancedColors.Default,
storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages"));
public enum UseEnhancedColors
{
Migrated = -2,
DoNotUse = -1,
Default = 0,
Use = 1
}
}
[ExportOptionProvider, Shared]
internal class ColorSchemeOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ColorSchemeOptionsProvider()
{
}
public ImmutableArray<IOption> Options => ImmutableArray.Create<IOption>(
ColorSchemeOptions.ColorScheme,
ColorSchemeOptions.LegacyUseEnhancedColors);
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/FinallyKeywordRecommender.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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Finally" keyword for the statement context
''' </summary>
Friend Class FinallyKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Finally", VBFeaturesResources.Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If Not context.IsMultiLineStatementContext Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
Dim tryBlock = targetToken.GetAncestor(Of TryBlockSyntax)()
If tryBlock Is Nothing OrElse tryBlock.FinallyBlock IsNot Nothing Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
' If we're in the Try block, then we simply need to make sure we have no catch blocks, or else a Finally
' won't be valid here
If context.IsInStatementBlockOfKind(SyntaxKind.TryBlock) AndAlso
Not IsInCatchOfTry(targetToken, tryBlock) Then
If tryBlock.CatchBlocks.Count = 0 Then
Return s_keywords
End If
ElseIf IsInCatchOfTry(targetToken, tryBlock) Then
If TextSpan.FromBounds(tryBlock.CatchBlocks.Last().SpanStart, tryBlock.EndTryStatement.SpanStart).Contains(context.Position) Then
Return s_keywords
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
Private Shared Function IsInCatchOfTry(targetToken As SyntaxToken, tryBlock As TryBlockSyntax) As Boolean
Dim parent = targetToken.Parent
While parent IsNot tryBlock
If parent.IsKind(SyntaxKind.CatchBlock) AndAlso tryBlock.CatchBlocks.Contains(DirectCast(parent, CatchBlockSyntax)) Then
Return True
End If
parent = parent.Parent
End While
Return False
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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Finally" keyword for the statement context
''' </summary>
Friend Class FinallyKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Finally", VBFeaturesResources.Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If Not context.IsMultiLineStatementContext Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
Dim tryBlock = targetToken.GetAncestor(Of TryBlockSyntax)()
If tryBlock Is Nothing OrElse tryBlock.FinallyBlock IsNot Nothing Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
' If we're in the Try block, then we simply need to make sure we have no catch blocks, or else a Finally
' won't be valid here
If context.IsInStatementBlockOfKind(SyntaxKind.TryBlock) AndAlso
Not IsInCatchOfTry(targetToken, tryBlock) Then
If tryBlock.CatchBlocks.Count = 0 Then
Return s_keywords
End If
ElseIf IsInCatchOfTry(targetToken, tryBlock) Then
If TextSpan.FromBounds(tryBlock.CatchBlocks.Last().SpanStart, tryBlock.EndTryStatement.SpanStart).Contains(context.Position) Then
Return s_keywords
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
Private Shared Function IsInCatchOfTry(targetToken As SyntaxToken, tryBlock As TryBlockSyntax) As Boolean
Dim parent = targetToken.Parent
While parent IsNot tryBlock
If parent.IsKind(SyntaxKind.CatchBlock) AndAlso tryBlock.CatchBlocks.Contains(DirectCast(parent, CatchBlockSyntax)) Then
Return True
End If
parent = parent.Parent
End While
Return False
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Analyzers/VisualBasic/CodeFixes/FileHeaders/VisualBasicFileHeaderCodeFixProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.FileHeaders
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Namespace Microsoft.CodeAnalysis.VisualBasic.FileHeaders
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.FileHeader)>
<[Shared]>
Friend Class VisualBasicFileHeaderCodeFixProvider
Inherits AbstractFileHeaderCodeFixProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides ReadOnly Property FileHeaderHelper As AbstractFileHeaderHelper
Get
Return VisualBasicFileHeaderHelper.Instance
End Get
End Property
Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts
Get
Return VisualBasicSyntaxFacts.Instance
End Get
End Property
Protected Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds
Get
Return VisualBasicSyntaxKinds.Instance
End Get
End Property
Protected Overrides Function EndOfLine(text As String) As SyntaxTrivia
Return SyntaxFactory.EndOfLine(text)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.FileHeaders
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Namespace Microsoft.CodeAnalysis.VisualBasic.FileHeaders
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.FileHeader)>
<[Shared]>
Friend Class VisualBasicFileHeaderCodeFixProvider
Inherits AbstractFileHeaderCodeFixProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides ReadOnly Property FileHeaderHelper As AbstractFileHeaderHelper
Get
Return VisualBasicFileHeaderHelper.Instance
End Get
End Property
Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts
Get
Return VisualBasicSyntaxFacts.Instance
End Get
End Property
Protected Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds
Get
Return VisualBasicSyntaxKinds.Instance
End Get
End Property
Protected Overrides Function EndOfLine(text As String) As SyntaxTrivia
Return SyntaxFactory.EndOfLine(text)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Compilers/Test/Core/LazyToString.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.Test.Utilities
{
internal sealed class LazyToString
{
private readonly Func<object> _evaluator;
public LazyToString(Func<object> evaluator)
=> _evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator));
public override string ToString()
=> _evaluator().ToString();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Roslyn.Test.Utilities
{
internal sealed class LazyToString
{
private readonly Func<object> _evaluator;
public LazyToString(Func<object> evaluator)
=> _evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator));
public override string ToString()
=> _evaluator().ToString();
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Compilers/VisualBasic/Portable/Emit/PENetModuleBuilder.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.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend NotInheritable Class PENetModuleBuilder
Inherits PEModuleBuilder
Friend Sub New(
sourceModule As SourceModuleSymbol,
emitOptions As EmitOptions,
serializationProperties As Cci.ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription))
MyBase.New(sourceModule, emitOptions, OutputKind.NetModule, serializationProperties, manifestResources)
End Sub
Protected Overrides Sub AddEmbeddedResourcesFromAddedModules(builder As ArrayBuilder(Of Cci.ManagedResource), diagnostics As DiagnosticBag)
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property EncSymbolChanges As SymbolChanges
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property PreviousGeneration As EmitBaseline
Get
Return Nothing
End Get
End Property
Public Overrides Function GetFiles(context As EmitContext) As IEnumerable(Of Cci.IFileReference)
Return SpecializedCollections.EmptyEnumerable(Of Cci.IFileReference)()
End Function
Public Overrides ReadOnly Property SourceAssemblyOpt As ISourceAssemblySymbolInternal
Get
Return Nothing
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend NotInheritable Class PENetModuleBuilder
Inherits PEModuleBuilder
Friend Sub New(
sourceModule As SourceModuleSymbol,
emitOptions As EmitOptions,
serializationProperties As Cci.ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription))
MyBase.New(sourceModule, emitOptions, OutputKind.NetModule, serializationProperties, manifestResources)
End Sub
Protected Overrides Sub AddEmbeddedResourcesFromAddedModules(builder As ArrayBuilder(Of Cci.ManagedResource), diagnostics As DiagnosticBag)
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property EncSymbolChanges As SymbolChanges
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property PreviousGeneration As EmitBaseline
Get
Return Nothing
End Get
End Property
Public Overrides Function GetFiles(context As EmitContext) As IEnumerable(Of Cci.IFileReference)
Return SpecializedCollections.EmptyEnumerable(Of Cci.IFileReference)()
End Function
Public Overrides ReadOnly Property SourceAssemblyOpt As ISourceAssemblySymbolInternal
Get
Return Nothing
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/VisualStudio/Core/Def/Implementation/LanguageClient/LiveShareInProcLanguageClient.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.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient
{
// The C# and VB ILanguageClient should not activate on the host. When LiveShare mirrors the C# ILC to the guest,
// they will not copy the DisableUserExperience attribute, so guests will still use the C# ILC.
[DisableUserExperience(true)]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
[Export(typeof(ILanguageClient))]
internal class LiveShareInProcLanguageClient : AbstractInProcLanguageClient
{
private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, true)]
public LiveShareInProcLanguageClient(
RequestDispatcherFactory csharpVBRequestDispatcherFactory,
VisualStudioWorkspace workspace,
IDiagnosticService diagnosticService,
IAsynchronousOperationListenerProvider listenerProvider,
ILspWorkspaceRegistrationService lspWorkspaceRegistrationService,
DefaultCapabilitiesProvider defaultCapabilitiesProvider,
ILspLoggerFactory lspLoggerFactory,
IThreadingContext threadingContext)
: base(csharpVBRequestDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, diagnosticsClientName: null)
{
_defaultCapabilitiesProvider = defaultCapabilitiesProvider;
}
public override string Name => "Live Share C#/Visual Basic Language Server Client";
public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities)
{
var experimentationService = Workspace.Services.GetRequiredService<IExperimentationService>();
var isLspEditorEnabled = experimentationService.IsExperimentEnabled(VisualStudioWorkspaceContextService.LspEditorFeatureFlagName);
// If the preview feature flag to turn on the LSP editor in local scenarios is on, advertise no capabilities for this Live Share
// LSP server as LSP requests will be serviced by the AlwaysActiveInProcLanguageClient in both local and remote scenarios.
if (isLspEditorEnabled)
{
return new VSServerCapabilities
{
TextDocumentSync = new TextDocumentSyncOptions
{
OpenClose = false,
Change = TextDocumentSyncKind.None,
}
};
}
return _defaultCapabilitiesProvider.GetCapabilities(clientCapabilities);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient
{
// The C# and VB ILanguageClient should not activate on the host. When LiveShare mirrors the C# ILC to the guest,
// they will not copy the DisableUserExperience attribute, so guests will still use the C# ILC.
[DisableUserExperience(true)]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
[Export(typeof(ILanguageClient))]
internal class LiveShareInProcLanguageClient : AbstractInProcLanguageClient
{
private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, true)]
public LiveShareInProcLanguageClient(
RequestDispatcherFactory csharpVBRequestDispatcherFactory,
VisualStudioWorkspace workspace,
IDiagnosticService diagnosticService,
IAsynchronousOperationListenerProvider listenerProvider,
ILspWorkspaceRegistrationService lspWorkspaceRegistrationService,
DefaultCapabilitiesProvider defaultCapabilitiesProvider,
ILspLoggerFactory lspLoggerFactory,
IThreadingContext threadingContext)
: base(csharpVBRequestDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, diagnosticsClientName: null)
{
_defaultCapabilitiesProvider = defaultCapabilitiesProvider;
}
public override string Name => "Live Share C#/Visual Basic Language Server Client";
public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities)
{
var experimentationService = Workspace.Services.GetRequiredService<IExperimentationService>();
var isLspEditorEnabled = experimentationService.IsExperimentEnabled(VisualStudioWorkspaceContextService.LspEditorFeatureFlagName);
// If the preview feature flag to turn on the LSP editor in local scenarios is on, advertise no capabilities for this Live Share
// LSP server as LSP requests will be serviced by the AlwaysActiveInProcLanguageClient in both local and remote scenarios.
if (isLspEditorEnabled)
{
return new VSServerCapabilities
{
TextDocumentSync = new TextDocumentSyncOptions
{
OpenClose = false,
Change = TextDocumentSyncKind.None,
}
};
}
return _defaultCapabilitiesProvider.GetCapabilities(clientCapabilities);
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Compilers/Test/Core/Compilation/Exceptions.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.Runtime.Serialization;
using Microsoft.CodeAnalysis;
using static Roslyn.Test.Utilities.ExceptionHelper;
namespace Roslyn.Test.Utilities
{
[Serializable]
public class EmitException : Exception
{
[field: NonSerialized]
public IEnumerable<Diagnostic> Diagnostics { get; }
public EmitException(IEnumerable<Diagnostic> diagnostics, string directory)
: base(GetMessageFromResult(diagnostics, directory))
{
this.Diagnostics = diagnostics;
}
protected EmitException(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new NotImplementedException();
}
}
[Serializable]
public class ExecutionException : Exception
{
public ExecutionException(string expectedOutput, string actualOutput, string exePath)
: base(GetMessageFromResult(expectedOutput, actualOutput, exePath)) { }
public ExecutionException(Exception innerException, string exePath)
: base(GetMessageFromException(innerException, exePath), innerException) { }
protected ExecutionException(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new NotImplementedException();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis;
using static Roslyn.Test.Utilities.ExceptionHelper;
namespace Roslyn.Test.Utilities
{
[Serializable]
public class EmitException : Exception
{
[field: NonSerialized]
public IEnumerable<Diagnostic> Diagnostics { get; }
public EmitException(IEnumerable<Diagnostic> diagnostics, string directory)
: base(GetMessageFromResult(diagnostics, directory))
{
this.Diagnostics = diagnostics;
}
protected EmitException(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new NotImplementedException();
}
}
[Serializable]
public class ExecutionException : Exception
{
public ExecutionException(string expectedOutput, string actualOutput, string exePath)
: base(GetMessageFromResult(expectedOutput, actualOutput, exePath)) { }
public ExecutionException(Exception innerException, string exePath)
: base(GetMessageFromException(innerException, exePath), innerException) { }
protected ExecutionException(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new NotImplementedException();
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/SpeculationAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Utilities
{
/// <summary>
/// Helper class to analyze the semantic effects of a speculated syntax node replacement on the parenting nodes.
/// Given an expression node from a syntax tree and a new expression from a different syntax tree,
/// it replaces the expression with the new expression to create a speculated syntax tree.
/// It uses the original tree's semantic model to create a speculative semantic model and verifies that
/// the syntax replacement doesn't break the semantics of any parenting nodes of the original expression.
/// </summary>
internal class SpeculationAnalyzer : AbstractSpeculationAnalyzer<
ExpressionSyntax,
TypeSyntax,
AttributeSyntax,
ArgumentSyntax,
CommonForEachStatementSyntax,
ThrowStatementSyntax,
Conversion>
{
/// <summary>
/// Creates a semantic analyzer for speculative syntax replacement.
/// </summary>
/// <param name="expression">Original expression to be replaced.</param>
/// <param name="newExpression">New expression to replace the original expression.</param>
/// <param name="semanticModel">Semantic model of <paramref name="expression"/> node's syntax tree.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="skipVerificationForReplacedNode">
/// True if semantic analysis should be skipped for the replaced node and performed starting from parent of the original and replaced nodes.
/// This could be the case when custom verifications are required to be done by the caller or
/// semantics of the replaced expression are different from the original expression.
/// </param>
/// <param name="failOnOverloadResolutionFailuresInOriginalCode">
/// True if semantic analysis should fail when any of the invocation expression ancestors of <paramref name="expression"/> in original code has overload resolution failures.
/// </param>
public SpeculationAnalyzer(
ExpressionSyntax expression,
ExpressionSyntax newExpression,
SemanticModel semanticModel,
CancellationToken cancellationToken,
bool skipVerificationForReplacedNode = false,
bool failOnOverloadResolutionFailuresInOriginalCode = false)
: base(expression, newExpression, semanticModel, cancellationToken, skipVerificationForReplacedNode, failOnOverloadResolutionFailuresInOriginalCode)
{
}
protected override SyntaxNode GetSemanticRootForSpeculation(ExpressionSyntax expression)
{
Debug.Assert(expression != null);
var parentNodeToSpeculate = expression
.AncestorsAndSelf(ascendOutOfTrivia: false)
.Where(node => CanSpeculateOnNode(node))
.LastOrDefault();
return parentNodeToSpeculate ?? expression;
}
public static bool CanSpeculateOnNode(SyntaxNode node)
{
return (node is StatementSyntax && node.Kind() != SyntaxKind.Block) ||
node is TypeSyntax ||
node is CrefSyntax ||
node.Kind() == SyntaxKind.Attribute ||
node.Kind() == SyntaxKind.ThisConstructorInitializer ||
node.Kind() == SyntaxKind.BaseConstructorInitializer ||
node.Kind() == SyntaxKind.EqualsValueClause ||
node.Kind() == SyntaxKind.ArrowExpressionClause;
}
protected override void ValidateSpeculativeSemanticModel(SemanticModel speculativeSemanticModel, SyntaxNode nodeToSpeculate)
{
Debug.Assert(speculativeSemanticModel != null ||
nodeToSpeculate is ExpressionSyntax ||
this.SemanticRootOfOriginalExpression.GetAncestors().Any(node => node.IsKind(SyntaxKind.UnknownAccessorDeclaration) ||
node.IsKind(SyntaxKind.IncompleteMember) ||
node.IsKind(SyntaxKind.BracketedArgumentList)),
"SemanticModel.TryGetSpeculativeSemanticModel() API returned false.");
}
protected override SemanticModel CreateSpeculativeSemanticModel(SyntaxNode originalNode, SyntaxNode nodeToSpeculate, SemanticModel semanticModel)
=> CreateSpeculativeSemanticModelForNode(originalNode, nodeToSpeculate, semanticModel);
public static SemanticModel CreateSpeculativeSemanticModelForNode(SyntaxNode originalNode, SyntaxNode nodeToSpeculate, SemanticModel semanticModel)
{
var position = originalNode.SpanStart;
var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(originalNode as ExpressionSyntax);
return CreateSpeculativeSemanticModelForNode(nodeToSpeculate, semanticModel, position, isInNamespaceOrTypeContext);
}
public static SemanticModel CreateSpeculativeSemanticModelForNode(SyntaxNode nodeToSpeculate, SemanticModel semanticModel, int position, bool isInNamespaceOrTypeContext)
{
if (semanticModel.IsSpeculativeSemanticModel)
{
// Chaining speculative model not supported, speculate off the original model.
Debug.Assert(semanticModel.ParentModel != null);
Debug.Assert(!semanticModel.ParentModel.IsSpeculativeSemanticModel);
position = semanticModel.OriginalPositionForSpeculation;
semanticModel = semanticModel.ParentModel;
}
SemanticModel speculativeModel;
if (nodeToSpeculate is StatementSyntax statementNode)
{
semanticModel.TryGetSpeculativeSemanticModel(position, statementNode, out speculativeModel);
return speculativeModel;
}
if (nodeToSpeculate is TypeSyntax typeNode)
{
var bindingOption = isInNamespaceOrTypeContext ?
SpeculativeBindingOption.BindAsTypeOrNamespace :
SpeculativeBindingOption.BindAsExpression;
semanticModel.TryGetSpeculativeSemanticModel(position, typeNode, out speculativeModel, bindingOption);
return speculativeModel;
}
if (nodeToSpeculate is CrefSyntax cref)
{
semanticModel.TryGetSpeculativeSemanticModel(position, cref, out speculativeModel);
return speculativeModel;
}
switch (nodeToSpeculate.Kind())
{
case SyntaxKind.Attribute:
semanticModel.TryGetSpeculativeSemanticModel(position, (AttributeSyntax)nodeToSpeculate, out speculativeModel);
return speculativeModel;
case SyntaxKind.BaseConstructorInitializer:
case SyntaxKind.ThisConstructorInitializer:
semanticModel.TryGetSpeculativeSemanticModel(position, (ConstructorInitializerSyntax)nodeToSpeculate, out speculativeModel);
return speculativeModel;
case SyntaxKind.EqualsValueClause:
semanticModel.TryGetSpeculativeSemanticModel(position, (EqualsValueClauseSyntax)nodeToSpeculate, out speculativeModel);
return speculativeModel;
case SyntaxKind.ArrowExpressionClause:
semanticModel.TryGetSpeculativeSemanticModel(position, (ArrowExpressionClauseSyntax)nodeToSpeculate, out speculativeModel);
return speculativeModel;
}
// CONSIDER: Do we care about this case?
Debug.Assert(nodeToSpeculate is ExpressionSyntax);
return null;
}
/// <summary>
/// Determines whether performing the syntax replacement in one of the sibling nodes of the given lambda expressions will change the lambda binding semantics.
/// This is done by first determining the lambda parameters whose type differs in the replaced lambda node.
/// For each of these parameters, we find the descendant identifier name nodes in the lambda body and check if semantics of any of the parenting nodes of these
/// identifier nodes have changed in the replaced lambda.
/// </summary>
public bool ReplacementChangesSemanticsOfUnchangedLambda(ExpressionSyntax originalLambda, ExpressionSyntax replacedLambda)
{
originalLambda = originalLambda.WalkDownParentheses();
replacedLambda = replacedLambda.WalkDownParentheses();
SyntaxNode originalLambdaBody, replacedLambdaBody;
List<string> paramNames;
switch (originalLambda.Kind())
{
case SyntaxKind.ParenthesizedLambdaExpression:
{
var originalParenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)originalLambda;
var originalParams = originalParenthesizedLambda.ParameterList.Parameters;
if (!originalParams.Any())
{
return false;
}
var replacedParenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)replacedLambda;
var replacedParams = replacedParenthesizedLambda.ParameterList.Parameters;
Debug.Assert(originalParams.Count == replacedParams.Count);
paramNames = new List<string>();
for (var i = 0; i < originalParams.Count; i++)
{
var originalParam = originalParams[i];
var replacedParam = replacedParams[i];
if (!HaveSameParameterType(originalParam, replacedParam))
{
paramNames.Add(originalParam.Identifier.ValueText);
}
}
if (!paramNames.Any())
{
return false;
}
originalLambdaBody = originalParenthesizedLambda.Body;
replacedLambdaBody = replacedParenthesizedLambda.Body;
break;
}
case SyntaxKind.SimpleLambdaExpression:
{
var originalSimpleLambda = (SimpleLambdaExpressionSyntax)originalLambda;
var replacedSimpleLambda = (SimpleLambdaExpressionSyntax)replacedLambda;
if (HaveSameParameterType(originalSimpleLambda.Parameter, replacedSimpleLambda.Parameter))
{
return false;
}
paramNames = new List<string>() { originalSimpleLambda.Parameter.Identifier.ValueText };
originalLambdaBody = originalSimpleLambda.Body;
replacedLambdaBody = replacedSimpleLambda.Body;
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(originalLambda.Kind());
}
var originalIdentifierNodes = originalLambdaBody.DescendantNodes().OfType<IdentifierNameSyntax>().Where(node => paramNames.Contains(node.Identifier.ValueText));
if (!originalIdentifierNodes.Any())
{
return false;
}
var replacedIdentifierNodes = replacedLambdaBody.DescendantNodes().OfType<IdentifierNameSyntax>().Where(node => paramNames.Contains(node.Identifier.ValueText));
return ReplacementChangesSemanticsForNodes(originalIdentifierNodes, replacedIdentifierNodes, originalLambdaBody);
}
private bool HaveSameParameterType(ParameterSyntax originalParam, ParameterSyntax replacedParam)
{
var originalParamType = this.OriginalSemanticModel.GetDeclaredSymbol(originalParam).Type;
var replacedParamType = this.SpeculativeSemanticModel.GetDeclaredSymbol(replacedParam).Type;
return Equals(originalParamType, replacedParamType);
}
private bool ReplacementChangesSemanticsForNodes(
IEnumerable<IdentifierNameSyntax> originalIdentifierNodes,
IEnumerable<IdentifierNameSyntax> replacedIdentifierNodes,
SyntaxNode originalRoot)
{
Debug.Assert(originalIdentifierNodes.Any());
Debug.Assert(originalIdentifierNodes.Count() == replacedIdentifierNodes.Count());
var originalChildNodeEnum = originalIdentifierNodes.GetEnumerator();
var replacedChildNodeEnum = replacedIdentifierNodes.GetEnumerator();
while (originalChildNodeEnum.MoveNext())
{
replacedChildNodeEnum.MoveNext();
if (ReplacementChangesSemantics(originalChildNodeEnum.Current, replacedChildNodeEnum.Current, originalRoot, skipVerificationForCurrentNode: true))
{
return true;
}
}
return false;
}
protected override bool ReplacementChangesSemanticsForNodeLanguageSpecific(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode previousOriginalNode, SyntaxNode previousReplacedNode)
{
Debug.Assert(previousOriginalNode == null || previousOriginalNode.Parent == currentOriginalNode);
Debug.Assert(previousReplacedNode == null || previousReplacedNode.Parent == currentReplacedNode);
if (currentOriginalNode.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.ConstantPattern))
{
var expression = (ExpressionSyntax)currentReplacedNode.ChildNodes().First();
if (expression.WalkDownParentheses().IsKind(SyntaxKind.DefaultLiteralExpression))
{
// We can't have a default literal inside a case label or constant pattern.
return true;
}
}
if (currentOriginalNode is BinaryExpressionSyntax binaryExpression)
{
// If replacing the node will result in a broken binary expression, we won't remove it.
return ReplacementBreaksBinaryExpression(binaryExpression, (BinaryExpressionSyntax)currentReplacedNode);
}
else if (currentOriginalNode.Kind() == SyntaxKind.LogicalNotExpression)
{
return !TypesAreCompatible(((PrefixUnaryExpressionSyntax)currentOriginalNode).Operand, ((PrefixUnaryExpressionSyntax)currentReplacedNode).Operand);
}
else if (currentOriginalNode.Kind() == SyntaxKind.ConditionalAccessExpression)
{
return ReplacementBreaksConditionalAccessExpression((ConditionalAccessExpressionSyntax)currentOriginalNode, (ConditionalAccessExpressionSyntax)currentReplacedNode);
}
else if (currentOriginalNode is AssignmentExpressionSyntax assignment)
{
// If replacing the node will result in a broken assignment expression, we won't remove it.
return ReplacementBreaksAssignmentExpression(assignment, (AssignmentExpressionSyntax)currentReplacedNode);
}
else if (currentOriginalNode is SelectOrGroupClauseSyntax || currentOriginalNode is OrderingSyntax)
{
return !SymbolsAreCompatible(currentOriginalNode, currentReplacedNode);
}
else if (currentOriginalNode is QueryClauseSyntax queryClause)
{
return ReplacementBreaksQueryClause(queryClause, (QueryClauseSyntax)currentReplacedNode);
}
else if (currentOriginalNode.Kind() == SyntaxKind.VariableDeclarator)
{
// Heuristic: If replacing the node will result in changing the type of a local variable
// that is type-inferred, we won't remove it. It's possible to do this analysis, but it's
// very expensive and the benefit to the user is small.
var originalDeclarator = (VariableDeclaratorSyntax)currentOriginalNode;
var newDeclarator = (VariableDeclaratorSyntax)currentReplacedNode;
if (originalDeclarator.Initializer == null)
{
return newDeclarator.Initializer != null;
}
else if (newDeclarator.Initializer == null)
{
return true;
}
if (!originalDeclarator.Initializer.IsMissing &&
originalDeclarator.IsTypeInferred(this.OriginalSemanticModel) &&
!TypesAreCompatible(originalDeclarator.Initializer.Value, newDeclarator.Initializer.Value))
{
return true;
}
return false;
}
else if (currentOriginalNode.IsKind(SyntaxKind.ConditionalExpression, out ConditionalExpressionSyntax originalExpression))
{
var newExpression = (ConditionalExpressionSyntax)currentReplacedNode;
if (originalExpression.Condition != previousOriginalNode)
{
ExpressionSyntax originalOtherPartOfConditional, newOtherPartOfConditional;
if (originalExpression.WhenTrue == previousOriginalNode)
{
Debug.Assert(newExpression.WhenTrue == previousReplacedNode);
originalOtherPartOfConditional = originalExpression.WhenFalse;
newOtherPartOfConditional = newExpression.WhenFalse;
}
else
{
Debug.Assert(newExpression.WhenFalse == previousReplacedNode);
originalOtherPartOfConditional = originalExpression.WhenTrue;
newOtherPartOfConditional = newExpression.WhenTrue;
}
var originalExpressionTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression, this.CancellationToken);
var newExpressionTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression, this.CancellationToken);
var originalExpressionType = originalExpressionTypeInfo.Type;
var newExpressionType = newExpressionTypeInfo.Type;
// A conditional expression may have no type of it's own, but can be converted to a type if there's target-typed
// conditional expressions in play. For example:
//
// int? x = conditional ? (int?)trueValue : null;
//
// Once you remove the cast, the conditional has no type itself, but is being converted to int? by a conditional
// expression conversion.
if (newExpressionType == null &&
this.SpeculativeSemanticModel.GetConversion(newExpression, this.CancellationToken).IsConditionalExpression)
{
newExpressionType = newExpressionTypeInfo.ConvertedType;
}
if (originalExpressionType == null || newExpressionType == null)
{
// With the current implementation of the C# binder, this is impossible, but it's probably not wise to
// depend on an implementation detail of another layer.
return originalExpressionType != newExpressionType;
}
var originalConversion = this.OriginalSemanticModel.ClassifyConversion(originalOtherPartOfConditional, originalExpressionType);
var newConversion = this.SpeculativeSemanticModel.ClassifyConversion(newOtherPartOfConditional, newExpressionType);
// If this changes a boxing operation in one of the branches, we assume that semantics will change.
if (originalConversion.IsBoxing != newConversion.IsBoxing)
{
return true;
}
if (ReplacementBreaksBoxingInConditionalExpression(originalExpressionTypeInfo, newExpressionTypeInfo, (ExpressionSyntax)previousOriginalNode, (ExpressionSyntax)previousReplacedNode))
{
return true;
}
if (!ConversionsAreCompatible(originalConversion, newConversion))
{
return true;
}
}
}
else if (currentOriginalNode.IsKind(SyntaxKind.CaseSwitchLabel, out CaseSwitchLabelSyntax originalCaseSwitchLabel))
{
var newCaseSwitchLabel = (CaseSwitchLabelSyntax)currentReplacedNode;
// If case label is changing, then need to check if the semantics will change for the switch expression.
// e.g. if switch expression is "switch(x)" where "object x = 1f", then "case 1:" and "case (float) 1:" are different.
var originalCaseType = this.OriginalSemanticModel.GetTypeInfo(previousOriginalNode, this.CancellationToken).Type;
var newCaseType = this.SpeculativeSemanticModel.GetTypeInfo(previousReplacedNode, this.CancellationToken).Type;
if (Equals(originalCaseType, newCaseType))
return false;
var oldSwitchStatement = (SwitchStatementSyntax)originalCaseSwitchLabel.Parent.Parent;
var newSwitchStatement = (SwitchStatementSyntax)newCaseSwitchLabel.Parent.Parent;
var originalConversion = this.OriginalSemanticModel.ClassifyConversion(oldSwitchStatement.Expression, originalCaseType);
var newConversion = this.SpeculativeSemanticModel.ClassifyConversion(newSwitchStatement.Expression, newCaseType);
// if conversion only exists for either original or new, then semantics changed.
if (originalConversion.Exists != newConversion.Exists)
{
return true;
}
// Same conversion cannot result in both originalCaseType and newCaseType, which means the semantics changed
// (since originalCaseType != newCaseType)
return originalConversion == newConversion;
}
else if (currentOriginalNode.IsKind(SyntaxKind.SwitchStatement, out SwitchStatementSyntax originalSwitchStatement) &&
originalSwitchStatement.Expression == previousOriginalNode)
{
// Switch statement's expression changed, verify that the conversions from switch case labels to new switch
// expression type are not broken.
var newSwitchStatement = (SwitchStatementSyntax)currentReplacedNode;
var previousReplacedExpression = (ExpressionSyntax)previousReplacedNode;
// it is never legal to use `default/null` in a switch statement's expression.
if (previousReplacedExpression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression))
return true;
var originalSwitchLabels = originalSwitchStatement.Sections.SelectMany(section => section.Labels).ToArray();
var newSwitchLabels = newSwitchStatement.Sections.SelectMany(section => section.Labels).ToArray();
for (var i = 0; i < originalSwitchLabels.Length; i++)
{
if (originalSwitchLabels[i] is CaseSwitchLabelSyntax originalSwitchLabel &&
newSwitchLabels[i] is CaseSwitchLabelSyntax newSwitchLabel &&
!ImplicitConversionsAreCompatible(originalSwitchLabel.Value, newSwitchLabel.Value))
{
return true;
}
}
}
else if (currentOriginalNode.IsKind(SyntaxKind.SwitchExpression, out SwitchExpressionSyntax originalSwitchExpression) &&
originalSwitchExpression.GoverningExpression == previousOriginalNode)
{
var replacedSwitchExpression = (SwitchExpressionSyntax)currentReplacedNode;
// Switch expression's expression changed. Ensure it's the same type as before. If not, inference of
// the meaning of the patterns within can change.
var originalExprType = this.OriginalSemanticModel.GetTypeInfo(originalSwitchExpression.GoverningExpression, CancellationToken);
var replacedExprType = this.SpeculativeSemanticModel.GetTypeInfo(replacedSwitchExpression.GoverningExpression, CancellationToken);
if (!Equals(originalExprType.Type, replacedExprType.Type))
return true;
}
else if (currentOriginalNode.IsKind(SyntaxKind.IfStatement, out IfStatementSyntax originalIfStatement))
{
var newIfStatement = (IfStatementSyntax)currentReplacedNode;
if (originalIfStatement.Condition == previousOriginalNode)
{
// If condition changed, verify that original and replaced expression types are compatible.
if (!TypesAreCompatible(originalIfStatement.Condition, newIfStatement.Condition))
{
return true;
}
}
}
else if (currentOriginalNode is ConstructorInitializerSyntax originalCtorInitializer)
{
var newCtorInitializer = (ConstructorInitializerSyntax)currentReplacedNode;
return ReplacementBreaksConstructorInitializer(originalCtorInitializer, newCtorInitializer);
}
else if (currentOriginalNode.Kind() == SyntaxKind.CollectionInitializerExpression)
{
return previousOriginalNode != null &&
ReplacementBreaksCollectionInitializerAddMethod((ExpressionSyntax)previousOriginalNode, (ExpressionSyntax)previousReplacedNode);
}
else if (currentOriginalNode.Kind() == SyntaxKind.ImplicitArrayCreationExpression)
{
return !TypesAreCompatible((ImplicitArrayCreationExpressionSyntax)currentOriginalNode, (ImplicitArrayCreationExpressionSyntax)currentReplacedNode);
}
else if (currentOriginalNode is AnonymousObjectMemberDeclaratorSyntax originalAnonymousObjectMemberDeclarator)
{
var replacedAnonymousObjectMemberDeclarator = (AnonymousObjectMemberDeclaratorSyntax)currentReplacedNode;
return ReplacementBreaksAnonymousObjectMemberDeclarator(originalAnonymousObjectMemberDeclarator, replacedAnonymousObjectMemberDeclarator);
}
else if (currentOriginalNode.Kind() == SyntaxKind.DefaultExpression)
{
return !TypesAreCompatible((ExpressionSyntax)currentOriginalNode, (ExpressionSyntax)currentReplacedNode);
}
return false;
}
/// <summary>
/// Checks if the conversion might change the resultant boxed type.
/// Similar boxing checks are performed elsewhere, but in this case we need to perform the check on the entire conditional expression.
/// This will make sure the resultant cast is proper for the type of the conditional expression.
/// </summary>
private bool ReplacementBreaksBoxingInConditionalExpression(TypeInfo originalExpressionTypeInfo, TypeInfo newExpressionTypeInfo, ExpressionSyntax previousOriginalNode, ExpressionSyntax previousReplacedNode)
{
// If the resultant types are different and it is boxing to the converted type then semantics could be changing.
if (!Equals(originalExpressionTypeInfo.Type, newExpressionTypeInfo.Type))
{
var originalConvertedTypeConversion = this.OriginalSemanticModel.ClassifyConversion(previousOriginalNode, originalExpressionTypeInfo.ConvertedType);
var newExpressionConvertedTypeConversion = this.SpeculativeSemanticModel.ClassifyConversion(previousReplacedNode, newExpressionTypeInfo.ConvertedType);
if (originalConvertedTypeConversion.IsBoxing && newExpressionConvertedTypeConversion.IsBoxing)
{
return true;
}
}
return false;
}
private bool ReplacementBreaksAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax originalAnonymousObjectMemberDeclarator, AnonymousObjectMemberDeclaratorSyntax replacedAnonymousObjectMemberDeclarator)
{
var originalExpressionType = this.OriginalSemanticModel.GetTypeInfo(originalAnonymousObjectMemberDeclarator.Expression, this.CancellationToken).Type;
var newExpressionType = this.SpeculativeSemanticModel.GetTypeInfo(replacedAnonymousObjectMemberDeclarator.Expression, this.CancellationToken).Type;
return !object.Equals(originalExpressionType, newExpressionType);
}
private bool ReplacementBreaksConstructorInitializer(ConstructorInitializerSyntax ctorInitializer, ConstructorInitializerSyntax newCtorInitializer)
{
var originalSymbol = this.OriginalSemanticModel.GetSymbolInfo(ctorInitializer, CancellationToken).Symbol;
var newSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(newCtorInitializer, CancellationToken).Symbol;
return !SymbolsAreCompatible(originalSymbol, newSymbol);
}
private bool ReplacementBreaksCollectionInitializerAddMethod(ExpressionSyntax originalInitializer, ExpressionSyntax newInitializer)
{
var originalSymbol = this.OriginalSemanticModel.GetCollectionInitializerSymbolInfo(originalInitializer, CancellationToken).Symbol;
var newSymbol = this.SpeculativeSemanticModel.GetCollectionInitializerSymbolInfo(newInitializer, CancellationToken).Symbol;
return !SymbolsAreCompatible(originalSymbol, newSymbol);
}
protected override bool ExpressionMightReferenceMember(SyntaxNode node)
{
return node.IsKind(
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.SimpleMemberAccessExpression,
SyntaxKind.ImplicitElementAccess,
SyntaxKind.ObjectCreationExpression);
}
protected override ImmutableArray<ArgumentSyntax> GetArguments(ExpressionSyntax expression)
{
var argumentsList = GetArgumentList(expression);
return argumentsList != null ?
argumentsList.Arguments.AsImmutableOrEmpty() :
default;
}
private static BaseArgumentListSyntax GetArgumentList(ExpressionSyntax expression)
{
expression = expression.WalkDownParentheses();
return expression.Kind() switch
{
SyntaxKind.InvocationExpression => ((InvocationExpressionSyntax)expression).ArgumentList,
SyntaxKind.ObjectCreationExpression => ((ObjectCreationExpressionSyntax)expression).ArgumentList,
SyntaxKind.ElementAccessExpression => ((ElementAccessExpressionSyntax)expression).ArgumentList,
_ => (BaseArgumentListSyntax)null,
};
}
protected override ExpressionSyntax GetReceiver(ExpressionSyntax expression)
{
expression = expression.WalkDownParentheses();
switch (expression.Kind())
{
case SyntaxKind.SimpleMemberAccessExpression:
return ((MemberAccessExpressionSyntax)expression).Expression;
case SyntaxKind.InvocationExpression:
{
var result = ((InvocationExpressionSyntax)expression).Expression;
if (result.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
return GetReceiver(result);
}
return result;
}
case SyntaxKind.ElementAccessExpression:
{
var result = ((ElementAccessExpressionSyntax)expression).Expression;
if (result.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
result = GetReceiver(result);
}
return result;
}
default:
return null;
}
}
protected override bool IsInNamespaceOrTypeContext(ExpressionSyntax node)
=> SyntaxFacts.IsInNamespaceOrTypeContext(node);
protected override ExpressionSyntax GetForEachStatementExpression(CommonForEachStatementSyntax forEachStatement)
=> forEachStatement.Expression;
protected override ExpressionSyntax GetThrowStatementExpression(ThrowStatementSyntax throwStatement)
=> throwStatement.Expression;
protected override bool IsForEachTypeInferred(CommonForEachStatementSyntax forEachStatement, SemanticModel semanticModel)
=> forEachStatement.IsTypeInferred(semanticModel);
protected override bool IsParenthesizedExpression(SyntaxNode node)
=> node.IsKind(SyntaxKind.ParenthesizedExpression);
protected override bool IsNamedArgument(ArgumentSyntax argument)
=> argument.NameColon != null && !argument.NameColon.IsMissing;
protected override string GetNamedArgumentIdentifierValueText(ArgumentSyntax argument)
=> argument.NameColon.Name.Identifier.ValueText;
private bool ReplacementBreaksBinaryExpression(BinaryExpressionSyntax binaryExpression, BinaryExpressionSyntax newBinaryExpression)
{
if ((binaryExpression.IsKind(SyntaxKind.AsExpression) ||
binaryExpression.IsKind(SyntaxKind.IsExpression)) &&
ReplacementBreaksIsOrAsExpression(binaryExpression, newBinaryExpression))
{
return true;
}
return !SymbolsAreCompatible(binaryExpression, newBinaryExpression) ||
!TypesAreCompatible(binaryExpression, newBinaryExpression) ||
!ImplicitConversionsAreCompatible(binaryExpression, newBinaryExpression);
}
private bool ReplacementBreaksConditionalAccessExpression(ConditionalAccessExpressionSyntax conditionalAccessExpression, ConditionalAccessExpressionSyntax newConditionalAccessExpression)
{
return !SymbolsAreCompatible(conditionalAccessExpression, newConditionalAccessExpression) ||
!TypesAreCompatible(conditionalAccessExpression, newConditionalAccessExpression) ||
!SymbolsAreCompatible(conditionalAccessExpression.WhenNotNull, newConditionalAccessExpression.WhenNotNull) ||
!TypesAreCompatible(conditionalAccessExpression.WhenNotNull, newConditionalAccessExpression.WhenNotNull);
}
private bool ReplacementBreaksIsOrAsExpression(BinaryExpressionSyntax originalIsOrAsExpression, BinaryExpressionSyntax newIsOrAsExpression)
{
// Special case: Lambda expressions and anonymous delegates cannot appear
// on the left-side of an 'is' or 'as' cast. We can handle this case syntactically.
if (!originalIsOrAsExpression.Left.WalkDownParentheses().IsAnyLambdaOrAnonymousMethod() &&
newIsOrAsExpression.Left.WalkDownParentheses().IsAnyLambdaOrAnonymousMethod())
{
return true;
}
var originalConvertedType = this.OriginalSemanticModel.GetTypeInfo(originalIsOrAsExpression.Right).Type;
var newConvertedType = this.SpeculativeSemanticModel.GetTypeInfo(newIsOrAsExpression.Right).Type;
if (originalConvertedType == null || newConvertedType == null)
{
return originalConvertedType != newConvertedType;
}
var originalConversion = this.OriginalSemanticModel.ClassifyConversion(originalIsOrAsExpression.Left, originalConvertedType, isExplicitInSource: true);
var newConversion = this.SpeculativeSemanticModel.ClassifyConversion(newIsOrAsExpression.Left, newConvertedType, isExplicitInSource: true);
// Is and As operators do not consider any user-defined operators, just ensure that the conversion exists.
return originalConversion.Exists != newConversion.Exists;
}
private bool ReplacementBreaksAssignmentExpression(AssignmentExpressionSyntax assignmentExpression, AssignmentExpressionSyntax newAssignmentExpression)
{
if (assignmentExpression.IsCompoundAssignExpression() &&
assignmentExpression.Kind() != SyntaxKind.LeftShiftAssignmentExpression &&
assignmentExpression.Kind() != SyntaxKind.RightShiftAssignmentExpression &&
ReplacementBreaksCompoundAssignment(assignmentExpression.Left, assignmentExpression.Right, newAssignmentExpression.Left, newAssignmentExpression.Right))
{
return true;
}
return !SymbolsAreCompatible(assignmentExpression, newAssignmentExpression) ||
!TypesAreCompatible(assignmentExpression, newAssignmentExpression) ||
!ImplicitConversionsAreCompatible(assignmentExpression, newAssignmentExpression);
}
private bool ReplacementBreaksQueryClause(QueryClauseSyntax originalClause, QueryClauseSyntax newClause)
{
// Ensure QueryClauseInfos are compatible.
var originalClauseInfo = this.OriginalSemanticModel.GetQueryClauseInfo(originalClause, this.CancellationToken);
var newClauseInfo = this.SpeculativeSemanticModel.GetQueryClauseInfo(newClause, this.CancellationToken);
return !SymbolInfosAreCompatible(originalClauseInfo.CastInfo, newClauseInfo.CastInfo) ||
!SymbolInfosAreCompatible(originalClauseInfo.OperationInfo, newClauseInfo.OperationInfo);
}
protected override bool ReplacementIntroducesErrorType(ExpressionSyntax originalExpression, ExpressionSyntax newExpression)
{
// The base implementation will see that the type of the new expression may potentially change to null,
// because the expression has no type but can be converted to a conditional expression type. In that case,
// we don't want to consider the null type to be an error type.
if (newExpression.IsKind(SyntaxKind.ConditionalExpression) &&
ConditionalExpressionConversionsAreAllowed(newExpression) &&
this.SpeculativeSemanticModel.GetConversion(newExpression).IsConditionalExpression)
{
return false;
}
return base.ReplacementIntroducesErrorType(originalExpression, newExpression);
}
protected override bool ConversionsAreCompatible(SemanticModel originalModel, ExpressionSyntax originalExpression, SemanticModel newModel, ExpressionSyntax newExpression)
{
var originalConversion = originalModel.GetConversion(originalExpression);
var newConversion = newModel.GetConversion(newExpression);
if (originalExpression.IsKind(SyntaxKind.ConditionalExpression) &&
newExpression.IsKind(SyntaxKind.ConditionalExpression))
{
if (newConversion.IsConditionalExpression)
{
// If we went from a non-conditional-conversion to a conditional-conversion (i.e. by removing a
// cast), then that is always an error before CSharp9, and should not be allowed.
if (!originalConversion.IsConditionalExpression && !ConditionalExpressionConversionsAreAllowed(originalExpression))
return false;
// If the only change to the conversion here is the introduction of a conditional expression conversion,
// that means types didn't really change in a meaningful way.
if (originalConversion.IsIdentity)
return true;
}
}
return ConversionsAreCompatible(originalConversion, newConversion);
}
private static bool ConditionalExpressionConversionsAreAllowed(ExpressionSyntax originalExpression)
=> ((CSharpParseOptions)originalExpression.SyntaxTree.Options).LanguageVersion >= LanguageVersion.CSharp9;
protected override bool ConversionsAreCompatible(ExpressionSyntax originalExpression, ITypeSymbol originalTargetType, ExpressionSyntax newExpression, ITypeSymbol newTargetType)
{
this.GetConversions(originalExpression, originalTargetType, newExpression, newTargetType, out var originalConversion, out var newConversion);
if (originalConversion == null || newConversion == null)
{
return false;
}
return ConversionsAreCompatible(originalConversion.Value, newConversion.Value);
}
private bool ConversionsAreCompatible(Conversion originalConversion, Conversion newConversion)
{
if (originalConversion.Exists != newConversion.Exists ||
(!originalConversion.IsExplicit && newConversion.IsExplicit))
{
return false;
}
var originalIsUserDefined = originalConversion.IsUserDefined;
var newIsUserDefined = newConversion.IsUserDefined;
if (originalIsUserDefined != newIsUserDefined)
{
return false;
}
if (originalIsUserDefined || originalConversion.MethodSymbol != null || newConversion.MethodSymbol != null)
{
return SymbolsAreCompatible(originalConversion.MethodSymbol, newConversion.MethodSymbol);
}
return true;
}
protected override bool ForEachConversionsAreCompatible(SemanticModel originalModel, CommonForEachStatementSyntax originalForEach, SemanticModel newModel, CommonForEachStatementSyntax newForEach)
{
var originalInfo = originalModel.GetForEachStatementInfo(originalForEach);
var newInfo = newModel.GetForEachStatementInfo(newForEach);
return ConversionsAreCompatible(originalInfo.CurrentConversion, newInfo.CurrentConversion)
&& ConversionsAreCompatible(originalInfo.ElementConversion, newInfo.ElementConversion);
}
protected override void GetForEachSymbols(SemanticModel model, CommonForEachStatementSyntax forEach, out IMethodSymbol getEnumeratorMethod, out ITypeSymbol elementType)
{
var info = model.GetForEachStatementInfo(forEach);
getEnumeratorMethod = info.GetEnumeratorMethod;
elementType = info.ElementType;
}
protected override bool IsReferenceConversion(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
=> compilation.ClassifyConversion(sourceType, targetType).IsReference;
protected override Conversion ClassifyConversion(SemanticModel model, ExpressionSyntax expression, ITypeSymbol targetType) =>
model.ClassifyConversion(expression, targetType);
protected override Conversion ClassifyConversion(SemanticModel model, ITypeSymbol originalType, ITypeSymbol targetType) =>
model.Compilation.ClassifyConversion(originalType, targetType);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Utilities
{
/// <summary>
/// Helper class to analyze the semantic effects of a speculated syntax node replacement on the parenting nodes.
/// Given an expression node from a syntax tree and a new expression from a different syntax tree,
/// it replaces the expression with the new expression to create a speculated syntax tree.
/// It uses the original tree's semantic model to create a speculative semantic model and verifies that
/// the syntax replacement doesn't break the semantics of any parenting nodes of the original expression.
/// </summary>
internal class SpeculationAnalyzer : AbstractSpeculationAnalyzer<
ExpressionSyntax,
TypeSyntax,
AttributeSyntax,
ArgumentSyntax,
CommonForEachStatementSyntax,
ThrowStatementSyntax,
Conversion>
{
/// <summary>
/// Creates a semantic analyzer for speculative syntax replacement.
/// </summary>
/// <param name="expression">Original expression to be replaced.</param>
/// <param name="newExpression">New expression to replace the original expression.</param>
/// <param name="semanticModel">Semantic model of <paramref name="expression"/> node's syntax tree.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="skipVerificationForReplacedNode">
/// True if semantic analysis should be skipped for the replaced node and performed starting from parent of the original and replaced nodes.
/// This could be the case when custom verifications are required to be done by the caller or
/// semantics of the replaced expression are different from the original expression.
/// </param>
/// <param name="failOnOverloadResolutionFailuresInOriginalCode">
/// True if semantic analysis should fail when any of the invocation expression ancestors of <paramref name="expression"/> in original code has overload resolution failures.
/// </param>
public SpeculationAnalyzer(
ExpressionSyntax expression,
ExpressionSyntax newExpression,
SemanticModel semanticModel,
CancellationToken cancellationToken,
bool skipVerificationForReplacedNode = false,
bool failOnOverloadResolutionFailuresInOriginalCode = false)
: base(expression, newExpression, semanticModel, cancellationToken, skipVerificationForReplacedNode, failOnOverloadResolutionFailuresInOriginalCode)
{
}
protected override SyntaxNode GetSemanticRootForSpeculation(ExpressionSyntax expression)
{
Debug.Assert(expression != null);
var parentNodeToSpeculate = expression
.AncestorsAndSelf(ascendOutOfTrivia: false)
.Where(node => CanSpeculateOnNode(node))
.LastOrDefault();
return parentNodeToSpeculate ?? expression;
}
public static bool CanSpeculateOnNode(SyntaxNode node)
{
return (node is StatementSyntax && node.Kind() != SyntaxKind.Block) ||
node is TypeSyntax ||
node is CrefSyntax ||
node.Kind() == SyntaxKind.Attribute ||
node.Kind() == SyntaxKind.ThisConstructorInitializer ||
node.Kind() == SyntaxKind.BaseConstructorInitializer ||
node.Kind() == SyntaxKind.EqualsValueClause ||
node.Kind() == SyntaxKind.ArrowExpressionClause;
}
protected override void ValidateSpeculativeSemanticModel(SemanticModel speculativeSemanticModel, SyntaxNode nodeToSpeculate)
{
Debug.Assert(speculativeSemanticModel != null ||
nodeToSpeculate is ExpressionSyntax ||
this.SemanticRootOfOriginalExpression.GetAncestors().Any(node => node.IsKind(SyntaxKind.UnknownAccessorDeclaration) ||
node.IsKind(SyntaxKind.IncompleteMember) ||
node.IsKind(SyntaxKind.BracketedArgumentList)),
"SemanticModel.TryGetSpeculativeSemanticModel() API returned false.");
}
protected override SemanticModel CreateSpeculativeSemanticModel(SyntaxNode originalNode, SyntaxNode nodeToSpeculate, SemanticModel semanticModel)
=> CreateSpeculativeSemanticModelForNode(originalNode, nodeToSpeculate, semanticModel);
public static SemanticModel CreateSpeculativeSemanticModelForNode(SyntaxNode originalNode, SyntaxNode nodeToSpeculate, SemanticModel semanticModel)
{
var position = originalNode.SpanStart;
var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(originalNode as ExpressionSyntax);
return CreateSpeculativeSemanticModelForNode(nodeToSpeculate, semanticModel, position, isInNamespaceOrTypeContext);
}
public static SemanticModel CreateSpeculativeSemanticModelForNode(SyntaxNode nodeToSpeculate, SemanticModel semanticModel, int position, bool isInNamespaceOrTypeContext)
{
if (semanticModel.IsSpeculativeSemanticModel)
{
// Chaining speculative model not supported, speculate off the original model.
Debug.Assert(semanticModel.ParentModel != null);
Debug.Assert(!semanticModel.ParentModel.IsSpeculativeSemanticModel);
position = semanticModel.OriginalPositionForSpeculation;
semanticModel = semanticModel.ParentModel;
}
SemanticModel speculativeModel;
if (nodeToSpeculate is StatementSyntax statementNode)
{
semanticModel.TryGetSpeculativeSemanticModel(position, statementNode, out speculativeModel);
return speculativeModel;
}
if (nodeToSpeculate is TypeSyntax typeNode)
{
var bindingOption = isInNamespaceOrTypeContext ?
SpeculativeBindingOption.BindAsTypeOrNamespace :
SpeculativeBindingOption.BindAsExpression;
semanticModel.TryGetSpeculativeSemanticModel(position, typeNode, out speculativeModel, bindingOption);
return speculativeModel;
}
if (nodeToSpeculate is CrefSyntax cref)
{
semanticModel.TryGetSpeculativeSemanticModel(position, cref, out speculativeModel);
return speculativeModel;
}
switch (nodeToSpeculate.Kind())
{
case SyntaxKind.Attribute:
semanticModel.TryGetSpeculativeSemanticModel(position, (AttributeSyntax)nodeToSpeculate, out speculativeModel);
return speculativeModel;
case SyntaxKind.BaseConstructorInitializer:
case SyntaxKind.ThisConstructorInitializer:
semanticModel.TryGetSpeculativeSemanticModel(position, (ConstructorInitializerSyntax)nodeToSpeculate, out speculativeModel);
return speculativeModel;
case SyntaxKind.EqualsValueClause:
semanticModel.TryGetSpeculativeSemanticModel(position, (EqualsValueClauseSyntax)nodeToSpeculate, out speculativeModel);
return speculativeModel;
case SyntaxKind.ArrowExpressionClause:
semanticModel.TryGetSpeculativeSemanticModel(position, (ArrowExpressionClauseSyntax)nodeToSpeculate, out speculativeModel);
return speculativeModel;
}
// CONSIDER: Do we care about this case?
Debug.Assert(nodeToSpeculate is ExpressionSyntax);
return null;
}
/// <summary>
/// Determines whether performing the syntax replacement in one of the sibling nodes of the given lambda expressions will change the lambda binding semantics.
/// This is done by first determining the lambda parameters whose type differs in the replaced lambda node.
/// For each of these parameters, we find the descendant identifier name nodes in the lambda body and check if semantics of any of the parenting nodes of these
/// identifier nodes have changed in the replaced lambda.
/// </summary>
public bool ReplacementChangesSemanticsOfUnchangedLambda(ExpressionSyntax originalLambda, ExpressionSyntax replacedLambda)
{
originalLambda = originalLambda.WalkDownParentheses();
replacedLambda = replacedLambda.WalkDownParentheses();
SyntaxNode originalLambdaBody, replacedLambdaBody;
List<string> paramNames;
switch (originalLambda.Kind())
{
case SyntaxKind.ParenthesizedLambdaExpression:
{
var originalParenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)originalLambda;
var originalParams = originalParenthesizedLambda.ParameterList.Parameters;
if (!originalParams.Any())
{
return false;
}
var replacedParenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)replacedLambda;
var replacedParams = replacedParenthesizedLambda.ParameterList.Parameters;
Debug.Assert(originalParams.Count == replacedParams.Count);
paramNames = new List<string>();
for (var i = 0; i < originalParams.Count; i++)
{
var originalParam = originalParams[i];
var replacedParam = replacedParams[i];
if (!HaveSameParameterType(originalParam, replacedParam))
{
paramNames.Add(originalParam.Identifier.ValueText);
}
}
if (!paramNames.Any())
{
return false;
}
originalLambdaBody = originalParenthesizedLambda.Body;
replacedLambdaBody = replacedParenthesizedLambda.Body;
break;
}
case SyntaxKind.SimpleLambdaExpression:
{
var originalSimpleLambda = (SimpleLambdaExpressionSyntax)originalLambda;
var replacedSimpleLambda = (SimpleLambdaExpressionSyntax)replacedLambda;
if (HaveSameParameterType(originalSimpleLambda.Parameter, replacedSimpleLambda.Parameter))
{
return false;
}
paramNames = new List<string>() { originalSimpleLambda.Parameter.Identifier.ValueText };
originalLambdaBody = originalSimpleLambda.Body;
replacedLambdaBody = replacedSimpleLambda.Body;
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(originalLambda.Kind());
}
var originalIdentifierNodes = originalLambdaBody.DescendantNodes().OfType<IdentifierNameSyntax>().Where(node => paramNames.Contains(node.Identifier.ValueText));
if (!originalIdentifierNodes.Any())
{
return false;
}
var replacedIdentifierNodes = replacedLambdaBody.DescendantNodes().OfType<IdentifierNameSyntax>().Where(node => paramNames.Contains(node.Identifier.ValueText));
return ReplacementChangesSemanticsForNodes(originalIdentifierNodes, replacedIdentifierNodes, originalLambdaBody);
}
private bool HaveSameParameterType(ParameterSyntax originalParam, ParameterSyntax replacedParam)
{
var originalParamType = this.OriginalSemanticModel.GetDeclaredSymbol(originalParam).Type;
var replacedParamType = this.SpeculativeSemanticModel.GetDeclaredSymbol(replacedParam).Type;
return Equals(originalParamType, replacedParamType);
}
private bool ReplacementChangesSemanticsForNodes(
IEnumerable<IdentifierNameSyntax> originalIdentifierNodes,
IEnumerable<IdentifierNameSyntax> replacedIdentifierNodes,
SyntaxNode originalRoot)
{
Debug.Assert(originalIdentifierNodes.Any());
Debug.Assert(originalIdentifierNodes.Count() == replacedIdentifierNodes.Count());
var originalChildNodeEnum = originalIdentifierNodes.GetEnumerator();
var replacedChildNodeEnum = replacedIdentifierNodes.GetEnumerator();
while (originalChildNodeEnum.MoveNext())
{
replacedChildNodeEnum.MoveNext();
if (ReplacementChangesSemantics(originalChildNodeEnum.Current, replacedChildNodeEnum.Current, originalRoot, skipVerificationForCurrentNode: true))
{
return true;
}
}
return false;
}
protected override bool ReplacementChangesSemanticsForNodeLanguageSpecific(SyntaxNode currentOriginalNode, SyntaxNode currentReplacedNode, SyntaxNode previousOriginalNode, SyntaxNode previousReplacedNode)
{
Debug.Assert(previousOriginalNode == null || previousOriginalNode.Parent == currentOriginalNode);
Debug.Assert(previousReplacedNode == null || previousReplacedNode.Parent == currentReplacedNode);
if (currentOriginalNode.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.ConstantPattern))
{
var expression = (ExpressionSyntax)currentReplacedNode.ChildNodes().First();
if (expression.WalkDownParentheses().IsKind(SyntaxKind.DefaultLiteralExpression))
{
// We can't have a default literal inside a case label or constant pattern.
return true;
}
}
if (currentOriginalNode is BinaryExpressionSyntax binaryExpression)
{
// If replacing the node will result in a broken binary expression, we won't remove it.
return ReplacementBreaksBinaryExpression(binaryExpression, (BinaryExpressionSyntax)currentReplacedNode);
}
else if (currentOriginalNode.Kind() == SyntaxKind.LogicalNotExpression)
{
return !TypesAreCompatible(((PrefixUnaryExpressionSyntax)currentOriginalNode).Operand, ((PrefixUnaryExpressionSyntax)currentReplacedNode).Operand);
}
else if (currentOriginalNode.Kind() == SyntaxKind.ConditionalAccessExpression)
{
return ReplacementBreaksConditionalAccessExpression((ConditionalAccessExpressionSyntax)currentOriginalNode, (ConditionalAccessExpressionSyntax)currentReplacedNode);
}
else if (currentOriginalNode is AssignmentExpressionSyntax assignment)
{
// If replacing the node will result in a broken assignment expression, we won't remove it.
return ReplacementBreaksAssignmentExpression(assignment, (AssignmentExpressionSyntax)currentReplacedNode);
}
else if (currentOriginalNode is SelectOrGroupClauseSyntax || currentOriginalNode is OrderingSyntax)
{
return !SymbolsAreCompatible(currentOriginalNode, currentReplacedNode);
}
else if (currentOriginalNode is QueryClauseSyntax queryClause)
{
return ReplacementBreaksQueryClause(queryClause, (QueryClauseSyntax)currentReplacedNode);
}
else if (currentOriginalNode.Kind() == SyntaxKind.VariableDeclarator)
{
// Heuristic: If replacing the node will result in changing the type of a local variable
// that is type-inferred, we won't remove it. It's possible to do this analysis, but it's
// very expensive and the benefit to the user is small.
var originalDeclarator = (VariableDeclaratorSyntax)currentOriginalNode;
var newDeclarator = (VariableDeclaratorSyntax)currentReplacedNode;
if (originalDeclarator.Initializer == null)
{
return newDeclarator.Initializer != null;
}
else if (newDeclarator.Initializer == null)
{
return true;
}
if (!originalDeclarator.Initializer.IsMissing &&
originalDeclarator.IsTypeInferred(this.OriginalSemanticModel) &&
!TypesAreCompatible(originalDeclarator.Initializer.Value, newDeclarator.Initializer.Value))
{
return true;
}
return false;
}
else if (currentOriginalNode.IsKind(SyntaxKind.ConditionalExpression, out ConditionalExpressionSyntax originalExpression))
{
var newExpression = (ConditionalExpressionSyntax)currentReplacedNode;
if (originalExpression.Condition != previousOriginalNode)
{
ExpressionSyntax originalOtherPartOfConditional, newOtherPartOfConditional;
if (originalExpression.WhenTrue == previousOriginalNode)
{
Debug.Assert(newExpression.WhenTrue == previousReplacedNode);
originalOtherPartOfConditional = originalExpression.WhenFalse;
newOtherPartOfConditional = newExpression.WhenFalse;
}
else
{
Debug.Assert(newExpression.WhenFalse == previousReplacedNode);
originalOtherPartOfConditional = originalExpression.WhenTrue;
newOtherPartOfConditional = newExpression.WhenTrue;
}
var originalExpressionTypeInfo = this.OriginalSemanticModel.GetTypeInfo(originalExpression, this.CancellationToken);
var newExpressionTypeInfo = this.SpeculativeSemanticModel.GetTypeInfo(newExpression, this.CancellationToken);
var originalExpressionType = originalExpressionTypeInfo.Type;
var newExpressionType = newExpressionTypeInfo.Type;
// A conditional expression may have no type of it's own, but can be converted to a type if there's target-typed
// conditional expressions in play. For example:
//
// int? x = conditional ? (int?)trueValue : null;
//
// Once you remove the cast, the conditional has no type itself, but is being converted to int? by a conditional
// expression conversion.
if (newExpressionType == null &&
this.SpeculativeSemanticModel.GetConversion(newExpression, this.CancellationToken).IsConditionalExpression)
{
newExpressionType = newExpressionTypeInfo.ConvertedType;
}
if (originalExpressionType == null || newExpressionType == null)
{
// With the current implementation of the C# binder, this is impossible, but it's probably not wise to
// depend on an implementation detail of another layer.
return originalExpressionType != newExpressionType;
}
var originalConversion = this.OriginalSemanticModel.ClassifyConversion(originalOtherPartOfConditional, originalExpressionType);
var newConversion = this.SpeculativeSemanticModel.ClassifyConversion(newOtherPartOfConditional, newExpressionType);
// If this changes a boxing operation in one of the branches, we assume that semantics will change.
if (originalConversion.IsBoxing != newConversion.IsBoxing)
{
return true;
}
if (ReplacementBreaksBoxingInConditionalExpression(originalExpressionTypeInfo, newExpressionTypeInfo, (ExpressionSyntax)previousOriginalNode, (ExpressionSyntax)previousReplacedNode))
{
return true;
}
if (!ConversionsAreCompatible(originalConversion, newConversion))
{
return true;
}
}
}
else if (currentOriginalNode.IsKind(SyntaxKind.CaseSwitchLabel, out CaseSwitchLabelSyntax originalCaseSwitchLabel))
{
var newCaseSwitchLabel = (CaseSwitchLabelSyntax)currentReplacedNode;
// If case label is changing, then need to check if the semantics will change for the switch expression.
// e.g. if switch expression is "switch(x)" where "object x = 1f", then "case 1:" and "case (float) 1:" are different.
var originalCaseType = this.OriginalSemanticModel.GetTypeInfo(previousOriginalNode, this.CancellationToken).Type;
var newCaseType = this.SpeculativeSemanticModel.GetTypeInfo(previousReplacedNode, this.CancellationToken).Type;
if (Equals(originalCaseType, newCaseType))
return false;
var oldSwitchStatement = (SwitchStatementSyntax)originalCaseSwitchLabel.Parent.Parent;
var newSwitchStatement = (SwitchStatementSyntax)newCaseSwitchLabel.Parent.Parent;
var originalConversion = this.OriginalSemanticModel.ClassifyConversion(oldSwitchStatement.Expression, originalCaseType);
var newConversion = this.SpeculativeSemanticModel.ClassifyConversion(newSwitchStatement.Expression, newCaseType);
// if conversion only exists for either original or new, then semantics changed.
if (originalConversion.Exists != newConversion.Exists)
{
return true;
}
// Same conversion cannot result in both originalCaseType and newCaseType, which means the semantics changed
// (since originalCaseType != newCaseType)
return originalConversion == newConversion;
}
else if (currentOriginalNode.IsKind(SyntaxKind.SwitchStatement, out SwitchStatementSyntax originalSwitchStatement) &&
originalSwitchStatement.Expression == previousOriginalNode)
{
// Switch statement's expression changed, verify that the conversions from switch case labels to new switch
// expression type are not broken.
var newSwitchStatement = (SwitchStatementSyntax)currentReplacedNode;
var previousReplacedExpression = (ExpressionSyntax)previousReplacedNode;
// it is never legal to use `default/null` in a switch statement's expression.
if (previousReplacedExpression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression))
return true;
var originalSwitchLabels = originalSwitchStatement.Sections.SelectMany(section => section.Labels).ToArray();
var newSwitchLabels = newSwitchStatement.Sections.SelectMany(section => section.Labels).ToArray();
for (var i = 0; i < originalSwitchLabels.Length; i++)
{
if (originalSwitchLabels[i] is CaseSwitchLabelSyntax originalSwitchLabel &&
newSwitchLabels[i] is CaseSwitchLabelSyntax newSwitchLabel &&
!ImplicitConversionsAreCompatible(originalSwitchLabel.Value, newSwitchLabel.Value))
{
return true;
}
}
}
else if (currentOriginalNode.IsKind(SyntaxKind.SwitchExpression, out SwitchExpressionSyntax originalSwitchExpression) &&
originalSwitchExpression.GoverningExpression == previousOriginalNode)
{
var replacedSwitchExpression = (SwitchExpressionSyntax)currentReplacedNode;
// Switch expression's expression changed. Ensure it's the same type as before. If not, inference of
// the meaning of the patterns within can change.
var originalExprType = this.OriginalSemanticModel.GetTypeInfo(originalSwitchExpression.GoverningExpression, CancellationToken);
var replacedExprType = this.SpeculativeSemanticModel.GetTypeInfo(replacedSwitchExpression.GoverningExpression, CancellationToken);
if (!Equals(originalExprType.Type, replacedExprType.Type))
return true;
}
else if (currentOriginalNode.IsKind(SyntaxKind.IfStatement, out IfStatementSyntax originalIfStatement))
{
var newIfStatement = (IfStatementSyntax)currentReplacedNode;
if (originalIfStatement.Condition == previousOriginalNode)
{
// If condition changed, verify that original and replaced expression types are compatible.
if (!TypesAreCompatible(originalIfStatement.Condition, newIfStatement.Condition))
{
return true;
}
}
}
else if (currentOriginalNode is ConstructorInitializerSyntax originalCtorInitializer)
{
var newCtorInitializer = (ConstructorInitializerSyntax)currentReplacedNode;
return ReplacementBreaksConstructorInitializer(originalCtorInitializer, newCtorInitializer);
}
else if (currentOriginalNode.Kind() == SyntaxKind.CollectionInitializerExpression)
{
return previousOriginalNode != null &&
ReplacementBreaksCollectionInitializerAddMethod((ExpressionSyntax)previousOriginalNode, (ExpressionSyntax)previousReplacedNode);
}
else if (currentOriginalNode.Kind() == SyntaxKind.ImplicitArrayCreationExpression)
{
return !TypesAreCompatible((ImplicitArrayCreationExpressionSyntax)currentOriginalNode, (ImplicitArrayCreationExpressionSyntax)currentReplacedNode);
}
else if (currentOriginalNode is AnonymousObjectMemberDeclaratorSyntax originalAnonymousObjectMemberDeclarator)
{
var replacedAnonymousObjectMemberDeclarator = (AnonymousObjectMemberDeclaratorSyntax)currentReplacedNode;
return ReplacementBreaksAnonymousObjectMemberDeclarator(originalAnonymousObjectMemberDeclarator, replacedAnonymousObjectMemberDeclarator);
}
else if (currentOriginalNode.Kind() == SyntaxKind.DefaultExpression)
{
return !TypesAreCompatible((ExpressionSyntax)currentOriginalNode, (ExpressionSyntax)currentReplacedNode);
}
return false;
}
/// <summary>
/// Checks if the conversion might change the resultant boxed type.
/// Similar boxing checks are performed elsewhere, but in this case we need to perform the check on the entire conditional expression.
/// This will make sure the resultant cast is proper for the type of the conditional expression.
/// </summary>
private bool ReplacementBreaksBoxingInConditionalExpression(TypeInfo originalExpressionTypeInfo, TypeInfo newExpressionTypeInfo, ExpressionSyntax previousOriginalNode, ExpressionSyntax previousReplacedNode)
{
// If the resultant types are different and it is boxing to the converted type then semantics could be changing.
if (!Equals(originalExpressionTypeInfo.Type, newExpressionTypeInfo.Type))
{
var originalConvertedTypeConversion = this.OriginalSemanticModel.ClassifyConversion(previousOriginalNode, originalExpressionTypeInfo.ConvertedType);
var newExpressionConvertedTypeConversion = this.SpeculativeSemanticModel.ClassifyConversion(previousReplacedNode, newExpressionTypeInfo.ConvertedType);
if (originalConvertedTypeConversion.IsBoxing && newExpressionConvertedTypeConversion.IsBoxing)
{
return true;
}
}
return false;
}
private bool ReplacementBreaksAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax originalAnonymousObjectMemberDeclarator, AnonymousObjectMemberDeclaratorSyntax replacedAnonymousObjectMemberDeclarator)
{
var originalExpressionType = this.OriginalSemanticModel.GetTypeInfo(originalAnonymousObjectMemberDeclarator.Expression, this.CancellationToken).Type;
var newExpressionType = this.SpeculativeSemanticModel.GetTypeInfo(replacedAnonymousObjectMemberDeclarator.Expression, this.CancellationToken).Type;
return !object.Equals(originalExpressionType, newExpressionType);
}
private bool ReplacementBreaksConstructorInitializer(ConstructorInitializerSyntax ctorInitializer, ConstructorInitializerSyntax newCtorInitializer)
{
var originalSymbol = this.OriginalSemanticModel.GetSymbolInfo(ctorInitializer, CancellationToken).Symbol;
var newSymbol = this.SpeculativeSemanticModel.GetSymbolInfo(newCtorInitializer, CancellationToken).Symbol;
return !SymbolsAreCompatible(originalSymbol, newSymbol);
}
private bool ReplacementBreaksCollectionInitializerAddMethod(ExpressionSyntax originalInitializer, ExpressionSyntax newInitializer)
{
var originalSymbol = this.OriginalSemanticModel.GetCollectionInitializerSymbolInfo(originalInitializer, CancellationToken).Symbol;
var newSymbol = this.SpeculativeSemanticModel.GetCollectionInitializerSymbolInfo(newInitializer, CancellationToken).Symbol;
return !SymbolsAreCompatible(originalSymbol, newSymbol);
}
protected override bool ExpressionMightReferenceMember(SyntaxNode node)
{
return node.IsKind(
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.SimpleMemberAccessExpression,
SyntaxKind.ImplicitElementAccess,
SyntaxKind.ObjectCreationExpression);
}
protected override ImmutableArray<ArgumentSyntax> GetArguments(ExpressionSyntax expression)
{
var argumentsList = GetArgumentList(expression);
return argumentsList != null ?
argumentsList.Arguments.AsImmutableOrEmpty() :
default;
}
private static BaseArgumentListSyntax GetArgumentList(ExpressionSyntax expression)
{
expression = expression.WalkDownParentheses();
return expression.Kind() switch
{
SyntaxKind.InvocationExpression => ((InvocationExpressionSyntax)expression).ArgumentList,
SyntaxKind.ObjectCreationExpression => ((ObjectCreationExpressionSyntax)expression).ArgumentList,
SyntaxKind.ElementAccessExpression => ((ElementAccessExpressionSyntax)expression).ArgumentList,
_ => (BaseArgumentListSyntax)null,
};
}
protected override ExpressionSyntax GetReceiver(ExpressionSyntax expression)
{
expression = expression.WalkDownParentheses();
switch (expression.Kind())
{
case SyntaxKind.SimpleMemberAccessExpression:
return ((MemberAccessExpressionSyntax)expression).Expression;
case SyntaxKind.InvocationExpression:
{
var result = ((InvocationExpressionSyntax)expression).Expression;
if (result.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
return GetReceiver(result);
}
return result;
}
case SyntaxKind.ElementAccessExpression:
{
var result = ((ElementAccessExpressionSyntax)expression).Expression;
if (result.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
result = GetReceiver(result);
}
return result;
}
default:
return null;
}
}
protected override bool IsInNamespaceOrTypeContext(ExpressionSyntax node)
=> SyntaxFacts.IsInNamespaceOrTypeContext(node);
protected override ExpressionSyntax GetForEachStatementExpression(CommonForEachStatementSyntax forEachStatement)
=> forEachStatement.Expression;
protected override ExpressionSyntax GetThrowStatementExpression(ThrowStatementSyntax throwStatement)
=> throwStatement.Expression;
protected override bool IsForEachTypeInferred(CommonForEachStatementSyntax forEachStatement, SemanticModel semanticModel)
=> forEachStatement.IsTypeInferred(semanticModel);
protected override bool IsParenthesizedExpression(SyntaxNode node)
=> node.IsKind(SyntaxKind.ParenthesizedExpression);
protected override bool IsNamedArgument(ArgumentSyntax argument)
=> argument.NameColon != null && !argument.NameColon.IsMissing;
protected override string GetNamedArgumentIdentifierValueText(ArgumentSyntax argument)
=> argument.NameColon.Name.Identifier.ValueText;
private bool ReplacementBreaksBinaryExpression(BinaryExpressionSyntax binaryExpression, BinaryExpressionSyntax newBinaryExpression)
{
if ((binaryExpression.IsKind(SyntaxKind.AsExpression) ||
binaryExpression.IsKind(SyntaxKind.IsExpression)) &&
ReplacementBreaksIsOrAsExpression(binaryExpression, newBinaryExpression))
{
return true;
}
return !SymbolsAreCompatible(binaryExpression, newBinaryExpression) ||
!TypesAreCompatible(binaryExpression, newBinaryExpression) ||
!ImplicitConversionsAreCompatible(binaryExpression, newBinaryExpression);
}
private bool ReplacementBreaksConditionalAccessExpression(ConditionalAccessExpressionSyntax conditionalAccessExpression, ConditionalAccessExpressionSyntax newConditionalAccessExpression)
{
return !SymbolsAreCompatible(conditionalAccessExpression, newConditionalAccessExpression) ||
!TypesAreCompatible(conditionalAccessExpression, newConditionalAccessExpression) ||
!SymbolsAreCompatible(conditionalAccessExpression.WhenNotNull, newConditionalAccessExpression.WhenNotNull) ||
!TypesAreCompatible(conditionalAccessExpression.WhenNotNull, newConditionalAccessExpression.WhenNotNull);
}
private bool ReplacementBreaksIsOrAsExpression(BinaryExpressionSyntax originalIsOrAsExpression, BinaryExpressionSyntax newIsOrAsExpression)
{
// Special case: Lambda expressions and anonymous delegates cannot appear
// on the left-side of an 'is' or 'as' cast. We can handle this case syntactically.
if (!originalIsOrAsExpression.Left.WalkDownParentheses().IsAnyLambdaOrAnonymousMethod() &&
newIsOrAsExpression.Left.WalkDownParentheses().IsAnyLambdaOrAnonymousMethod())
{
return true;
}
var originalConvertedType = this.OriginalSemanticModel.GetTypeInfo(originalIsOrAsExpression.Right).Type;
var newConvertedType = this.SpeculativeSemanticModel.GetTypeInfo(newIsOrAsExpression.Right).Type;
if (originalConvertedType == null || newConvertedType == null)
{
return originalConvertedType != newConvertedType;
}
var originalConversion = this.OriginalSemanticModel.ClassifyConversion(originalIsOrAsExpression.Left, originalConvertedType, isExplicitInSource: true);
var newConversion = this.SpeculativeSemanticModel.ClassifyConversion(newIsOrAsExpression.Left, newConvertedType, isExplicitInSource: true);
// Is and As operators do not consider any user-defined operators, just ensure that the conversion exists.
return originalConversion.Exists != newConversion.Exists;
}
private bool ReplacementBreaksAssignmentExpression(AssignmentExpressionSyntax assignmentExpression, AssignmentExpressionSyntax newAssignmentExpression)
{
if (assignmentExpression.IsCompoundAssignExpression() &&
assignmentExpression.Kind() != SyntaxKind.LeftShiftAssignmentExpression &&
assignmentExpression.Kind() != SyntaxKind.RightShiftAssignmentExpression &&
ReplacementBreaksCompoundAssignment(assignmentExpression.Left, assignmentExpression.Right, newAssignmentExpression.Left, newAssignmentExpression.Right))
{
return true;
}
return !SymbolsAreCompatible(assignmentExpression, newAssignmentExpression) ||
!TypesAreCompatible(assignmentExpression, newAssignmentExpression) ||
!ImplicitConversionsAreCompatible(assignmentExpression, newAssignmentExpression);
}
private bool ReplacementBreaksQueryClause(QueryClauseSyntax originalClause, QueryClauseSyntax newClause)
{
// Ensure QueryClauseInfos are compatible.
var originalClauseInfo = this.OriginalSemanticModel.GetQueryClauseInfo(originalClause, this.CancellationToken);
var newClauseInfo = this.SpeculativeSemanticModel.GetQueryClauseInfo(newClause, this.CancellationToken);
return !SymbolInfosAreCompatible(originalClauseInfo.CastInfo, newClauseInfo.CastInfo) ||
!SymbolInfosAreCompatible(originalClauseInfo.OperationInfo, newClauseInfo.OperationInfo);
}
protected override bool ReplacementIntroducesErrorType(ExpressionSyntax originalExpression, ExpressionSyntax newExpression)
{
// The base implementation will see that the type of the new expression may potentially change to null,
// because the expression has no type but can be converted to a conditional expression type. In that case,
// we don't want to consider the null type to be an error type.
if (newExpression.IsKind(SyntaxKind.ConditionalExpression) &&
ConditionalExpressionConversionsAreAllowed(newExpression) &&
this.SpeculativeSemanticModel.GetConversion(newExpression).IsConditionalExpression)
{
return false;
}
return base.ReplacementIntroducesErrorType(originalExpression, newExpression);
}
protected override bool ConversionsAreCompatible(SemanticModel originalModel, ExpressionSyntax originalExpression, SemanticModel newModel, ExpressionSyntax newExpression)
{
var originalConversion = originalModel.GetConversion(originalExpression);
var newConversion = newModel.GetConversion(newExpression);
if (originalExpression.IsKind(SyntaxKind.ConditionalExpression) &&
newExpression.IsKind(SyntaxKind.ConditionalExpression))
{
if (newConversion.IsConditionalExpression)
{
// If we went from a non-conditional-conversion to a conditional-conversion (i.e. by removing a
// cast), then that is always an error before CSharp9, and should not be allowed.
if (!originalConversion.IsConditionalExpression && !ConditionalExpressionConversionsAreAllowed(originalExpression))
return false;
// If the only change to the conversion here is the introduction of a conditional expression conversion,
// that means types didn't really change in a meaningful way.
if (originalConversion.IsIdentity)
return true;
}
}
return ConversionsAreCompatible(originalConversion, newConversion);
}
private static bool ConditionalExpressionConversionsAreAllowed(ExpressionSyntax originalExpression)
=> ((CSharpParseOptions)originalExpression.SyntaxTree.Options).LanguageVersion >= LanguageVersion.CSharp9;
protected override bool ConversionsAreCompatible(ExpressionSyntax originalExpression, ITypeSymbol originalTargetType, ExpressionSyntax newExpression, ITypeSymbol newTargetType)
{
this.GetConversions(originalExpression, originalTargetType, newExpression, newTargetType, out var originalConversion, out var newConversion);
if (originalConversion == null || newConversion == null)
{
return false;
}
return ConversionsAreCompatible(originalConversion.Value, newConversion.Value);
}
private bool ConversionsAreCompatible(Conversion originalConversion, Conversion newConversion)
{
if (originalConversion.Exists != newConversion.Exists ||
(!originalConversion.IsExplicit && newConversion.IsExplicit))
{
return false;
}
var originalIsUserDefined = originalConversion.IsUserDefined;
var newIsUserDefined = newConversion.IsUserDefined;
if (originalIsUserDefined != newIsUserDefined)
{
return false;
}
if (originalIsUserDefined || originalConversion.MethodSymbol != null || newConversion.MethodSymbol != null)
{
return SymbolsAreCompatible(originalConversion.MethodSymbol, newConversion.MethodSymbol);
}
return true;
}
protected override bool ForEachConversionsAreCompatible(SemanticModel originalModel, CommonForEachStatementSyntax originalForEach, SemanticModel newModel, CommonForEachStatementSyntax newForEach)
{
var originalInfo = originalModel.GetForEachStatementInfo(originalForEach);
var newInfo = newModel.GetForEachStatementInfo(newForEach);
return ConversionsAreCompatible(originalInfo.CurrentConversion, newInfo.CurrentConversion)
&& ConversionsAreCompatible(originalInfo.ElementConversion, newInfo.ElementConversion);
}
protected override void GetForEachSymbols(SemanticModel model, CommonForEachStatementSyntax forEach, out IMethodSymbol getEnumeratorMethod, out ITypeSymbol elementType)
{
var info = model.GetForEachStatementInfo(forEach);
getEnumeratorMethod = info.GetEnumeratorMethod;
elementType = info.ElementType;
}
protected override bool IsReferenceConversion(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
=> compilation.ClassifyConversion(sourceType, targetType).IsReference;
protected override Conversion ClassifyConversion(SemanticModel model, ExpressionSyntax expression, ITypeSymbol targetType) =>
model.ClassifyConversion(expression, targetType);
protected override Conversion ClassifyConversion(SemanticModel model, ITypeSymbol originalType, ITypeSymbol targetType) =>
model.Compilation.ClassifyConversion(originalType, targetType);
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Workspaces/Core/Portable/Diagnostics/DiagnosticAnalysisResultBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Workspaces.Diagnostics
{
/// <summary>
/// We have this builder to avoid creating collections unnecessarily.
/// Expectation is that, most of time, most of analyzers doesn't have any diagnostics. so no need to actually create any objects.
/// </summary>
internal struct DiagnosticAnalysisResultBuilder
{
public readonly Project Project;
public readonly VersionStamp Version;
private HashSet<DocumentId>? _lazyDocumentsWithDiagnostics;
private Dictionary<DocumentId, List<DiagnosticData>>? _lazySyntaxLocals;
private Dictionary<DocumentId, List<DiagnosticData>>? _lazySemanticLocals;
private Dictionary<DocumentId, List<DiagnosticData>>? _lazyNonLocals;
private List<DiagnosticData>? _lazyOthers;
public DiagnosticAnalysisResultBuilder(Project project, VersionStamp version)
{
Project = project;
Version = version;
_lazyDocumentsWithDiagnostics = null;
_lazySyntaxLocals = null;
_lazySemanticLocals = null;
_lazyNonLocals = null;
_lazyOthers = null;
}
public ImmutableHashSet<DocumentId> DocumentIds => _lazyDocumentsWithDiagnostics == null ? ImmutableHashSet<DocumentId>.Empty : _lazyDocumentsWithDiagnostics.ToImmutableHashSet();
public ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>> SyntaxLocals => Convert(_lazySyntaxLocals);
public ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>> SemanticLocals => Convert(_lazySemanticLocals);
public ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>> NonLocals => Convert(_lazyNonLocals);
public ImmutableArray<DiagnosticData> Others => _lazyOthers == null ? ImmutableArray<DiagnosticData>.Empty : _lazyOthers.ToImmutableArray();
public void AddExternalSyntaxDiagnostics(DocumentId documentId, IEnumerable<Diagnostic> diagnostics)
{
AddExternalDiagnostics(ref _lazySyntaxLocals, documentId, diagnostics);
}
public void AddExternalSemanticDiagnostics(DocumentId documentId, IEnumerable<Diagnostic> diagnostics)
{
// this is for diagnostic producer that doesnt use compiler based DiagnosticAnalyzer such as TypeScript.
Contract.ThrowIfTrue(Project.SupportsCompilation);
AddExternalDiagnostics(ref _lazySemanticLocals, documentId, diagnostics);
}
private void AddExternalDiagnostics(
ref Dictionary<DocumentId, List<DiagnosticData>>? lazyLocals, DocumentId documentId, IEnumerable<Diagnostic> diagnostics)
{
foreach (var diagnostic in diagnostics)
{
// REVIEW: what is our plan for additional locations?
switch (diagnostic.Location.Kind)
{
case LocationKind.ExternalFile:
{
var diagnosticDocumentId = Project.GetDocumentForExternalLocation(diagnostic.Location);
if (documentId == diagnosticDocumentId)
{
// local diagnostics to a file
AddDocumentDiagnostic(ref lazyLocals, Project.GetTextDocument(diagnosticDocumentId), diagnostic);
}
else if (diagnosticDocumentId != null)
{
// non local diagnostics to a file
AddDocumentDiagnostic(ref _lazyNonLocals, Project.GetTextDocument(diagnosticDocumentId), diagnostic);
}
else
{
// non local diagnostics without location
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
}
break;
}
case LocationKind.None:
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
break;
case LocationKind.SourceFile:
case LocationKind.MetadataFile:
case LocationKind.XmlFile:
// ignore
continue;
case var kind:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
private void AddDocumentDiagnostic(ref Dictionary<DocumentId, List<DiagnosticData>>? map, TextDocument? document, Diagnostic diagnostic)
{
if (document is null || !document.SupportsDiagnostics())
{
return;
}
map ??= new Dictionary<DocumentId, List<DiagnosticData>>();
map.GetOrAdd(document.Id, _ => new List<DiagnosticData>()).Add(DiagnosticData.Create(diagnostic, document));
_lazyDocumentsWithDiagnostics ??= new HashSet<DocumentId>();
_lazyDocumentsWithDiagnostics.Add(document.Id);
}
private void AddOtherDiagnostic(DiagnosticData data)
{
_lazyOthers ??= new List<DiagnosticData>();
_lazyOthers.Add(data);
}
public void AddSyntaxDiagnostics(SyntaxTree tree, IEnumerable<Diagnostic> diagnostics)
=> AddDiagnostics(ref _lazySyntaxLocals, tree, diagnostics);
public void AddSemanticDiagnostics(SyntaxTree tree, IEnumerable<Diagnostic> diagnostics)
=> AddDiagnostics(ref _lazySemanticLocals, tree, diagnostics);
public void AddCompilationDiagnostics(IEnumerable<Diagnostic> diagnostics)
{
Dictionary<DocumentId, List<DiagnosticData>>? dummy = null;
AddDiagnostics(ref dummy, tree: null, diagnostics: diagnostics);
// dummy should be always null since tree is null
Debug.Assert(dummy == null);
}
private void AddDiagnostics(
ref Dictionary<DocumentId, List<DiagnosticData>>? lazyLocals, SyntaxTree? tree, IEnumerable<Diagnostic> diagnostics)
{
foreach (var diagnostic in diagnostics)
{
// REVIEW: what is our plan for additional locations?
switch (diagnostic.Location.Kind)
{
case LocationKind.ExternalFile:
var diagnosticDocumentId = Project.GetDocumentForExternalLocation(diagnostic.Location);
if (diagnosticDocumentId != null)
{
AddDocumentDiagnostic(ref _lazyNonLocals, Project.GetRequiredTextDocument(diagnosticDocumentId), diagnostic);
}
else
{
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
}
break;
case LocationKind.None:
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
break;
case LocationKind.SourceFile:
var diagnosticTree = diagnostic.Location.SourceTree;
if (tree != null && diagnosticTree == tree)
{
// local diagnostics to a file
AddDocumentDiagnostic(ref lazyLocals, Project.GetDocument(diagnosticTree), diagnostic);
}
else if (diagnosticTree != null)
{
// non local diagnostics to a file
AddDocumentDiagnostic(ref _lazyNonLocals, Project.GetDocument(diagnosticTree), diagnostic);
}
else
{
// non local diagnostics without location
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
}
break;
case LocationKind.MetadataFile:
case LocationKind.XmlFile:
// ignore
continue;
default:
throw ExceptionUtilities.UnexpectedValue(diagnostic.Location.Kind);
}
}
}
private static ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>> Convert(Dictionary<DocumentId, List<DiagnosticData>>? map)
{
return map == null ?
ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty :
map.ToImmutableDictionary(kv => kv.Key, kv => kv.Value.ToImmutableArray());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Workspaces.Diagnostics
{
/// <summary>
/// We have this builder to avoid creating collections unnecessarily.
/// Expectation is that, most of time, most of analyzers doesn't have any diagnostics. so no need to actually create any objects.
/// </summary>
internal struct DiagnosticAnalysisResultBuilder
{
public readonly Project Project;
public readonly VersionStamp Version;
private HashSet<DocumentId>? _lazyDocumentsWithDiagnostics;
private Dictionary<DocumentId, List<DiagnosticData>>? _lazySyntaxLocals;
private Dictionary<DocumentId, List<DiagnosticData>>? _lazySemanticLocals;
private Dictionary<DocumentId, List<DiagnosticData>>? _lazyNonLocals;
private List<DiagnosticData>? _lazyOthers;
public DiagnosticAnalysisResultBuilder(Project project, VersionStamp version)
{
Project = project;
Version = version;
_lazyDocumentsWithDiagnostics = null;
_lazySyntaxLocals = null;
_lazySemanticLocals = null;
_lazyNonLocals = null;
_lazyOthers = null;
}
public ImmutableHashSet<DocumentId> DocumentIds => _lazyDocumentsWithDiagnostics == null ? ImmutableHashSet<DocumentId>.Empty : _lazyDocumentsWithDiagnostics.ToImmutableHashSet();
public ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>> SyntaxLocals => Convert(_lazySyntaxLocals);
public ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>> SemanticLocals => Convert(_lazySemanticLocals);
public ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>> NonLocals => Convert(_lazyNonLocals);
public ImmutableArray<DiagnosticData> Others => _lazyOthers == null ? ImmutableArray<DiagnosticData>.Empty : _lazyOthers.ToImmutableArray();
public void AddExternalSyntaxDiagnostics(DocumentId documentId, IEnumerable<Diagnostic> diagnostics)
{
AddExternalDiagnostics(ref _lazySyntaxLocals, documentId, diagnostics);
}
public void AddExternalSemanticDiagnostics(DocumentId documentId, IEnumerable<Diagnostic> diagnostics)
{
// this is for diagnostic producer that doesnt use compiler based DiagnosticAnalyzer such as TypeScript.
Contract.ThrowIfTrue(Project.SupportsCompilation);
AddExternalDiagnostics(ref _lazySemanticLocals, documentId, diagnostics);
}
private void AddExternalDiagnostics(
ref Dictionary<DocumentId, List<DiagnosticData>>? lazyLocals, DocumentId documentId, IEnumerable<Diagnostic> diagnostics)
{
foreach (var diagnostic in diagnostics)
{
// REVIEW: what is our plan for additional locations?
switch (diagnostic.Location.Kind)
{
case LocationKind.ExternalFile:
{
var diagnosticDocumentId = Project.GetDocumentForExternalLocation(diagnostic.Location);
if (documentId == diagnosticDocumentId)
{
// local diagnostics to a file
AddDocumentDiagnostic(ref lazyLocals, Project.GetTextDocument(diagnosticDocumentId), diagnostic);
}
else if (diagnosticDocumentId != null)
{
// non local diagnostics to a file
AddDocumentDiagnostic(ref _lazyNonLocals, Project.GetTextDocument(diagnosticDocumentId), diagnostic);
}
else
{
// non local diagnostics without location
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
}
break;
}
case LocationKind.None:
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
break;
case LocationKind.SourceFile:
case LocationKind.MetadataFile:
case LocationKind.XmlFile:
// ignore
continue;
case var kind:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
private void AddDocumentDiagnostic(ref Dictionary<DocumentId, List<DiagnosticData>>? map, TextDocument? document, Diagnostic diagnostic)
{
if (document is null || !document.SupportsDiagnostics())
{
return;
}
map ??= new Dictionary<DocumentId, List<DiagnosticData>>();
map.GetOrAdd(document.Id, _ => new List<DiagnosticData>()).Add(DiagnosticData.Create(diagnostic, document));
_lazyDocumentsWithDiagnostics ??= new HashSet<DocumentId>();
_lazyDocumentsWithDiagnostics.Add(document.Id);
}
private void AddOtherDiagnostic(DiagnosticData data)
{
_lazyOthers ??= new List<DiagnosticData>();
_lazyOthers.Add(data);
}
public void AddSyntaxDiagnostics(SyntaxTree tree, IEnumerable<Diagnostic> diagnostics)
=> AddDiagnostics(ref _lazySyntaxLocals, tree, diagnostics);
public void AddSemanticDiagnostics(SyntaxTree tree, IEnumerable<Diagnostic> diagnostics)
=> AddDiagnostics(ref _lazySemanticLocals, tree, diagnostics);
public void AddCompilationDiagnostics(IEnumerable<Diagnostic> diagnostics)
{
Dictionary<DocumentId, List<DiagnosticData>>? dummy = null;
AddDiagnostics(ref dummy, tree: null, diagnostics: diagnostics);
// dummy should be always null since tree is null
Debug.Assert(dummy == null);
}
private void AddDiagnostics(
ref Dictionary<DocumentId, List<DiagnosticData>>? lazyLocals, SyntaxTree? tree, IEnumerable<Diagnostic> diagnostics)
{
foreach (var diagnostic in diagnostics)
{
// REVIEW: what is our plan for additional locations?
switch (diagnostic.Location.Kind)
{
case LocationKind.ExternalFile:
var diagnosticDocumentId = Project.GetDocumentForExternalLocation(diagnostic.Location);
if (diagnosticDocumentId != null)
{
AddDocumentDiagnostic(ref _lazyNonLocals, Project.GetRequiredTextDocument(diagnosticDocumentId), diagnostic);
}
else
{
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
}
break;
case LocationKind.None:
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
break;
case LocationKind.SourceFile:
var diagnosticTree = diagnostic.Location.SourceTree;
if (tree != null && diagnosticTree == tree)
{
// local diagnostics to a file
AddDocumentDiagnostic(ref lazyLocals, Project.GetDocument(diagnosticTree), diagnostic);
}
else if (diagnosticTree != null)
{
// non local diagnostics to a file
AddDocumentDiagnostic(ref _lazyNonLocals, Project.GetDocument(diagnosticTree), diagnostic);
}
else
{
// non local diagnostics without location
AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
}
break;
case LocationKind.MetadataFile:
case LocationKind.XmlFile:
// ignore
continue;
default:
throw ExceptionUtilities.UnexpectedValue(diagnostic.Location.Kind);
}
}
}
private static ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>> Convert(Dictionary<DocumentId, List<DiagnosticData>>? map)
{
return map == null ?
ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty :
map.ToImmutableDictionary(kv => kv.Key, kv => kv.Value.ToImmutableArray());
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/Operations/AdjustNewLinesOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting.Rules
{
/// <summary>
/// indicate how many lines are needed between two tokens
/// </summary>
internal sealed class AdjustNewLinesOperation
{
internal AdjustNewLinesOperation(int line, AdjustNewLinesOption option)
{
Contract.ThrowIfFalse(option != AdjustNewLinesOption.ForceLines || line > 0);
Contract.ThrowIfFalse(option != AdjustNewLinesOption.PreserveLines || line >= 0);
Contract.ThrowIfFalse(option != AdjustNewLinesOption.ForceLinesIfOnSingleLine || line > 0);
this.Line = line;
this.Option = option;
}
public int Line { get; }
public AdjustNewLinesOption Option { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting.Rules
{
/// <summary>
/// indicate how many lines are needed between two tokens
/// </summary>
internal sealed class AdjustNewLinesOperation
{
internal AdjustNewLinesOperation(int line, AdjustNewLinesOption option)
{
Contract.ThrowIfFalse(option != AdjustNewLinesOption.ForceLines || line > 0);
Contract.ThrowIfFalse(option != AdjustNewLinesOption.PreserveLines || line >= 0);
Contract.ThrowIfFalse(option != AdjustNewLinesOption.ForceLinesIfOnSingleLine || line > 0);
this.Line = line;
this.Option = option;
}
public int Line { get; }
public AdjustNewLinesOption Option { get; }
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Features/Core/Portable/AddImport/AddImportFixData.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.Runtime.Serialization;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.AddImport
{
[DataContract]
internal sealed class AddImportFixData
{
[DataMember(Order = 0)]
public AddImportFixKind Kind { get; }
/// <summary>
/// Text changes to make to the document. Usually just the import to add. May also
/// include a change to the name node the feature was invoked on to fix the casing of it.
/// May be empty for fixes that don't need to add an import and only do something like
/// add a project/metadata reference.
/// </summary>
[DataMember(Order = 1)]
public readonly ImmutableArray<TextChange> TextChanges;
/// <summary>
/// String to display in the lightbulb menu.
/// </summary>
[DataMember(Order = 2)]
public readonly string Title;
/// <summary>
/// Tags that control what glyph is displayed in the lightbulb menu.
/// </summary>
[DataMember(Order = 3)]
public readonly ImmutableArray<string> Tags;
/// <summary>
/// The priority this item should have in the lightbulb list.
/// </summary>
[DataMember(Order = 4)]
public readonly CodeActionPriority Priority;
#region When adding P2P references.
/// <summary>
/// The optional id for a <see cref="Project"/> we'd like to add a reference to.
/// </summary>
[DataMember(Order = 5)]
public readonly ProjectId ProjectReferenceToAdd;
#endregion
#region When adding a metadata reference
/// <summary>
/// If we're adding <see cref="PortableExecutableReferenceFilePathToAdd"/> then this
/// is the id for the <see cref="Project"/> we can find that <see cref="PortableExecutableReference"/>
/// referenced from.
/// </summary>
[DataMember(Order = 6)]
public readonly ProjectId PortableExecutableReferenceProjectId;
/// <summary>
/// If we want to add a <see cref="PortableExecutableReference"/> metadata reference, this
/// is the <see cref="PortableExecutableReference.FilePath"/> for it.
/// </summary>
[DataMember(Order = 7)]
public readonly string PortableExecutableReferenceFilePathToAdd;
#endregion
#region When adding an assembly reference
[DataMember(Order = 8)]
public readonly string AssemblyReferenceAssemblyName;
[DataMember(Order = 9)]
public readonly string AssemblyReferenceFullyQualifiedTypeName;
#endregion
#region When adding a package reference
[DataMember(Order = 10)]
public readonly string PackageSource;
[DataMember(Order = 11)]
public readonly string PackageName;
[DataMember(Order = 12)]
public readonly string PackageVersionOpt;
#endregion
// Must be public since it's used for deserialization.
public AddImportFixData(
AddImportFixKind kind,
ImmutableArray<TextChange> textChanges,
string title = null,
ImmutableArray<string> tags = default,
CodeActionPriority priority = default,
ProjectId projectReferenceToAdd = null,
ProjectId portableExecutableReferenceProjectId = null,
string portableExecutableReferenceFilePathToAdd = null,
string assemblyReferenceAssemblyName = null,
string assemblyReferenceFullyQualifiedTypeName = null,
string packageSource = null,
string packageName = null,
string packageVersionOpt = null)
{
Kind = kind;
TextChanges = textChanges;
Title = title;
Tags = tags;
Priority = priority;
ProjectReferenceToAdd = projectReferenceToAdd;
PortableExecutableReferenceProjectId = portableExecutableReferenceProjectId;
PortableExecutableReferenceFilePathToAdd = portableExecutableReferenceFilePathToAdd;
AssemblyReferenceAssemblyName = assemblyReferenceAssemblyName;
AssemblyReferenceFullyQualifiedTypeName = assemblyReferenceFullyQualifiedTypeName;
PackageSource = packageSource;
PackageName = packageName;
PackageVersionOpt = packageVersionOpt;
}
public static AddImportFixData CreateForProjectSymbol(ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId projectReferenceToAdd)
=> new(AddImportFixKind.ProjectSymbol,
textChanges,
title: title,
tags: tags,
priority: priority,
projectReferenceToAdd: projectReferenceToAdd);
public static AddImportFixData CreateForMetadataSymbol(ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId portableExecutableReferenceProjectId, string portableExecutableReferenceFilePathToAdd)
=> new(AddImportFixKind.MetadataSymbol,
textChanges,
title: title,
tags: tags,
priority: priority,
portableExecutableReferenceProjectId: portableExecutableReferenceProjectId,
portableExecutableReferenceFilePathToAdd: portableExecutableReferenceFilePathToAdd);
public static AddImportFixData CreateForReferenceAssemblySymbol(ImmutableArray<TextChange> textChanges, string title, string assemblyReferenceAssemblyName, string assemblyReferenceFullyQualifiedTypeName)
=> new(AddImportFixKind.ReferenceAssemblySymbol,
textChanges,
title: title,
tags: WellKnownTagArrays.AddReference,
priority: CodeActionPriority.Low,
assemblyReferenceAssemblyName: assemblyReferenceAssemblyName,
assemblyReferenceFullyQualifiedTypeName: assemblyReferenceFullyQualifiedTypeName);
public static AddImportFixData CreateForPackageSymbol(ImmutableArray<TextChange> textChanges, string packageSource, string packageName, string packageVersionOpt)
=> new(AddImportFixKind.PackageSymbol,
textChanges,
packageSource: packageSource,
priority: CodeActionPriority.Low,
packageName: packageName,
packageVersionOpt: packageVersionOpt);
}
}
| // Licensed to the .NET Foundation under one or more 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.Runtime.Serialization;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.AddImport
{
[DataContract]
internal sealed class AddImportFixData
{
[DataMember(Order = 0)]
public AddImportFixKind Kind { get; }
/// <summary>
/// Text changes to make to the document. Usually just the import to add. May also
/// include a change to the name node the feature was invoked on to fix the casing of it.
/// May be empty for fixes that don't need to add an import and only do something like
/// add a project/metadata reference.
/// </summary>
[DataMember(Order = 1)]
public readonly ImmutableArray<TextChange> TextChanges;
/// <summary>
/// String to display in the lightbulb menu.
/// </summary>
[DataMember(Order = 2)]
public readonly string Title;
/// <summary>
/// Tags that control what glyph is displayed in the lightbulb menu.
/// </summary>
[DataMember(Order = 3)]
public readonly ImmutableArray<string> Tags;
/// <summary>
/// The priority this item should have in the lightbulb list.
/// </summary>
[DataMember(Order = 4)]
public readonly CodeActionPriority Priority;
#region When adding P2P references.
/// <summary>
/// The optional id for a <see cref="Project"/> we'd like to add a reference to.
/// </summary>
[DataMember(Order = 5)]
public readonly ProjectId ProjectReferenceToAdd;
#endregion
#region When adding a metadata reference
/// <summary>
/// If we're adding <see cref="PortableExecutableReferenceFilePathToAdd"/> then this
/// is the id for the <see cref="Project"/> we can find that <see cref="PortableExecutableReference"/>
/// referenced from.
/// </summary>
[DataMember(Order = 6)]
public readonly ProjectId PortableExecutableReferenceProjectId;
/// <summary>
/// If we want to add a <see cref="PortableExecutableReference"/> metadata reference, this
/// is the <see cref="PortableExecutableReference.FilePath"/> for it.
/// </summary>
[DataMember(Order = 7)]
public readonly string PortableExecutableReferenceFilePathToAdd;
#endregion
#region When adding an assembly reference
[DataMember(Order = 8)]
public readonly string AssemblyReferenceAssemblyName;
[DataMember(Order = 9)]
public readonly string AssemblyReferenceFullyQualifiedTypeName;
#endregion
#region When adding a package reference
[DataMember(Order = 10)]
public readonly string PackageSource;
[DataMember(Order = 11)]
public readonly string PackageName;
[DataMember(Order = 12)]
public readonly string PackageVersionOpt;
#endregion
// Must be public since it's used for deserialization.
public AddImportFixData(
AddImportFixKind kind,
ImmutableArray<TextChange> textChanges,
string title = null,
ImmutableArray<string> tags = default,
CodeActionPriority priority = default,
ProjectId projectReferenceToAdd = null,
ProjectId portableExecutableReferenceProjectId = null,
string portableExecutableReferenceFilePathToAdd = null,
string assemblyReferenceAssemblyName = null,
string assemblyReferenceFullyQualifiedTypeName = null,
string packageSource = null,
string packageName = null,
string packageVersionOpt = null)
{
Kind = kind;
TextChanges = textChanges;
Title = title;
Tags = tags;
Priority = priority;
ProjectReferenceToAdd = projectReferenceToAdd;
PortableExecutableReferenceProjectId = portableExecutableReferenceProjectId;
PortableExecutableReferenceFilePathToAdd = portableExecutableReferenceFilePathToAdd;
AssemblyReferenceAssemblyName = assemblyReferenceAssemblyName;
AssemblyReferenceFullyQualifiedTypeName = assemblyReferenceFullyQualifiedTypeName;
PackageSource = packageSource;
PackageName = packageName;
PackageVersionOpt = packageVersionOpt;
}
public static AddImportFixData CreateForProjectSymbol(ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId projectReferenceToAdd)
=> new(AddImportFixKind.ProjectSymbol,
textChanges,
title: title,
tags: tags,
priority: priority,
projectReferenceToAdd: projectReferenceToAdd);
public static AddImportFixData CreateForMetadataSymbol(ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId portableExecutableReferenceProjectId, string portableExecutableReferenceFilePathToAdd)
=> new(AddImportFixKind.MetadataSymbol,
textChanges,
title: title,
tags: tags,
priority: priority,
portableExecutableReferenceProjectId: portableExecutableReferenceProjectId,
portableExecutableReferenceFilePathToAdd: portableExecutableReferenceFilePathToAdd);
public static AddImportFixData CreateForReferenceAssemblySymbol(ImmutableArray<TextChange> textChanges, string title, string assemblyReferenceAssemblyName, string assemblyReferenceFullyQualifiedTypeName)
=> new(AddImportFixKind.ReferenceAssemblySymbol,
textChanges,
title: title,
tags: WellKnownTagArrays.AddReference,
priority: CodeActionPriority.Low,
assemblyReferenceAssemblyName: assemblyReferenceAssemblyName,
assemblyReferenceFullyQualifiedTypeName: assemblyReferenceFullyQualifiedTypeName);
public static AddImportFixData CreateForPackageSymbol(ImmutableArray<TextChange> textChanges, string packageSource, string packageName, string packageVersionOpt)
=> new(AddImportFixKind.PackageSymbol,
textChanges,
packageSource: packageSource,
priority: CodeActionPriority.Low,
packageName: packageName,
packageVersionOpt: packageVersionOpt);
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Dependencies/Collections/ImmutableSegmentedList`1+Enumerator.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;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Collections
{
internal partial struct ImmutableSegmentedList<T>
{
public struct Enumerator : IEnumerator<T>
{
private readonly SegmentedList<T> _list;
private SegmentedList<T>.Enumerator _enumerator;
internal Enumerator(SegmentedList<T> list)
{
_list = list;
_enumerator = list.GetEnumerator();
}
public T Current => _enumerator.Current;
object? IEnumerator.Current => ((IEnumerator)_enumerator).Current;
public void Dispose()
=> _enumerator.Dispose();
public bool MoveNext()
=> _enumerator.MoveNext();
public void Reset()
{
// Create a new enumerator, since _enumerator.Reset() will fail for cases where the list was mutated
// after enumeration started, and ImmutableSegmentList<T>.Builder allows for this case without error.
_enumerator = _list.GetEnumerator();
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Collections
{
internal partial struct ImmutableSegmentedList<T>
{
public struct Enumerator : IEnumerator<T>
{
private readonly SegmentedList<T> _list;
private SegmentedList<T>.Enumerator _enumerator;
internal Enumerator(SegmentedList<T> list)
{
_list = list;
_enumerator = list.GetEnumerator();
}
public T Current => _enumerator.Current;
object? IEnumerator.Current => ((IEnumerator)_enumerator).Current;
public void Dispose()
=> _enumerator.Dispose();
public bool MoveNext()
=> _enumerator.MoveNext();
public void Reset()
{
// Create a new enumerator, since _enumerator.Reset() will fail for cases where the list was mutated
// after enumeration started, and ImmutableSegmentList<T>.Builder allows for this case without error.
_enumerator = _list.GetEnumerator();
}
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Features/LanguageServer/Protocol/LanguageServerResources.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.LanguageServer
{
/// <summary>
/// Stub type - replace with type generated from resx file when resources are needed in this assembly.
/// </summary>
internal static class LanguageServerResources
{
}
}
| // Licensed to the .NET Foundation under one or more 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.LanguageServer
{
/// <summary>
/// Stub type - replace with type generated from resx file when resources are needed in this assembly.
/// </summary>
internal static class LanguageServerResources
{
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenMultiDimensionalArray.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.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenMultiDimensionalArray
Inherits BasicTestBase
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1, 2) {{1, 2, 3}, {1, 2, 3}}
System.Console.Write(arr(1, 1))
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"),
expectedOutput:="2").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=24 <PrivateImplementationDetails>.618A09BD4B017EFD77C1C5CEA9D47D21EC52DDDEE4892C2A026D588E54AE8F19"
IL_000d: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0012: ldc.i4.1
IL_0013: ldc.i4.1
IL_0014: call "Integer(*,*).Get"
IL_0019: call "Sub System.Console.Write(Integer)"
IL_001e: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer001()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1, 2) {{1, 2, 3}, {1, Integer.Parse("42"), 3}}
System.Console.Write(arr(1, 1))
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"),
expectedOutput:="42").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 49 (0x31)
.maxstack 5
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=24 <PrivateImplementationDetails>.70DE168CE7BA89AB94AD130FD8CB2C588B408E6B5C7FA55F4B322158684A1362"
IL_000d: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: ldc.i4.1
IL_0015: ldstr "42"
IL_001a: call "Function Integer.Parse(String) As Integer"
IL_001f: call "Integer(*,*).Set"
IL_0024: ldc.i4.1
IL_0025: ldc.i4.1
IL_0026: call "Integer(*,*).Get"
IL_002b: call "Sub System.Console.Write(Integer)"
IL_0030: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer002()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1, 2) {{Integer.Parse("1"), Integer.Parse("2"), Integer.Parse("3")}, {Integer.Parse("4"), Integer.Parse("5"), Integer.Parse("6")}}
System.Console.Write(arr(1, 1))
End Sub
End Module
</file>
</compilation>,
expectedOutput:="5").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 128 (0x80)
.maxstack 5
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldstr "1"
IL_000f: call "Function Integer.Parse(String) As Integer"
IL_0014: call "Integer(*,*).Set"
IL_0019: dup
IL_001a: ldc.i4.0
IL_001b: ldc.i4.1
IL_001c: ldstr "2"
IL_0021: call "Function Integer.Parse(String) As Integer"
IL_0026: call "Integer(*,*).Set"
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldc.i4.2
IL_002e: ldstr "3"
IL_0033: call "Function Integer.Parse(String) As Integer"
IL_0038: call "Integer(*,*).Set"
IL_003d: dup
IL_003e: ldc.i4.1
IL_003f: ldc.i4.0
IL_0040: ldstr "4"
IL_0045: call "Function Integer.Parse(String) As Integer"
IL_004a: call "Integer(*,*).Set"
IL_004f: dup
IL_0050: ldc.i4.1
IL_0051: ldc.i4.1
IL_0052: ldstr "5"
IL_0057: call "Function Integer.Parse(String) As Integer"
IL_005c: call "Integer(*,*).Set"
IL_0061: dup
IL_0062: ldc.i4.1
IL_0063: ldc.i4.2
IL_0064: ldstr "6"
IL_0069: call "Function Integer.Parse(String) As Integer"
IL_006e: call "Integer(*,*).Set"
IL_0073: ldc.i4.1
IL_0074: ldc.i4.1
IL_0075: call "Integer(*,*).Get"
IL_007a: call "Sub System.Console.Write(Integer)"
IL_007f: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer003()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1, -1) {{}, {}}
System.Console.Write(arr.Length)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="0").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.0
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: callvirt "Function System.Array.get_Length() As Integer"
IL_000c: call "Sub System.Console.Write(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer004()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(-1, -1) {}
System.Console.Write(arr.Length)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="0").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: callvirt "Function System.Array.get_Length() As Integer"
IL_000c: call "Sub System.Console.Write(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreate()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1,2) {}
System.Console.Write(arr.Length)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="6").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: callvirt "Function System.Array.get_Length() As Integer"
IL_000c: call "Sub System.Console.Write(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateGeneric()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
goo(Of String)()
c1(Of Long).goo()
End Sub
Class c1(Of T)
Public Shared Sub goo()
Dim arr As T(,) = New T(1, 2) {}
System.Console.Write(arr.Length)
End Sub
End Class
Public Sub goo(Of T)()
Dim arr As T(,) = New T(1, 2) {}
System.Console.Write(arr.Length)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="66").
VerifyIL("A.goo(Of T)()",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "T(*,*)..ctor"
IL_0007: callvirt "Function System.Array.get_Length() As Integer"
IL_000c: call "Sub System.Console.Write(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayGetSetAddress()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
goo(Of String)("hello")
c1(Of Long).goo(123)
End Sub
Class c1(Of T)
Public Shared Sub goo(e as T)
Dim arr As T(,) = New T(2, 3) {}
arr(1, 2) = e
System.Console.Write(arr(1, 2).ToString)
Dim v as T = arr(1, 2)
System.Console.Write(v.ToString)
End Sub
End Class
Public Sub goo(Of T)(e as T)
Dim arr As T(,) = New T(2, 3) {}
arr(1, 2) = e
System.Console.Write(arr(1, 2).ToString)
Dim v as T = arr(1, 2)
System.Console.Write(v.ToString)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hellohello123123").
VerifyIL("A.goo(Of T)(T)",
<![CDATA[
{
// Code size 69 (0x45)
.maxstack 5
.locals init (T V_0) //v
IL_0000: ldc.i4.3
IL_0001: ldc.i4.4
IL_0002: newobj "T(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: ldc.i4.2
IL_000a: ldarg.0
IL_000b: call "T(*,*).Set"
IL_0010: dup
IL_0011: ldc.i4.1
IL_0012: ldc.i4.2
IL_0013: readonly.
IL_0015: call "T(*,*).Address"
IL_001a: constrained. "T"
IL_0020: callvirt "Function Object.ToString() As String"
IL_0025: call "Sub System.Console.Write(String)"
IL_002a: ldc.i4.1
IL_002b: ldc.i4.2
IL_002c: call "T(*,*).Get"
IL_0031: stloc.0
IL_0032: ldloca.s V_0
IL_0034: constrained. "T"
IL_003a: callvirt "Function Object.ToString() As String"
IL_003f: call "Sub System.Console.Write(String)"
IL_0044: ret
}
]]>)
End Sub
<WorkItem(542259, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542259")>
<Fact>
Public Sub MixMultiAndJaggedArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim x = New Exception(,,) {}
Dim y = New Exception(,,) {{{}}}
Dim z = New Exception(,)() {}
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics()
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim myArray1 As Integer(,) = New Integer(-1, -1) {}
Dim myArray2 As Integer(,) = New Integer(3, 1) {}
Dim myArray3 As Integer(,,) = New Integer(3, 1, 2) {}
Dim myArray4 As Integer(,) = New Integer(2147483646, 2147483646) {}
Dim myArray5 As Integer(,) = New Integer(2147483648UI - 1, 2147483648UI - 1) {}
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: pop
IL_0008: ldc.i4.4
IL_0009: ldc.i4.2
IL_000a: newobj "Integer(*,*)..ctor"
IL_000f: pop
IL_0010: ldc.i4.4
IL_0011: ldc.i4.2
IL_0012: ldc.i4.3
IL_0013: newobj "Integer(*,*,*)..ctor"
IL_0018: pop
IL_0019: ldc.i4 0x7fffffff
IL_001e: ldc.i4 0x7fffffff
IL_0023: newobj "Integer(*,*)..ctor"
IL_0028: pop
IL_0029: ldc.i4 0x80000000
IL_002e: ldc.i4 0x80000000
IL_0033: newobj "Integer(*,*)..ctor"
IL_0038: pop
IL_0039: ret
}
]]>)
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray_1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim myArray6 As Integer(,,,,) = Nothing
myArray6 = New Integer(4, 5, 8, 3, 6) {}
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 13 (0xd)
.maxstack 5
IL_0000: ldc.i4.5
IL_0001: ldc.i4.6
IL_0002: ldc.i4.s 9
IL_0004: ldc.i4.4
IL_0005: ldc.i4.7
IL_0006: newobj "Integer(*,*,*,*,*)..ctor"
IL_000b: pop
IL_000c: ret
}
]]>)
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray_2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Private Delegate Sub myDelegate(myString As String)
Sub Main()
Dim myArray1 As myInterface(,) = New myInterface(3, 1) {}
Dim myArray2 As myDelegate(,) = New myDelegate(3, 1) {}
Dim myArray3 = New Integer(Number.One, Number.Two) {}
End Sub
End Module
Interface myInterface
End Interface
Enum Number
One
Two
End Enum
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 25 (0x19)
.maxstack 2
IL_0000: ldc.i4.4
IL_0001: ldc.i4.2
IL_0002: newobj "myInterface(*,*)..ctor"
IL_0007: pop
IL_0008: ldc.i4.4
IL_0009: ldc.i4.2
IL_000a: newobj "Module1.myDelegate(*,*)..ctor"
IL_000f: pop
IL_0010: ldc.i4.1
IL_0011: ldc.i4.2
IL_0012: newobj "Integer(*,*)..ctor"
IL_0017: pop
IL_0018: ret
}
]]>)
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray_3()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class C1
Public Shared Sub Main()
Dim myLength As Integer = 3
Dim arr As Integer(,) = New Integer(myLength, 1) {}
End Sub
Private Class A
Private x As Integer = 1
Private arr As Integer(,) = New Integer(x, 4) {}
End Class
End Class
</file>
</compilation>).VerifyIL("C1.Main", <![CDATA[
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldc.i4.3
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ldc.i4.2
IL_0004: newobj "Integer(*,*)..ctor"
IL_0009: pop
IL_000a: ret
}
]]>)
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray_5()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim myArray8 As Integer(,) = New Integer(-1, 4) {}
Dim arrDouble#(,) = New Double(1, 2) {}
Dim arrDecimal@(,) = New Decimal(1, 2) {}
Dim arrString$(,) = New String(1, 2) {}
Dim arrInteger%(,) = New Integer(1, 2) {}
Dim arrLong&(,) = New Long(1, 2) {}
Dim arrSingle!(,) = New Single(1, 2) {}
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 57 (0x39)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.5
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: pop
IL_0008: ldc.i4.2
IL_0009: ldc.i4.3
IL_000a: newobj "Double(*,*)..ctor"
IL_000f: pop
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: newobj "Decimal(*,*)..ctor"
IL_0017: pop
IL_0018: ldc.i4.2
IL_0019: ldc.i4.3
IL_001a: newobj "String(*,*)..ctor"
IL_001f: pop
IL_0020: ldc.i4.2
IL_0021: ldc.i4.3
IL_0022: newobj "Integer(*,*)..ctor"
IL_0027: pop
IL_0028: ldc.i4.2
IL_0029: ldc.i4.3
IL_002a: newobj "Long(*,*)..ctor"
IL_002f: pop
IL_0030: ldc.i4.2
IL_0031: ldc.i4.3
IL_0032: newobj "Single(*,*)..ctor"
IL_0037: pop
IL_0038: ret
}
]]>)
End Sub
' Initialize multi- dimensional array
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub InitializemultiDimensionalArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Infer On
Imports System
Imports Microsoft.VisualBasic.Information
Module Module1
Sub Main()
Dim myArray1 As Integer(,,) = {{{0, 1}, {2, 3}}, {{4, 5}, {6, 7}}}
Dim myArray2 As Single(,) = New Single(2, 1) {{CSng(1.0), CSng(2.0)}, {CSng(3.0), CSng(4.0)}, {CSng(5.0), CSng(6.0)}}
Dim myArray3 As Long(,) = New Long(,) {{1, 2}, {3, 4}, {5, 6}}
Dim myArray4 As Char(,)
myArray4 = New Char(2, 1) {{"1"c, "2"c}, {"3"c, "4"c}, {"5"c, "6"c}}
Dim myArray5 As Decimal(,)
myArray5 = New Decimal(,) {{CDec(1.0), CDec(2.0)}, {CDec(3.0), CDec(4.0)}, {CDec(5.0), CDec(6.0)}}
Dim myArray6 As Integer(,) = New Integer(-1, -1) {}
Dim myArray7 As Integer(,) = New Integer(,) {{}}
Dim myArray8 As Integer(,,) = New Integer(,,) {{{}}}
Dim myArray9 As String(,) = New String(2, 1) {{"a"c, "b"c}, {"c"c, "d"c}, {"e"c, "f"c}}
Console.WriteLine(UBound(myArray1, 1))
Console.WriteLine(UBound(myArray1, 2))
Console.WriteLine(UBound(myArray1, 3))
Console.WriteLine(UBound(myArray2, 1))
Console.WriteLine(UBound(myArray2, 2))
Console.WriteLine(UBound(myArray3, 1))
Console.WriteLine(UBound(myArray3, 2))
Console.WriteLine(UBound(myArray4, 1))
Console.WriteLine(UBound(myArray4, 2))
Console.WriteLine(UBound(myArray5, 1))
Console.WriteLine(UBound(myArray5, 2))
Console.WriteLine(UBound(myArray6, 1))
Console.WriteLine(UBound(myArray6, 2))
Console.WriteLine(UBound(myArray7, 1))
Console.WriteLine(UBound(myArray7, 2))
Console.WriteLine(UBound(myArray8, 1))
Console.WriteLine(UBound(myArray8, 2))
Console.WriteLine(UBound(myArray8, 3))
Console.WriteLine(UBound(myArray9, 1))
Console.WriteLine(UBound(myArray9, 2))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[1
1
1
2
1
2
1
2
1
2
1
-1
-1
0
-1
0
0
-1
2
1]]>)
End Sub
' Use different kinds of var as index upper bound
<Fact>
Public Sub DifferentVarAsBound()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Infer On
Imports Microsoft.VisualBasic.Information
Module Module1
Property prop As Integer
Sub Main(args As String())
Dim arr1(3, prop) As Integer
Dim arr2(3, fun()) As Integer
Dim x = fun()
Dim arr3(x, 1) As Integer
Dim z() As Integer
Dim y() As Integer
Dim replyCounts(,) As Short = New Short(UBound(z, 1), UBound(y, 1)) {}
End Sub
Function fun() As Integer
Return 3
End Function
Sub goo(x As Integer)
Dim arr1(3, x) As Integer
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 67 (0x43)
.maxstack 3
.locals init (Integer() V_0, //z
Integer() V_1) //y
IL_0000: ldc.i4.4
IL_0001: call "Function Module1.get_prop() As Integer"
IL_0006: ldc.i4.1
IL_0007: add.ovf
IL_0008: newobj "Integer(*,*)..ctor"
IL_000d: pop
IL_000e: ldc.i4.4
IL_000f: call "Function Module1.fun() As Integer"
IL_0014: ldc.i4.1
IL_0015: add.ovf
IL_0016: newobj "Integer(*,*)..ctor"
IL_001b: pop
IL_001c: call "Function Module1.fun() As Integer"
IL_0021: ldc.i4.1
IL_0022: add.ovf
IL_0023: ldc.i4.2
IL_0024: newobj "Integer(*,*)..ctor"
IL_0029: pop
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: call "Function Microsoft.VisualBasic.Information.UBound(System.Array, Integer) As Integer"
IL_0031: ldc.i4.1
IL_0032: add.ovf
IL_0033: ldloc.1
IL_0034: ldc.i4.1
IL_0035: call "Function Microsoft.VisualBasic.Information.UBound(System.Array, Integer) As Integer"
IL_003a: ldc.i4.1
IL_003b: add.ovf
IL_003c: newobj "Short(*,*)..ctor"
IL_0041: pop
IL_0042: ret
}
]]>)
End Sub
' Specify lower bound and up bound for multi-dimensional array
<Fact>
Public Sub SpecifyLowerAndUpBound()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Property prop As Integer
Sub Main(args As String())
Dim arr1(0 To 0, 0 To -1) As Integer
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldc.i4.0
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: pop
IL_0008: ret
}
]]>)
End Sub
' Array creation expression can be part of an anonymous object creation expression
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub ArrayCreateAsAnonymous()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Infer On
Imports System
Imports Microsoft.VisualBasic.Information
Module Module1
Sub Main(args As String())
Dim a0 = New With {
Key.b4 = New Integer(1, 2) {}, _
Key.b5 = New Integer(1, 1) {{1, 2}, {2, 3}},
Key.b6 = New Integer()() {New Integer(1) {}, New Integer(2) {}},
Key.b7 = New Integer(2)() {},
Key.b8 = New Integer(1)() {New Integer(0) {}, New Integer(1) {}},
Key.b9 = New Integer() {1, 2, 3},
Key.b10 = New Integer(,) {{1, 2}, {2, 3}}
}
Console.WriteLine(UBound(a0.b4, 1))
Console.WriteLine(UBound(a0.b4, 2))
Console.WriteLine(UBound(a0.b5, 1))
Console.WriteLine(UBound(a0.b5, 2))
Console.WriteLine(UBound(a0.b6, 1))
Console.WriteLine(UBound(a0.b7, 1))
Console.WriteLine(UBound(a0.b8, 1))
Console.WriteLine(UBound(a0.b9, 1))
Console.WriteLine(UBound(a0.b10, 1))
Console.WriteLine(UBound(a0.b10, 2))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[1
2
1
1
1
2
1
2
1
1]]>)
End Sub
' Accessing an array's 0th element should work fine
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessZero()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 4) {}
arr(0, 0) = 5
Console.WriteLine(arr(0, 0))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[5]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 29 (0x1d)
.maxstack 5
IL_0000: ldc.i4.5
IL_0001: ldc.i4.5
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.5
IL_000b: call "Integer(*,*).Set"
IL_0010: ldc.i4.0
IL_0011: ldc.i4.0
IL_0012: call "Integer(*,*).Get"
IL_0017: call "Sub System.Console.WriteLine(Integer)"
IL_001c: ret
}
]]>)
End Sub
' Accessing an array's maxlength element should work fine
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessMaxLength()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 3) {}
arr(4, 3) = 5
Console.WriteLine(arr(4, 3))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[5]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 29 (0x1d)
.maxstack 5
IL_0000: ldc.i4.5
IL_0001: ldc.i4.4
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.4
IL_0009: ldc.i4.3
IL_000a: ldc.i4.5
IL_000b: call "Integer(*,*).Set"
IL_0010: ldc.i4.4
IL_0011: ldc.i4.3
IL_0012: call "Integer(*,*).Get"
IL_0017: call "Sub System.Console.WriteLine(Integer)"
IL_001c: ret
}
]]>)
End Sub
' Accessing an array's -1 element should throw an exception
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessLessThanMin()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 4) {}
Try
arr(-1, 1) = 5
arr(1, -1) = 5
arr(-1, -1) = 5
Catch generatedExceptionName As System.IndexOutOfRangeException
End Try
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 4
.locals init (Integer(,) V_0, //arr
System.IndexOutOfRangeException V_1) //generatedExceptionName
IL_0000: ldc.i4.5
IL_0001: ldc.i4.5
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: stloc.0
.try
{
IL_0008: ldloc.0
IL_0009: ldc.i4.m1
IL_000a: ldc.i4.1
IL_000b: ldc.i4.5
IL_000c: call "Integer(*,*).Set"
IL_0011: ldloc.0
IL_0012: ldc.i4.1
IL_0013: ldc.i4.m1
IL_0014: ldc.i4.5
IL_0015: call "Integer(*,*).Set"
IL_001a: ldloc.0
IL_001b: ldc.i4.m1
IL_001c: ldc.i4.m1
IL_001d: ldc.i4.5
IL_001e: call "Integer(*,*).Set"
IL_0023: leave.s IL_0033
}
catch System.IndexOutOfRangeException
{
IL_0025: dup
IL_0026: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_002b: stloc.1
IL_002c: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0031: leave.s IL_0033
}
IL_0033: ret
}
]]>)
End Sub
' Accessing an array's maxlength+1 element should throw an exception
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessGreaterThanMax()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 3) {}
Try
arr(5, 3) = 5
arr(4, 4) = 5
arr(5, 4) = 5
Catch
End Try
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 50 (0x32)
.maxstack 4
.locals init (Integer(,) V_0) //arr
IL_0000: ldc.i4.5
IL_0001: ldc.i4.4
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: stloc.0
.try
{
IL_0008: ldloc.0
IL_0009: ldc.i4.5
IL_000a: ldc.i4.3
IL_000b: ldc.i4.5
IL_000c: call "Integer(*,*).Set"
IL_0011: ldloc.0
IL_0012: ldc.i4.4
IL_0013: ldc.i4.4
IL_0014: ldc.i4.5
IL_0015: call "Integer(*,*).Set"
IL_001a: ldloc.0
IL_001b: ldc.i4.5
IL_001c: ldc.i4.4
IL_001d: ldc.i4.5
IL_001e: call "Integer(*,*).Set"
IL_0023: leave.s IL_0031
}
catch System.Exception
{
IL_0025: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_002a: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_002f: leave.s IL_0031
}
IL_0031: ret
}
]]>)
End Sub
' Accessing an array's index with a variable of type int, short, byte should work
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessWithDifferentType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Infer On
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 4) {}
Dim idx As Integer = 2
Dim idx1 As Byte = 1
Dim idx3 As Short = 4
Dim idx4 = 2.0
Dim idx5 As Long = 3L
arr(idx, 3) = 100
arr(idx1, 3) = 100
arr(idx3, 3) = 100
arr(cint(idx4), 3) = 100
arr(cint(idx5), 3) = 100
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 85 (0x55)
.maxstack 5
.locals init (Integer V_0, //idx
Byte V_1, //idx1
Short V_2, //idx3
Double V_3, //idx4
Long V_4) //idx5
IL_0000: ldc.i4.5
IL_0001: ldc.i4.5
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: ldc.i4.2
IL_0008: stloc.0
IL_0009: ldc.i4.1
IL_000a: stloc.1
IL_000b: ldc.i4.4
IL_000c: stloc.2
IL_000d: ldc.r8 2
IL_0016: stloc.3
IL_0017: ldc.i4.3
IL_0018: conv.i8
IL_0019: stloc.s V_4
IL_001b: dup
IL_001c: ldloc.0
IL_001d: ldc.i4.3
IL_001e: ldc.i4.s 100
IL_0020: call "Integer(*,*).Set"
IL_0025: dup
IL_0026: ldloc.1
IL_0027: ldc.i4.3
IL_0028: ldc.i4.s 100
IL_002a: call "Integer(*,*).Set"
IL_002f: dup
IL_0030: ldloc.2
IL_0031: ldc.i4.3
IL_0032: ldc.i4.s 100
IL_0034: call "Integer(*,*).Set"
IL_0039: dup
IL_003a: ldloc.3
IL_003b: call "Function System.Math.Round(Double) As Double"
IL_0040: conv.ovf.i4
IL_0041: ldc.i4.3
IL_0042: ldc.i4.s 100
IL_0044: call "Integer(*,*).Set"
IL_0049: ldloc.s V_4
IL_004b: conv.ovf.i4
IL_004c: ldc.i4.3
IL_004d: ldc.i4.s 100
IL_004f: call "Integer(*,*).Set"
IL_0054: ret
}
]]>)
End Sub
' Passing an element to a function as a byVal or byRef parameter should work
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub ArrayAsArgument()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(,) {{1, 2}}
ElementTaker((arr(0, 1)))
Console.WriteLine(arr(0, 1))
ElementTaker(arr(0, 1))
Console.WriteLine(arr(0, 1))
End Sub
Public Function ElementTaker(ByRef val As Integer) As Integer
val = val + 5
Return val
End Function
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[2
7]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 82 (0x52)
.maxstack 5
.locals init (Integer V_0)
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: call "Integer(*,*).Set"
IL_0010: dup
IL_0011: ldc.i4.0
IL_0012: ldc.i4.1
IL_0013: ldc.i4.2
IL_0014: call "Integer(*,*).Set"
IL_0019: dup
IL_001a: ldc.i4.0
IL_001b: ldc.i4.1
IL_001c: call "Integer(*,*).Get"
IL_0021: stloc.0
IL_0022: ldloca.s V_0
IL_0024: call "Function Module1.ElementTaker(ByRef Integer) As Integer"
IL_0029: pop
IL_002a: dup
IL_002b: ldc.i4.0
IL_002c: ldc.i4.1
IL_002d: call "Integer(*,*).Get"
IL_0032: call "Sub System.Console.WriteLine(Integer)"
IL_0037: dup
IL_0038: ldc.i4.0
IL_0039: ldc.i4.1
IL_003a: call "Integer(*,*).Address"
IL_003f: call "Function Module1.ElementTaker(ByRef Integer) As Integer"
IL_0044: pop
IL_0045: ldc.i4.0
IL_0046: ldc.i4.1
IL_0047: call "Integer(*,*).Get"
IL_004c: call "Sub System.Console.WriteLine(Integer)"
IL_0051: ret
}
]]>)
End Sub
' Passing an element to a function as a byVal or byRef parameter should work
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub ArrayAsArgument_1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(,) {{1, 2}}
ElementTaker(arr(0, 1))
Console.WriteLine(arr(0, 1))
End Sub
Public Function ElementTaker(ByVal val As Integer) As Integer
val = 5
Return val
End Function
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[2]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 5
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: call "Integer(*,*).Set"
IL_0010: dup
IL_0011: ldc.i4.0
IL_0012: ldc.i4.1
IL_0013: ldc.i4.2
IL_0014: call "Integer(*,*).Set"
IL_0019: dup
IL_001a: ldc.i4.0
IL_001b: ldc.i4.1
IL_001c: call "Integer(*,*).Get"
IL_0021: call "Function Module1.ElementTaker(Integer) As Integer"
IL_0026: pop
IL_0027: ldc.i4.0
IL_0028: ldc.i4.1
IL_0029: call "Integer(*,*).Get"
IL_002e: call "Sub System.Console.WriteLine(Integer)"
IL_0033: ret
}
]]>)
End Sub
' Assigning nothing to an array variable
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AssignNothingToArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Public Sub Main()
Dim arr As Integer(,) = New Integer(0, 1) {{1, 2}}
Dim arr1 As Integer(,) = Nothing
arr = Nothing
arr(0, 1) = 3
arr1(0, 1) = 3
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 45 (0x2d)
.maxstack 5
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: call "Integer(*,*).Set"
IL_0010: dup
IL_0011: ldc.i4.0
IL_0012: ldc.i4.1
IL_0013: ldc.i4.2
IL_0014: call "Integer(*,*).Set"
IL_0019: pop
IL_001a: ldnull
IL_001b: ldnull
IL_001c: ldc.i4.0
IL_001d: ldc.i4.1
IL_001e: ldc.i4.3
IL_001f: call "Integer(*,*).Set"
IL_0024: ldc.i4.0
IL_0025: ldc.i4.1
IL_0026: ldc.i4.3
IL_0027: call "Integer(*,*).Set"
IL_002c: ret
}
]]>)
End Sub
' Assigning a smaller array to a bigger array or vice versa should work
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub AssignArrayToArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic.Information
Module Program
Public Sub Main()
Dim arr1 As Integer(,) = New Integer(4, 1) {{1, 2}, {3, 4}, {5, 6}, {8, 9}, {100, 1210}}
Dim arr2 As Integer(,) = New Integer(2, 1) {{6, 7}, {8, 1}, {2, 12}}
arr1 = arr2
Dim arr3 As Integer(,) = New Integer(1, 1) {{6, 7}, {9, 8}}
Dim arr4 As Integer(,) = New Integer(2, 2) {{1, 2, 3}, {4, 5, 6}, {8, 0, 2}}
arr3 = arr4
Console.WriteLine(UBound(arr1, 1))
Console.WriteLine(UBound(arr1, 2))
Console.WriteLine(UBound(arr2, 1))
Console.WriteLine(UBound(arr2, 2))
Console.WriteLine(UBound(arr3, 1))
Console.WriteLine(UBound(arr3, 2))
Console.WriteLine(UBound(arr4, 1))
Console.WriteLine(UBound(arr4, 2))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[2
1
2
1
2
2
2
2]]>)
End Sub
' Access index by enum
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessIndexByEnum()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Public Sub Main()
Dim cube As Integer(,) = New Integer(1, 2) {}
cube(Number.One, Number.Two) = 1
Console.WriteLine(cube(Number.One, Number.Two))
End Sub
End Module
Enum Number
One
Two
End Enum
</file>
</compilation>, expectedOutput:=<![CDATA[1]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 29 (0x1d)
.maxstack 5
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: ldc.i4.1
IL_000b: call "Integer(*,*).Set"
IL_0010: ldc.i4.0
IL_0011: ldc.i4.1
IL_0012: call "Integer(*,*).Get"
IL_0017: call "Sub System.Console.WriteLine(Integer)"
IL_001c: ret
}
]]>)
End Sub
' Assigning a struct variable to an element should work
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AssigningStructToElement()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Public Sub Main()
Dim arr As myStruct(,) = New myStruct(2, 1) {}
Dim ms As myStruct
ms.x = 4
ms.y = 5
arr(2, 0) = ms
End Sub
End Module
Structure myStruct
Public x As Integer
Public y As Integer
End Structure
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 32 (0x20)
.maxstack 4
.locals init (myStruct V_0) //ms
IL_0000: ldc.i4.3
IL_0001: ldc.i4.2
IL_0002: newobj "myStruct(*,*)..ctor"
IL_0007: ldloca.s V_0
IL_0009: ldc.i4.4
IL_000a: stfld "myStruct.x As Integer"
IL_000f: ldloca.s V_0
IL_0011: ldc.i4.5
IL_0012: stfld "myStruct.y As Integer"
IL_0017: ldc.i4.2
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: call "myStruct(*,*).Set"
IL_001f: ret
}
]]>)
End Sub
' Using foreach on a multi-dimensional array
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub ForEachMultiDimensionalArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Public Sub Main()
Dim arr As Integer(,,) = New Integer(,,) {{{1, 2}, {4, 5}}}
For Each i As Integer In arr
Console.WriteLine(i)
Next
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[1
2
4
5]]>)
End Sub
' Overload method by different dimension of array
<Fact>
Public Sub OverloadByDiffDimensionArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Program
Sub Main(args As String())
End Sub
Sub goo(ByRef arg(,,) As Integer)
End Sub
Sub goo(ByRef arg(,) As Integer)
End Sub
Sub goo(ByRef arg() As Integer)
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics()
End Sub
' Multi-dimensional array args could not as entry point
<Fact()>
Public Sub MultidimensionalArgsAsEntryPoint()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class B
Public Shared Sub Main(args As String(,))
End Sub
Public Shared Sub Main()
End Sub
End Class
Class M1
Public Shared Sub Main(args As String(,))
End Sub
End Class
</file>
</compilation>).VerifyDiagnostics()
End Sub
' Declare multi-dimensional and Jagged array
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MixedArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports Microsoft.VisualBasic.Information
Class program
Public Shared Sub Main()
Dim x = New Integer(,)() {}
Dim y(,)() As Byte = New Byte(,)() {{New Byte() {2, 1, 3}}, {New Byte() {3, 0}}}
System.Console.WriteLine(UBound(y, 1))
System.Console.WriteLine(UBound(y, 2))
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[1
0]]>)
End Sub
' Parse an Attribute instance that takes a generic type with a generic argument that is a multi-dimensional array
<Fact>
Public Sub Generic()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
<TypeAttribute(GetType(Program(Of [String])(,)))> _
Public Class Goo
End Class
Class Program(Of T)
End Class
Class TypeAttribute
Inherits Attribute
Public Sub New(value As Type)
End Sub
End Class
</file>
</compilation>).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub MDArrayTypeRef()
Dim csCompilation = CreateCSharpCompilation("CS",
<![CDATA[
public class A
{
public static readonly string[,] dummy = new string[2, 2] { { "", "M" }, { "S", "SM" } };
}]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VB",
<![CDATA[
Module Module1
Sub Main()
Dim x = A.dummy
System.Console.Writeline(x(1,1))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[
SM
]]>)
vbVerifier.VerifyDiagnostics()
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenMultiDimensionalArray
Inherits BasicTestBase
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1, 2) {{1, 2, 3}, {1, 2, 3}}
System.Console.Write(arr(1, 1))
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"),
expectedOutput:="2").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=24 <PrivateImplementationDetails>.618A09BD4B017EFD77C1C5CEA9D47D21EC52DDDEE4892C2A026D588E54AE8F19"
IL_000d: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0012: ldc.i4.1
IL_0013: ldc.i4.1
IL_0014: call "Integer(*,*).Get"
IL_0019: call "Sub System.Console.Write(Integer)"
IL_001e: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer001()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1, 2) {{1, 2, 3}, {1, Integer.Parse("42"), 3}}
System.Console.Write(arr(1, 1))
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"),
expectedOutput:="42").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 49 (0x31)
.maxstack 5
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=24 <PrivateImplementationDetails>.70DE168CE7BA89AB94AD130FD8CB2C588B408E6B5C7FA55F4B322158684A1362"
IL_000d: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: ldc.i4.1
IL_0015: ldstr "42"
IL_001a: call "Function Integer.Parse(String) As Integer"
IL_001f: call "Integer(*,*).Set"
IL_0024: ldc.i4.1
IL_0025: ldc.i4.1
IL_0026: call "Integer(*,*).Get"
IL_002b: call "Sub System.Console.Write(Integer)"
IL_0030: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer002()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1, 2) {{Integer.Parse("1"), Integer.Parse("2"), Integer.Parse("3")}, {Integer.Parse("4"), Integer.Parse("5"), Integer.Parse("6")}}
System.Console.Write(arr(1, 1))
End Sub
End Module
</file>
</compilation>,
expectedOutput:="5").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 128 (0x80)
.maxstack 5
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldstr "1"
IL_000f: call "Function Integer.Parse(String) As Integer"
IL_0014: call "Integer(*,*).Set"
IL_0019: dup
IL_001a: ldc.i4.0
IL_001b: ldc.i4.1
IL_001c: ldstr "2"
IL_0021: call "Function Integer.Parse(String) As Integer"
IL_0026: call "Integer(*,*).Set"
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldc.i4.2
IL_002e: ldstr "3"
IL_0033: call "Function Integer.Parse(String) As Integer"
IL_0038: call "Integer(*,*).Set"
IL_003d: dup
IL_003e: ldc.i4.1
IL_003f: ldc.i4.0
IL_0040: ldstr "4"
IL_0045: call "Function Integer.Parse(String) As Integer"
IL_004a: call "Integer(*,*).Set"
IL_004f: dup
IL_0050: ldc.i4.1
IL_0051: ldc.i4.1
IL_0052: ldstr "5"
IL_0057: call "Function Integer.Parse(String) As Integer"
IL_005c: call "Integer(*,*).Set"
IL_0061: dup
IL_0062: ldc.i4.1
IL_0063: ldc.i4.2
IL_0064: ldstr "6"
IL_0069: call "Function Integer.Parse(String) As Integer"
IL_006e: call "Integer(*,*).Set"
IL_0073: ldc.i4.1
IL_0074: ldc.i4.1
IL_0075: call "Integer(*,*).Get"
IL_007a: call "Sub System.Console.Write(Integer)"
IL_007f: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer003()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1, -1) {{}, {}}
System.Console.Write(arr.Length)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="0").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.0
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: callvirt "Function System.Array.get_Length() As Integer"
IL_000c: call "Sub System.Console.Write(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateWithInitializer004()
CompileAndVerify(
<compilation>
<file name="a.vb">
Public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(-1, -1) {}
System.Console.Write(arr.Length)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="0").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: callvirt "Function System.Array.get_Length() As Integer"
IL_000c: call "Sub System.Console.Write(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreate()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
Dim arr As Integer(,) = New Integer(1,2) {}
System.Console.Write(arr.Length)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="6").
VerifyIL("A.Main",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: callvirt "Function System.Array.get_Length() As Integer"
IL_000c: call "Sub System.Console.Write(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayCreateGeneric()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
goo(Of String)()
c1(Of Long).goo()
End Sub
Class c1(Of T)
Public Shared Sub goo()
Dim arr As T(,) = New T(1, 2) {}
System.Console.Write(arr.Length)
End Sub
End Class
Public Sub goo(Of T)()
Dim arr As T(,) = New T(1, 2) {}
System.Console.Write(arr.Length)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="66").
VerifyIL("A.goo(Of T)()",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "T(*,*)..ctor"
IL_0007: callvirt "Function System.Array.get_Length() As Integer"
IL_000c: call "Sub System.Console.Write(Integer)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub MultiDimensionalArrayGetSetAddress()
CompileAndVerify(
<compilation>
<file name="a.vb">
public Module A
Public Sub Main()
goo(Of String)("hello")
c1(Of Long).goo(123)
End Sub
Class c1(Of T)
Public Shared Sub goo(e as T)
Dim arr As T(,) = New T(2, 3) {}
arr(1, 2) = e
System.Console.Write(arr(1, 2).ToString)
Dim v as T = arr(1, 2)
System.Console.Write(v.ToString)
End Sub
End Class
Public Sub goo(Of T)(e as T)
Dim arr As T(,) = New T(2, 3) {}
arr(1, 2) = e
System.Console.Write(arr(1, 2).ToString)
Dim v as T = arr(1, 2)
System.Console.Write(v.ToString)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hellohello123123").
VerifyIL("A.goo(Of T)(T)",
<![CDATA[
{
// Code size 69 (0x45)
.maxstack 5
.locals init (T V_0) //v
IL_0000: ldc.i4.3
IL_0001: ldc.i4.4
IL_0002: newobj "T(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: ldc.i4.2
IL_000a: ldarg.0
IL_000b: call "T(*,*).Set"
IL_0010: dup
IL_0011: ldc.i4.1
IL_0012: ldc.i4.2
IL_0013: readonly.
IL_0015: call "T(*,*).Address"
IL_001a: constrained. "T"
IL_0020: callvirt "Function Object.ToString() As String"
IL_0025: call "Sub System.Console.Write(String)"
IL_002a: ldc.i4.1
IL_002b: ldc.i4.2
IL_002c: call "T(*,*).Get"
IL_0031: stloc.0
IL_0032: ldloca.s V_0
IL_0034: constrained. "T"
IL_003a: callvirt "Function Object.ToString() As String"
IL_003f: call "Sub System.Console.Write(String)"
IL_0044: ret
}
]]>)
End Sub
<WorkItem(542259, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542259")>
<Fact>
Public Sub MixMultiAndJaggedArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim x = New Exception(,,) {}
Dim y = New Exception(,,) {{{}}}
Dim z = New Exception(,)() {}
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics()
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim myArray1 As Integer(,) = New Integer(-1, -1) {}
Dim myArray2 As Integer(,) = New Integer(3, 1) {}
Dim myArray3 As Integer(,,) = New Integer(3, 1, 2) {}
Dim myArray4 As Integer(,) = New Integer(2147483646, 2147483646) {}
Dim myArray5 As Integer(,) = New Integer(2147483648UI - 1, 2147483648UI - 1) {}
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 58 (0x3a)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: pop
IL_0008: ldc.i4.4
IL_0009: ldc.i4.2
IL_000a: newobj "Integer(*,*)..ctor"
IL_000f: pop
IL_0010: ldc.i4.4
IL_0011: ldc.i4.2
IL_0012: ldc.i4.3
IL_0013: newobj "Integer(*,*,*)..ctor"
IL_0018: pop
IL_0019: ldc.i4 0x7fffffff
IL_001e: ldc.i4 0x7fffffff
IL_0023: newobj "Integer(*,*)..ctor"
IL_0028: pop
IL_0029: ldc.i4 0x80000000
IL_002e: ldc.i4 0x80000000
IL_0033: newobj "Integer(*,*)..ctor"
IL_0038: pop
IL_0039: ret
}
]]>)
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray_1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim myArray6 As Integer(,,,,) = Nothing
myArray6 = New Integer(4, 5, 8, 3, 6) {}
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 13 (0xd)
.maxstack 5
IL_0000: ldc.i4.5
IL_0001: ldc.i4.6
IL_0002: ldc.i4.s 9
IL_0004: ldc.i4.4
IL_0005: ldc.i4.7
IL_0006: newobj "Integer(*,*,*,*,*)..ctor"
IL_000b: pop
IL_000c: ret
}
]]>)
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray_2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Private Delegate Sub myDelegate(myString As String)
Sub Main()
Dim myArray1 As myInterface(,) = New myInterface(3, 1) {}
Dim myArray2 As myDelegate(,) = New myDelegate(3, 1) {}
Dim myArray3 = New Integer(Number.One, Number.Two) {}
End Sub
End Module
Interface myInterface
End Interface
Enum Number
One
Two
End Enum
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 25 (0x19)
.maxstack 2
IL_0000: ldc.i4.4
IL_0001: ldc.i4.2
IL_0002: newobj "myInterface(*,*)..ctor"
IL_0007: pop
IL_0008: ldc.i4.4
IL_0009: ldc.i4.2
IL_000a: newobj "Module1.myDelegate(*,*)..ctor"
IL_000f: pop
IL_0010: ldc.i4.1
IL_0011: ldc.i4.2
IL_0012: newobj "Integer(*,*)..ctor"
IL_0017: pop
IL_0018: ret
}
]]>)
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray_3()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class C1
Public Shared Sub Main()
Dim myLength As Integer = 3
Dim arr As Integer(,) = New Integer(myLength, 1) {}
End Sub
Private Class A
Private x As Integer = 1
Private arr As Integer(,) = New Integer(x, 4) {}
End Class
End Class
</file>
</compilation>).VerifyIL("C1.Main", <![CDATA[
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldc.i4.3
IL_0001: ldc.i4.1
IL_0002: add.ovf
IL_0003: ldc.i4.2
IL_0004: newobj "Integer(*,*)..ctor"
IL_0009: pop
IL_000a: ret
}
]]>)
End Sub
' Declaration multi- dimensional array
<Fact>
Public Sub DeclarationmultiDimensionalArray_5()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim myArray8 As Integer(,) = New Integer(-1, 4) {}
Dim arrDouble#(,) = New Double(1, 2) {}
Dim arrDecimal@(,) = New Decimal(1, 2) {}
Dim arrString$(,) = New String(1, 2) {}
Dim arrInteger%(,) = New Integer(1, 2) {}
Dim arrLong&(,) = New Long(1, 2) {}
Dim arrSingle!(,) = New Single(1, 2) {}
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 57 (0x39)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.5
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: pop
IL_0008: ldc.i4.2
IL_0009: ldc.i4.3
IL_000a: newobj "Double(*,*)..ctor"
IL_000f: pop
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: newobj "Decimal(*,*)..ctor"
IL_0017: pop
IL_0018: ldc.i4.2
IL_0019: ldc.i4.3
IL_001a: newobj "String(*,*)..ctor"
IL_001f: pop
IL_0020: ldc.i4.2
IL_0021: ldc.i4.3
IL_0022: newobj "Integer(*,*)..ctor"
IL_0027: pop
IL_0028: ldc.i4.2
IL_0029: ldc.i4.3
IL_002a: newobj "Long(*,*)..ctor"
IL_002f: pop
IL_0030: ldc.i4.2
IL_0031: ldc.i4.3
IL_0032: newobj "Single(*,*)..ctor"
IL_0037: pop
IL_0038: ret
}
]]>)
End Sub
' Initialize multi- dimensional array
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub InitializemultiDimensionalArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Infer On
Imports System
Imports Microsoft.VisualBasic.Information
Module Module1
Sub Main()
Dim myArray1 As Integer(,,) = {{{0, 1}, {2, 3}}, {{4, 5}, {6, 7}}}
Dim myArray2 As Single(,) = New Single(2, 1) {{CSng(1.0), CSng(2.0)}, {CSng(3.0), CSng(4.0)}, {CSng(5.0), CSng(6.0)}}
Dim myArray3 As Long(,) = New Long(,) {{1, 2}, {3, 4}, {5, 6}}
Dim myArray4 As Char(,)
myArray4 = New Char(2, 1) {{"1"c, "2"c}, {"3"c, "4"c}, {"5"c, "6"c}}
Dim myArray5 As Decimal(,)
myArray5 = New Decimal(,) {{CDec(1.0), CDec(2.0)}, {CDec(3.0), CDec(4.0)}, {CDec(5.0), CDec(6.0)}}
Dim myArray6 As Integer(,) = New Integer(-1, -1) {}
Dim myArray7 As Integer(,) = New Integer(,) {{}}
Dim myArray8 As Integer(,,) = New Integer(,,) {{{}}}
Dim myArray9 As String(,) = New String(2, 1) {{"a"c, "b"c}, {"c"c, "d"c}, {"e"c, "f"c}}
Console.WriteLine(UBound(myArray1, 1))
Console.WriteLine(UBound(myArray1, 2))
Console.WriteLine(UBound(myArray1, 3))
Console.WriteLine(UBound(myArray2, 1))
Console.WriteLine(UBound(myArray2, 2))
Console.WriteLine(UBound(myArray3, 1))
Console.WriteLine(UBound(myArray3, 2))
Console.WriteLine(UBound(myArray4, 1))
Console.WriteLine(UBound(myArray4, 2))
Console.WriteLine(UBound(myArray5, 1))
Console.WriteLine(UBound(myArray5, 2))
Console.WriteLine(UBound(myArray6, 1))
Console.WriteLine(UBound(myArray6, 2))
Console.WriteLine(UBound(myArray7, 1))
Console.WriteLine(UBound(myArray7, 2))
Console.WriteLine(UBound(myArray8, 1))
Console.WriteLine(UBound(myArray8, 2))
Console.WriteLine(UBound(myArray8, 3))
Console.WriteLine(UBound(myArray9, 1))
Console.WriteLine(UBound(myArray9, 2))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[1
1
1
2
1
2
1
2
1
2
1
-1
-1
0
-1
0
0
-1
2
1]]>)
End Sub
' Use different kinds of var as index upper bound
<Fact>
Public Sub DifferentVarAsBound()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Infer On
Imports Microsoft.VisualBasic.Information
Module Module1
Property prop As Integer
Sub Main(args As String())
Dim arr1(3, prop) As Integer
Dim arr2(3, fun()) As Integer
Dim x = fun()
Dim arr3(x, 1) As Integer
Dim z() As Integer
Dim y() As Integer
Dim replyCounts(,) As Short = New Short(UBound(z, 1), UBound(y, 1)) {}
End Sub
Function fun() As Integer
Return 3
End Function
Sub goo(x As Integer)
Dim arr1(3, x) As Integer
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 67 (0x43)
.maxstack 3
.locals init (Integer() V_0, //z
Integer() V_1) //y
IL_0000: ldc.i4.4
IL_0001: call "Function Module1.get_prop() As Integer"
IL_0006: ldc.i4.1
IL_0007: add.ovf
IL_0008: newobj "Integer(*,*)..ctor"
IL_000d: pop
IL_000e: ldc.i4.4
IL_000f: call "Function Module1.fun() As Integer"
IL_0014: ldc.i4.1
IL_0015: add.ovf
IL_0016: newobj "Integer(*,*)..ctor"
IL_001b: pop
IL_001c: call "Function Module1.fun() As Integer"
IL_0021: ldc.i4.1
IL_0022: add.ovf
IL_0023: ldc.i4.2
IL_0024: newobj "Integer(*,*)..ctor"
IL_0029: pop
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: call "Function Microsoft.VisualBasic.Information.UBound(System.Array, Integer) As Integer"
IL_0031: ldc.i4.1
IL_0032: add.ovf
IL_0033: ldloc.1
IL_0034: ldc.i4.1
IL_0035: call "Function Microsoft.VisualBasic.Information.UBound(System.Array, Integer) As Integer"
IL_003a: ldc.i4.1
IL_003b: add.ovf
IL_003c: newobj "Short(*,*)..ctor"
IL_0041: pop
IL_0042: ret
}
]]>)
End Sub
' Specify lower bound and up bound for multi-dimensional array
<Fact>
Public Sub SpecifyLowerAndUpBound()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Module1
Property prop As Integer
Sub Main(args As String())
Dim arr1(0 To 0, 0 To -1) As Integer
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldc.i4.0
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: pop
IL_0008: ret
}
]]>)
End Sub
' Array creation expression can be part of an anonymous object creation expression
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub ArrayCreateAsAnonymous()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Infer On
Imports System
Imports Microsoft.VisualBasic.Information
Module Module1
Sub Main(args As String())
Dim a0 = New With {
Key.b4 = New Integer(1, 2) {}, _
Key.b5 = New Integer(1, 1) {{1, 2}, {2, 3}},
Key.b6 = New Integer()() {New Integer(1) {}, New Integer(2) {}},
Key.b7 = New Integer(2)() {},
Key.b8 = New Integer(1)() {New Integer(0) {}, New Integer(1) {}},
Key.b9 = New Integer() {1, 2, 3},
Key.b10 = New Integer(,) {{1, 2}, {2, 3}}
}
Console.WriteLine(UBound(a0.b4, 1))
Console.WriteLine(UBound(a0.b4, 2))
Console.WriteLine(UBound(a0.b5, 1))
Console.WriteLine(UBound(a0.b5, 2))
Console.WriteLine(UBound(a0.b6, 1))
Console.WriteLine(UBound(a0.b7, 1))
Console.WriteLine(UBound(a0.b8, 1))
Console.WriteLine(UBound(a0.b9, 1))
Console.WriteLine(UBound(a0.b10, 1))
Console.WriteLine(UBound(a0.b10, 2))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[1
2
1
1
1
2
1
2
1
1]]>)
End Sub
' Accessing an array's 0th element should work fine
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessZero()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 4) {}
arr(0, 0) = 5
Console.WriteLine(arr(0, 0))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[5]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 29 (0x1d)
.maxstack 5
IL_0000: ldc.i4.5
IL_0001: ldc.i4.5
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.5
IL_000b: call "Integer(*,*).Set"
IL_0010: ldc.i4.0
IL_0011: ldc.i4.0
IL_0012: call "Integer(*,*).Get"
IL_0017: call "Sub System.Console.WriteLine(Integer)"
IL_001c: ret
}
]]>)
End Sub
' Accessing an array's maxlength element should work fine
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessMaxLength()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 3) {}
arr(4, 3) = 5
Console.WriteLine(arr(4, 3))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[5]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 29 (0x1d)
.maxstack 5
IL_0000: ldc.i4.5
IL_0001: ldc.i4.4
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.4
IL_0009: ldc.i4.3
IL_000a: ldc.i4.5
IL_000b: call "Integer(*,*).Set"
IL_0010: ldc.i4.4
IL_0011: ldc.i4.3
IL_0012: call "Integer(*,*).Get"
IL_0017: call "Sub System.Console.WriteLine(Integer)"
IL_001c: ret
}
]]>)
End Sub
' Accessing an array's -1 element should throw an exception
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessLessThanMin()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 4) {}
Try
arr(-1, 1) = 5
arr(1, -1) = 5
arr(-1, -1) = 5
Catch generatedExceptionName As System.IndexOutOfRangeException
End Try
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 4
.locals init (Integer(,) V_0, //arr
System.IndexOutOfRangeException V_1) //generatedExceptionName
IL_0000: ldc.i4.5
IL_0001: ldc.i4.5
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: stloc.0
.try
{
IL_0008: ldloc.0
IL_0009: ldc.i4.m1
IL_000a: ldc.i4.1
IL_000b: ldc.i4.5
IL_000c: call "Integer(*,*).Set"
IL_0011: ldloc.0
IL_0012: ldc.i4.1
IL_0013: ldc.i4.m1
IL_0014: ldc.i4.5
IL_0015: call "Integer(*,*).Set"
IL_001a: ldloc.0
IL_001b: ldc.i4.m1
IL_001c: ldc.i4.m1
IL_001d: ldc.i4.5
IL_001e: call "Integer(*,*).Set"
IL_0023: leave.s IL_0033
}
catch System.IndexOutOfRangeException
{
IL_0025: dup
IL_0026: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_002b: stloc.1
IL_002c: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0031: leave.s IL_0033
}
IL_0033: ret
}
]]>)
End Sub
' Accessing an array's maxlength+1 element should throw an exception
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessGreaterThanMax()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 3) {}
Try
arr(5, 3) = 5
arr(4, 4) = 5
arr(5, 4) = 5
Catch
End Try
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 50 (0x32)
.maxstack 4
.locals init (Integer(,) V_0) //arr
IL_0000: ldc.i4.5
IL_0001: ldc.i4.4
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: stloc.0
.try
{
IL_0008: ldloc.0
IL_0009: ldc.i4.5
IL_000a: ldc.i4.3
IL_000b: ldc.i4.5
IL_000c: call "Integer(*,*).Set"
IL_0011: ldloc.0
IL_0012: ldc.i4.4
IL_0013: ldc.i4.4
IL_0014: ldc.i4.5
IL_0015: call "Integer(*,*).Set"
IL_001a: ldloc.0
IL_001b: ldc.i4.5
IL_001c: ldc.i4.4
IL_001d: ldc.i4.5
IL_001e: call "Integer(*,*).Set"
IL_0023: leave.s IL_0031
}
catch System.Exception
{
IL_0025: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_002a: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_002f: leave.s IL_0031
}
IL_0031: ret
}
]]>)
End Sub
' Accessing an array's index with a variable of type int, short, byte should work
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessWithDifferentType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Infer On
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(4, 4) {}
Dim idx As Integer = 2
Dim idx1 As Byte = 1
Dim idx3 As Short = 4
Dim idx4 = 2.0
Dim idx5 As Long = 3L
arr(idx, 3) = 100
arr(idx1, 3) = 100
arr(idx3, 3) = 100
arr(cint(idx4), 3) = 100
arr(cint(idx5), 3) = 100
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 85 (0x55)
.maxstack 5
.locals init (Integer V_0, //idx
Byte V_1, //idx1
Short V_2, //idx3
Double V_3, //idx4
Long V_4) //idx5
IL_0000: ldc.i4.5
IL_0001: ldc.i4.5
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: ldc.i4.2
IL_0008: stloc.0
IL_0009: ldc.i4.1
IL_000a: stloc.1
IL_000b: ldc.i4.4
IL_000c: stloc.2
IL_000d: ldc.r8 2
IL_0016: stloc.3
IL_0017: ldc.i4.3
IL_0018: conv.i8
IL_0019: stloc.s V_4
IL_001b: dup
IL_001c: ldloc.0
IL_001d: ldc.i4.3
IL_001e: ldc.i4.s 100
IL_0020: call "Integer(*,*).Set"
IL_0025: dup
IL_0026: ldloc.1
IL_0027: ldc.i4.3
IL_0028: ldc.i4.s 100
IL_002a: call "Integer(*,*).Set"
IL_002f: dup
IL_0030: ldloc.2
IL_0031: ldc.i4.3
IL_0032: ldc.i4.s 100
IL_0034: call "Integer(*,*).Set"
IL_0039: dup
IL_003a: ldloc.3
IL_003b: call "Function System.Math.Round(Double) As Double"
IL_0040: conv.ovf.i4
IL_0041: ldc.i4.3
IL_0042: ldc.i4.s 100
IL_0044: call "Integer(*,*).Set"
IL_0049: ldloc.s V_4
IL_004b: conv.ovf.i4
IL_004c: ldc.i4.3
IL_004d: ldc.i4.s 100
IL_004f: call "Integer(*,*).Set"
IL_0054: ret
}
]]>)
End Sub
' Passing an element to a function as a byVal or byRef parameter should work
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub ArrayAsArgument()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(,) {{1, 2}}
ElementTaker((arr(0, 1)))
Console.WriteLine(arr(0, 1))
ElementTaker(arr(0, 1))
Console.WriteLine(arr(0, 1))
End Sub
Public Function ElementTaker(ByRef val As Integer) As Integer
val = val + 5
Return val
End Function
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[2
7]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 82 (0x52)
.maxstack 5
.locals init (Integer V_0)
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: call "Integer(*,*).Set"
IL_0010: dup
IL_0011: ldc.i4.0
IL_0012: ldc.i4.1
IL_0013: ldc.i4.2
IL_0014: call "Integer(*,*).Set"
IL_0019: dup
IL_001a: ldc.i4.0
IL_001b: ldc.i4.1
IL_001c: call "Integer(*,*).Get"
IL_0021: stloc.0
IL_0022: ldloca.s V_0
IL_0024: call "Function Module1.ElementTaker(ByRef Integer) As Integer"
IL_0029: pop
IL_002a: dup
IL_002b: ldc.i4.0
IL_002c: ldc.i4.1
IL_002d: call "Integer(*,*).Get"
IL_0032: call "Sub System.Console.WriteLine(Integer)"
IL_0037: dup
IL_0038: ldc.i4.0
IL_0039: ldc.i4.1
IL_003a: call "Integer(*,*).Address"
IL_003f: call "Function Module1.ElementTaker(ByRef Integer) As Integer"
IL_0044: pop
IL_0045: ldc.i4.0
IL_0046: ldc.i4.1
IL_0047: call "Integer(*,*).Get"
IL_004c: call "Sub System.Console.WriteLine(Integer)"
IL_0051: ret
}
]]>)
End Sub
' Passing an element to a function as a byVal or byRef parameter should work
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub ArrayAsArgument_1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Dim arr As Integer(,) = New Integer(,) {{1, 2}}
ElementTaker(arr(0, 1))
Console.WriteLine(arr(0, 1))
End Sub
Public Function ElementTaker(ByVal val As Integer) As Integer
val = 5
Return val
End Function
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[2]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 5
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: call "Integer(*,*).Set"
IL_0010: dup
IL_0011: ldc.i4.0
IL_0012: ldc.i4.1
IL_0013: ldc.i4.2
IL_0014: call "Integer(*,*).Set"
IL_0019: dup
IL_001a: ldc.i4.0
IL_001b: ldc.i4.1
IL_001c: call "Integer(*,*).Get"
IL_0021: call "Function Module1.ElementTaker(Integer) As Integer"
IL_0026: pop
IL_0027: ldc.i4.0
IL_0028: ldc.i4.1
IL_0029: call "Integer(*,*).Get"
IL_002e: call "Sub System.Console.WriteLine(Integer)"
IL_0033: ret
}
]]>)
End Sub
' Assigning nothing to an array variable
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AssignNothingToArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Public Sub Main()
Dim arr As Integer(,) = New Integer(0, 1) {{1, 2}}
Dim arr1 As Integer(,) = Nothing
arr = Nothing
arr(0, 1) = 3
arr1(0, 1) = 3
End Sub
End Module
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 45 (0x2d)
.maxstack 5
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: call "Integer(*,*).Set"
IL_0010: dup
IL_0011: ldc.i4.0
IL_0012: ldc.i4.1
IL_0013: ldc.i4.2
IL_0014: call "Integer(*,*).Set"
IL_0019: pop
IL_001a: ldnull
IL_001b: ldnull
IL_001c: ldc.i4.0
IL_001d: ldc.i4.1
IL_001e: ldc.i4.3
IL_001f: call "Integer(*,*).Set"
IL_0024: ldc.i4.0
IL_0025: ldc.i4.1
IL_0026: ldc.i4.3
IL_0027: call "Integer(*,*).Set"
IL_002c: ret
}
]]>)
End Sub
' Assigning a smaller array to a bigger array or vice versa should work
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub AssignArrayToArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic.Information
Module Program
Public Sub Main()
Dim arr1 As Integer(,) = New Integer(4, 1) {{1, 2}, {3, 4}, {5, 6}, {8, 9}, {100, 1210}}
Dim arr2 As Integer(,) = New Integer(2, 1) {{6, 7}, {8, 1}, {2, 12}}
arr1 = arr2
Dim arr3 As Integer(,) = New Integer(1, 1) {{6, 7}, {9, 8}}
Dim arr4 As Integer(,) = New Integer(2, 2) {{1, 2, 3}, {4, 5, 6}, {8, 0, 2}}
arr3 = arr4
Console.WriteLine(UBound(arr1, 1))
Console.WriteLine(UBound(arr1, 2))
Console.WriteLine(UBound(arr2, 1))
Console.WriteLine(UBound(arr2, 2))
Console.WriteLine(UBound(arr3, 1))
Console.WriteLine(UBound(arr3, 2))
Console.WriteLine(UBound(arr4, 1))
Console.WriteLine(UBound(arr4, 2))
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[2
1
2
1
2
2
2
2]]>)
End Sub
' Access index by enum
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AccessIndexByEnum()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Public Sub Main()
Dim cube As Integer(,) = New Integer(1, 2) {}
cube(Number.One, Number.Two) = 1
Console.WriteLine(cube(Number.One, Number.Two))
End Sub
End Module
Enum Number
One
Two
End Enum
</file>
</compilation>, expectedOutput:=<![CDATA[1]]>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 29 (0x1d)
.maxstack 5
IL_0000: ldc.i4.2
IL_0001: ldc.i4.3
IL_0002: newobj "Integer(*,*)..ctor"
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: ldc.i4.1
IL_000b: call "Integer(*,*).Set"
IL_0010: ldc.i4.0
IL_0011: ldc.i4.1
IL_0012: call "Integer(*,*).Get"
IL_0017: call "Sub System.Console.WriteLine(Integer)"
IL_001c: ret
}
]]>)
End Sub
' Assigning a struct variable to an element should work
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub AssigningStructToElement()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Public Sub Main()
Dim arr As myStruct(,) = New myStruct(2, 1) {}
Dim ms As myStruct
ms.x = 4
ms.y = 5
arr(2, 0) = ms
End Sub
End Module
Structure myStruct
Public x As Integer
Public y As Integer
End Structure
</file>
</compilation>).VerifyIL("Module1.Main", <![CDATA[
{
// Code size 32 (0x20)
.maxstack 4
.locals init (myStruct V_0) //ms
IL_0000: ldc.i4.3
IL_0001: ldc.i4.2
IL_0002: newobj "myStruct(*,*)..ctor"
IL_0007: ldloca.s V_0
IL_0009: ldc.i4.4
IL_000a: stfld "myStruct.x As Integer"
IL_000f: ldloca.s V_0
IL_0011: ldc.i4.5
IL_0012: stfld "myStruct.y As Integer"
IL_0017: ldc.i4.2
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: call "myStruct(*,*).Set"
IL_001f: ret
}
]]>)
End Sub
' Using foreach on a multi-dimensional array
<WorkItem(528752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528752")>
<Fact>
Public Sub ForEachMultiDimensionalArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Module1
Public Sub Main()
Dim arr As Integer(,,) = New Integer(,,) {{{1, 2}, {4, 5}}}
For Each i As Integer In arr
Console.WriteLine(i)
Next
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[1
2
4
5]]>)
End Sub
' Overload method by different dimension of array
<Fact>
Public Sub OverloadByDiffDimensionArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Program
Sub Main(args As String())
End Sub
Sub goo(ByRef arg(,,) As Integer)
End Sub
Sub goo(ByRef arg(,) As Integer)
End Sub
Sub goo(ByRef arg() As Integer)
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics()
End Sub
' Multi-dimensional array args could not as entry point
<Fact()>
Public Sub MultidimensionalArgsAsEntryPoint()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class B
Public Shared Sub Main(args As String(,))
End Sub
Public Shared Sub Main()
End Sub
End Class
Class M1
Public Shared Sub Main(args As String(,))
End Sub
End Class
</file>
</compilation>).VerifyDiagnostics()
End Sub
' Declare multi-dimensional and Jagged array
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MixedArray()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports Microsoft.VisualBasic.Information
Class program
Public Shared Sub Main()
Dim x = New Integer(,)() {}
Dim y(,)() As Byte = New Byte(,)() {{New Byte() {2, 1, 3}}, {New Byte() {3, 0}}}
System.Console.WriteLine(UBound(y, 1))
System.Console.WriteLine(UBound(y, 2))
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[1
0]]>)
End Sub
' Parse an Attribute instance that takes a generic type with a generic argument that is a multi-dimensional array
<Fact>
Public Sub Generic()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
<TypeAttribute(GetType(Program(Of [String])(,)))> _
Public Class Goo
End Class
Class Program(Of T)
End Class
Class TypeAttribute
Inherits Attribute
Public Sub New(value As Type)
End Sub
End Class
</file>
</compilation>).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub MDArrayTypeRef()
Dim csCompilation = CreateCSharpCompilation("CS",
<![CDATA[
public class A
{
public static readonly string[,] dummy = new string[2, 2] { { "", "M" }, { "S", "SM" } };
}]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VB",
<![CDATA[
Module Module1
Sub Main()
Dim x = A.dummy
System.Console.Writeline(x(1,1))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[
SM
]]>)
vbVerifier.VerifyDiagnostics()
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Compilers/Test/Core/CompilationVerifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using ICSharpCode.Decompiler.Metadata;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.DiaSymReader.Tools;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class CompilationVerifier
{
private readonly Compilation _compilation;
private CompilationTestData _testData;
private readonly IEnumerable<ModuleData> _dependencies;
private ImmutableArray<Diagnostic> _diagnostics;
private IModuleSymbol _lazyModuleSymbol;
private IList<ModuleData> _allModuleData;
public ImmutableArray<byte> EmittedAssemblyData;
public ImmutableArray<byte> EmittedAssemblyPdb;
private readonly Func<IModuleSymbol, CompilationTestData.MethodData, IReadOnlyDictionary<int, string>, bool, string> _visualizeRealIL;
internal CompilationVerifier(
Compilation compilation,
Func<IModuleSymbol, CompilationTestData.MethodData, IReadOnlyDictionary<int, string>, bool, string> visualizeRealIL = null,
IEnumerable<ModuleData> dependencies = null)
{
_compilation = compilation;
_dependencies = dependencies;
_visualizeRealIL = visualizeRealIL;
}
internal CompilationTestData TestData => _testData;
public Compilation Compilation => _compilation;
internal ImmutableArray<Diagnostic> Diagnostics => _diagnostics;
internal Metadata GetMetadata()
{
if (EmittedAssemblyData == null)
{
throw new InvalidOperationException("You must call Emit before calling GetAllModuleMetadata.");
}
if (_compilation.Options.OutputKind.IsNetModule())
{
var metadata = ModuleMetadata.CreateFromImage(EmittedAssemblyData);
metadata.Module.PretendThereArentNoPiaLocalTypes();
return metadata;
}
else
{
var images = new List<ImmutableArray<byte>>
{
EmittedAssemblyData
};
if (_allModuleData != null)
{
images.AddRange(_allModuleData.Where(m => m.Kind == OutputKind.NetModule).Select(m => m.Image));
}
return AssemblyMetadata.Create(images.Select(image =>
{
var metadata = ModuleMetadata.CreateFromImage(image);
metadata.Module.PretendThereArentNoPiaLocalTypes();
return metadata;
}));
}
}
public string Dump(string methodName = null)
{
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleFullName = Emit(testEnvironment, manifestResources: null, EmitOptions.Default);
IList<ModuleData> moduleDatas = testEnvironment.GetAllModuleData();
var mainModule = moduleDatas.Single(md => md.FullName == mainModuleFullName);
RuntimeEnvironmentUtilities.DumpAssemblyData(moduleDatas, out var dumpDir);
string extension = mainModule.Kind == OutputKind.ConsoleApplication ? ".exe" : ".dll";
string modulePath = Path.Combine(dumpDir, mainModule.SimpleName + extension);
var decompiler = new ICSharpCode.Decompiler.CSharp.CSharpDecompiler(modulePath,
new ICSharpCode.Decompiler.DecompilerSettings() { AsyncAwait = false });
if (methodName != null)
{
var map = new Dictionary<string, ICSharpCode.Decompiler.TypeSystem.IMethod>();
listMethods(decompiler.TypeSystem.MainModule.RootNamespace, map);
if (map.TryGetValue(methodName, out var method))
{
return decompiler.DecompileAsString(method.MetadataToken);
}
else
{
throw new Exception($"Didn't find method '{methodName}'. Available/distinguishable methods are: \r\n{string.Join("\r\n", map.Keys)}");
}
}
return decompiler.DecompileWholeModuleAsString();
}
void listMethods(ICSharpCode.Decompiler.TypeSystem.INamespace @namespace, Dictionary<string, ICSharpCode.Decompiler.TypeSystem.IMethod> result)
{
foreach (var nestedNS in @namespace.ChildNamespaces)
{
if (nestedNS.FullName != "System" &&
nestedNS.FullName != "Microsoft")
{
listMethods(nestedNS, result);
}
}
foreach (var type in @namespace.Types)
{
listMethodsInType(type, result);
}
}
void listMethodsInType(ICSharpCode.Decompiler.TypeSystem.ITypeDefinition type, Dictionary<string, ICSharpCode.Decompiler.TypeSystem.IMethod> result)
{
foreach (var nestedType in type.NestedTypes)
{
listMethodsInType(nestedType, result);
}
foreach (var method in type.Methods)
{
if (result.ContainsKey(method.FullName))
{
// There is a bug with FullName on methods in generic types
result.Remove(method.FullName);
}
else
{
result.Add(method.FullName, method);
}
}
}
}
/// <summary>
/// Asserts that the emitted IL for a type is the same as the expected IL.
/// Many core library types are in different assemblies on .Net Framework, and .Net Core.
/// Therefore this test is likely to fail unless you only run it only only on one of these frameworks,
/// or you run it on both, but provide a different expected output string for each.
/// See <see cref="ExecutionConditionUtil"/>.
/// </summary>
/// <param name="typeName">The non-fully-qualified name of the type</param>
/// <param name="expected">The expected IL</param>
public void VerifyTypeIL(string typeName, string expected)
{
var output = new ICSharpCode.Decompiler.PlainTextOutput();
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleFullName = Emit(testEnvironment, manifestResources: null, EmitOptions.Default);
IList<ModuleData> moduleData = testEnvironment.GetAllModuleData();
var mainModule = moduleData.Single(md => md.FullName == mainModuleFullName);
using (var moduleMetadata = ModuleMetadata.CreateFromImage(testEnvironment.GetMainImage()))
{
var peFile = new PEFile(mainModuleFullName, moduleMetadata.Module.PEReaderOpt);
var metadataReader = moduleMetadata.GetMetadataReader();
bool found = false;
foreach (var typeDefHandle in metadataReader.TypeDefinitions)
{
var typeDef = metadataReader.GetTypeDefinition(typeDefHandle);
if (metadataReader.GetString(typeDef.Name) == typeName)
{
var disassembler = new ICSharpCode.Decompiler.Disassembler.ReflectionDisassembler(output, default);
disassembler.DisassembleType(peFile, typeDefHandle);
found = true;
break;
}
}
Assert.True(found, "Could not find type named " + typeName);
}
}
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, output.ToString(), escapeQuotes: false);
}
public void Emit(string expectedOutput, int? expectedReturnCode, string[] args, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, Verification peVerify, SignatureDescription[] expectedSignatures)
{
using var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies);
string mainModuleName = Emit(testEnvironment, manifestResources, emitOptions);
_allModuleData = testEnvironment.GetAllModuleData();
testEnvironment.Verify(peVerify);
if (expectedSignatures != null)
{
MetadataSignatureUnitTestHelper.VerifyMemberSignatures(testEnvironment, expectedSignatures);
}
if (expectedOutput != null || expectedReturnCode != null)
{
var returnCode = testEnvironment.Execute(mainModuleName, args, expectedOutput);
if (expectedReturnCode is int exCode)
{
Assert.Equal(exCode, returnCode);
}
}
}
// TODO(tomat): Fold into CompileAndVerify.
// Replace bool verify parameter with string[] expectedPeVerifyOutput. If null, no verification. If empty verify have to succeed. Otherwise compare errors.
public void EmitAndVerify(params string[] expectedPeVerifyOutput)
{
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleName = Emit(testEnvironment, null, null);
string[] actualOutput = testEnvironment.VerifyModules(new[] { mainModuleName });
Assert.Equal(expectedPeVerifyOutput, actualOutput);
}
}
private string Emit(IRuntimeEnvironment testEnvironment, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions)
{
testEnvironment.Emit(_compilation, manifestResources, emitOptions);
_diagnostics = testEnvironment.GetDiagnostics();
EmittedAssemblyData = testEnvironment.GetMainImage();
EmittedAssemblyPdb = testEnvironment.GetMainPdb();
_testData = ((IInternalRuntimeEnvironment)testEnvironment).GetCompilationTestData();
return _compilation.Assembly.Identity.GetDisplayName();
}
public CompilationVerifier VerifyIL(
string qualifiedMethodName,
XCData expectedIL,
bool realIL = false,
string sequencePoints = null,
[CallerFilePath] string callerPath = null,
[CallerLineNumber] int callerLine = 0)
{
return VerifyILImpl(qualifiedMethodName, expectedIL.Value, realIL, sequencePoints, callerPath, callerLine, escapeQuotes: false);
}
public CompilationVerifier VerifyIL(
string qualifiedMethodName,
string expectedIL,
bool realIL = false,
string sequencePoints = null,
[CallerFilePath] string callerPath = null,
[CallerLineNumber] int callerLine = 0,
string source = null)
{
return VerifyILImpl(qualifiedMethodName, expectedIL, realIL, sequencePoints, callerPath, callerLine, escapeQuotes: true, source: source);
}
public CompilationVerifier VerifyMissing(
string qualifiedMethodName)
{
Assert.False(_testData.TryGetMethodData(qualifiedMethodName, out _));
return this;
}
public void VerifyLocalSignature(
string qualifiedMethodName,
string expectedSignature,
[CallerLineNumber] int callerLine = 0,
[CallerFilePath] string callerPath = null)
{
var ilBuilder = _testData.GetMethodData(qualifiedMethodName).ILBuilder;
string actualSignature = ILBuilderVisualizer.LocalSignatureToString(ilBuilder);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, actualSignature, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
/// <summary>
/// Visualizes the IL for a given method, and ensures that it matches the expected IL.
/// </summary>
/// <param name="realIL">Controls whether the IL stream contains pseudo-tokens or real tokens.</param>
private CompilationVerifier VerifyILImpl(
string qualifiedMethodName,
string expectedIL,
bool realIL,
string sequencePoints,
string callerPath,
int callerLine,
bool escapeQuotes,
string source = null)
{
string actualIL = VisualizeIL(qualifiedMethodName, realIL, sequencePoints, source);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, message: null, escapeQuotes, callerPath, callerLine);
return this;
}
public string VisualizeIL(string qualifiedMethodName, bool realIL = false, string sequencePoints = null, string source = null)
{
// TODO: Currently the qualifiedMethodName is a symbol display name while PDB need metadata name.
// So we need to pass the PDB metadata name of the method to sequencePoints (instead of just bool).
return VisualizeIL(_testData.GetMethodData(qualifiedMethodName), realIL, sequencePoints, source);
}
internal string VisualizeIL(CompilationTestData.MethodData methodData, bool realIL, string sequencePoints = null, string source = null)
{
Dictionary<int, string> markers = null;
if (sequencePoints != null)
{
if (EmittedAssemblyPdb == null)
{
throw new InvalidOperationException($"{nameof(EmittedAssemblyPdb)} is not set");
}
if (EmittedAssemblyData == null)
{
throw new InvalidOperationException($"{nameof(EmittedAssemblyData)} is not set");
}
var actualPdbXml = PdbToXmlConverter.ToXml(
pdbStream: new MemoryStream(EmittedAssemblyPdb.ToArray()),
peStream: new MemoryStream(EmittedAssemblyData.ToArray()),
options: PdbToXmlOptions.ResolveTokens |
PdbToXmlOptions.ThrowOnError |
PdbToXmlOptions.ExcludeDocuments |
PdbToXmlOptions.ExcludeCustomDebugInformation |
PdbToXmlOptions.ExcludeScopes,
methodName: sequencePoints);
if (actualPdbXml.StartsWith("<error>"))
{
throw new Exception($"Failed to extract PDB information for method '{sequencePoints}'. PdbToXmlConverter returned:\r\n{actualPdbXml}");
}
markers = ILValidation.GetSequencePointMarkers(actualPdbXml, source);
}
if (!realIL)
{
return ILBuilderVisualizer.ILBuilderToString(methodData.ILBuilder, markers: markers);
}
if (_lazyModuleSymbol == null)
{
var targetReference = LoadTestEmittedExecutableForSymbolValidation(EmittedAssemblyData, _compilation.Options.OutputKind, display: _compilation.AssemblyName);
_lazyModuleSymbol = GetSymbolFromMetadata(targetReference, MetadataImportOptions.All);
}
if (_lazyModuleSymbol != null)
{
if (_visualizeRealIL == null)
{
throw new InvalidOperationException("IL visualization function is not set");
}
return _visualizeRealIL(_lazyModuleSymbol, methodData, markers, _testData.Module.GetMethodBody(methodData.Method).AreLocalsZeroed);
}
return null;
}
public CompilationVerifier VerifyMemberInIL(string methodName, bool expected)
{
Assert.Equal(expected, _testData.GetMethodsByName().ContainsKey(methodName));
return this;
}
public CompilationVerifier VerifyDiagnostics(params DiagnosticDescription[] expected)
{
_diagnostics.Verify(expected);
return this;
}
internal IModuleSymbol GetSymbolFromMetadata(MetadataReference metadataReference, MetadataImportOptions importOptions)
{
var dummy = _compilation
.RemoveAllSyntaxTrees()
.AddReferences(metadataReference)
.WithAssemblyName("Dummy")
.WithOptions(_compilation.Options.WithMetadataImportOptions(importOptions));
var symbol = dummy.GetAssemblyOrModuleSymbol(metadataReference);
if (metadataReference.Properties.Kind == MetadataImageKind.Assembly)
{
return ((IAssemblySymbol)symbol).Modules.First();
}
else
{
return (IModuleSymbol)symbol;
}
}
internal static MetadataReference LoadTestEmittedExecutableForSymbolValidation(
ImmutableArray<byte> image,
OutputKind outputKind,
string display = null)
{
var moduleMetadata = ModuleMetadata.CreateFromImage(image);
moduleMetadata.Module.PretendThereArentNoPiaLocalTypes();
if (outputKind == OutputKind.NetModule)
{
return moduleMetadata.GetReference(display: display);
}
else
{
return AssemblyMetadata.Create(moduleMetadata).GetReference(display: display);
}
}
public void VerifyOperationTree(string expectedOperationTree, bool skipImplicitlyDeclaredSymbols = false)
{
_compilation.VerifyOperationTree(expectedOperationTree, skipImplicitlyDeclaredSymbols);
}
public void VerifyOperationTree(string symbolToVerify, string expectedOperationTree, bool skipImplicitlyDeclaredSymbols = false)
{
_compilation.VerifyOperationTree(symbolToVerify, expectedOperationTree, skipImplicitlyDeclaredSymbols);
}
/// <summary>
/// Useful for verifying the expected variables are hoisted for closures, async, and iterator methods.
/// </summary>
public void VerifySynthesizedFields(string containingTypeName, params string[] expectedFields)
{
var types = TestData.Module.GetAllSynthesizedMembers();
Assert.Contains(types.Keys, t => containingTypeName == t.ToString());
var members = TestData.Module.GetAllSynthesizedMembers()
.Where(e => e.Key.ToString() == containingTypeName)
.Single()
.Value
.Where(s => s.Kind == SymbolKind.Field)
.Select(f => $"{((IFieldSymbol)f.GetISymbol()).Type.ToString()} {f.Name}")
.ToList();
AssertEx.SetEqual(expectedFields, members);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using ICSharpCode.Decompiler.Metadata;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.DiaSymReader.Tools;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class CompilationVerifier
{
private readonly Compilation _compilation;
private CompilationTestData _testData;
private readonly IEnumerable<ModuleData> _dependencies;
private ImmutableArray<Diagnostic> _diagnostics;
private IModuleSymbol _lazyModuleSymbol;
private IList<ModuleData> _allModuleData;
public ImmutableArray<byte> EmittedAssemblyData;
public ImmutableArray<byte> EmittedAssemblyPdb;
private readonly Func<IModuleSymbol, CompilationTestData.MethodData, IReadOnlyDictionary<int, string>, bool, string> _visualizeRealIL;
internal CompilationVerifier(
Compilation compilation,
Func<IModuleSymbol, CompilationTestData.MethodData, IReadOnlyDictionary<int, string>, bool, string> visualizeRealIL = null,
IEnumerable<ModuleData> dependencies = null)
{
_compilation = compilation;
_dependencies = dependencies;
_visualizeRealIL = visualizeRealIL;
}
internal CompilationTestData TestData => _testData;
public Compilation Compilation => _compilation;
internal ImmutableArray<Diagnostic> Diagnostics => _diagnostics;
internal Metadata GetMetadata()
{
if (EmittedAssemblyData == null)
{
throw new InvalidOperationException("You must call Emit before calling GetAllModuleMetadata.");
}
if (_compilation.Options.OutputKind.IsNetModule())
{
var metadata = ModuleMetadata.CreateFromImage(EmittedAssemblyData);
metadata.Module.PretendThereArentNoPiaLocalTypes();
return metadata;
}
else
{
var images = new List<ImmutableArray<byte>>
{
EmittedAssemblyData
};
if (_allModuleData != null)
{
images.AddRange(_allModuleData.Where(m => m.Kind == OutputKind.NetModule).Select(m => m.Image));
}
return AssemblyMetadata.Create(images.Select(image =>
{
var metadata = ModuleMetadata.CreateFromImage(image);
metadata.Module.PretendThereArentNoPiaLocalTypes();
return metadata;
}));
}
}
public string Dump(string methodName = null)
{
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleFullName = Emit(testEnvironment, manifestResources: null, EmitOptions.Default);
IList<ModuleData> moduleDatas = testEnvironment.GetAllModuleData();
var mainModule = moduleDatas.Single(md => md.FullName == mainModuleFullName);
RuntimeEnvironmentUtilities.DumpAssemblyData(moduleDatas, out var dumpDir);
string extension = mainModule.Kind == OutputKind.ConsoleApplication ? ".exe" : ".dll";
string modulePath = Path.Combine(dumpDir, mainModule.SimpleName + extension);
var decompiler = new ICSharpCode.Decompiler.CSharp.CSharpDecompiler(modulePath,
new ICSharpCode.Decompiler.DecompilerSettings() { AsyncAwait = false });
if (methodName != null)
{
var map = new Dictionary<string, ICSharpCode.Decompiler.TypeSystem.IMethod>();
listMethods(decompiler.TypeSystem.MainModule.RootNamespace, map);
if (map.TryGetValue(methodName, out var method))
{
return decompiler.DecompileAsString(method.MetadataToken);
}
else
{
throw new Exception($"Didn't find method '{methodName}'. Available/distinguishable methods are: \r\n{string.Join("\r\n", map.Keys)}");
}
}
return decompiler.DecompileWholeModuleAsString();
}
void listMethods(ICSharpCode.Decompiler.TypeSystem.INamespace @namespace, Dictionary<string, ICSharpCode.Decompiler.TypeSystem.IMethod> result)
{
foreach (var nestedNS in @namespace.ChildNamespaces)
{
if (nestedNS.FullName != "System" &&
nestedNS.FullName != "Microsoft")
{
listMethods(nestedNS, result);
}
}
foreach (var type in @namespace.Types)
{
listMethodsInType(type, result);
}
}
void listMethodsInType(ICSharpCode.Decompiler.TypeSystem.ITypeDefinition type, Dictionary<string, ICSharpCode.Decompiler.TypeSystem.IMethod> result)
{
foreach (var nestedType in type.NestedTypes)
{
listMethodsInType(nestedType, result);
}
foreach (var method in type.Methods)
{
if (result.ContainsKey(method.FullName))
{
// There is a bug with FullName on methods in generic types
result.Remove(method.FullName);
}
else
{
result.Add(method.FullName, method);
}
}
}
}
/// <summary>
/// Asserts that the emitted IL for a type is the same as the expected IL.
/// Many core library types are in different assemblies on .Net Framework, and .Net Core.
/// Therefore this test is likely to fail unless you only run it only only on one of these frameworks,
/// or you run it on both, but provide a different expected output string for each.
/// See <see cref="ExecutionConditionUtil"/>.
/// </summary>
/// <param name="typeName">The non-fully-qualified name of the type</param>
/// <param name="expected">The expected IL</param>
public void VerifyTypeIL(string typeName, string expected)
{
var output = new ICSharpCode.Decompiler.PlainTextOutput();
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleFullName = Emit(testEnvironment, manifestResources: null, EmitOptions.Default);
IList<ModuleData> moduleData = testEnvironment.GetAllModuleData();
var mainModule = moduleData.Single(md => md.FullName == mainModuleFullName);
using (var moduleMetadata = ModuleMetadata.CreateFromImage(testEnvironment.GetMainImage()))
{
var peFile = new PEFile(mainModuleFullName, moduleMetadata.Module.PEReaderOpt);
var metadataReader = moduleMetadata.GetMetadataReader();
bool found = false;
foreach (var typeDefHandle in metadataReader.TypeDefinitions)
{
var typeDef = metadataReader.GetTypeDefinition(typeDefHandle);
if (metadataReader.GetString(typeDef.Name) == typeName)
{
var disassembler = new ICSharpCode.Decompiler.Disassembler.ReflectionDisassembler(output, default);
disassembler.DisassembleType(peFile, typeDefHandle);
found = true;
break;
}
}
Assert.True(found, "Could not find type named " + typeName);
}
}
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, output.ToString(), escapeQuotes: false);
}
public void Emit(string expectedOutput, int? expectedReturnCode, string[] args, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, Verification peVerify, SignatureDescription[] expectedSignatures)
{
using var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies);
string mainModuleName = Emit(testEnvironment, manifestResources, emitOptions);
_allModuleData = testEnvironment.GetAllModuleData();
testEnvironment.Verify(peVerify);
if (expectedSignatures != null)
{
MetadataSignatureUnitTestHelper.VerifyMemberSignatures(testEnvironment, expectedSignatures);
}
if (expectedOutput != null || expectedReturnCode != null)
{
var returnCode = testEnvironment.Execute(mainModuleName, args, expectedOutput);
if (expectedReturnCode is int exCode)
{
Assert.Equal(exCode, returnCode);
}
}
}
// TODO(tomat): Fold into CompileAndVerify.
// Replace bool verify parameter with string[] expectedPeVerifyOutput. If null, no verification. If empty verify have to succeed. Otherwise compare errors.
public void EmitAndVerify(params string[] expectedPeVerifyOutput)
{
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleName = Emit(testEnvironment, null, null);
string[] actualOutput = testEnvironment.VerifyModules(new[] { mainModuleName });
Assert.Equal(expectedPeVerifyOutput, actualOutput);
}
}
private string Emit(IRuntimeEnvironment testEnvironment, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions)
{
testEnvironment.Emit(_compilation, manifestResources, emitOptions);
_diagnostics = testEnvironment.GetDiagnostics();
EmittedAssemblyData = testEnvironment.GetMainImage();
EmittedAssemblyPdb = testEnvironment.GetMainPdb();
_testData = ((IInternalRuntimeEnvironment)testEnvironment).GetCompilationTestData();
return _compilation.Assembly.Identity.GetDisplayName();
}
public CompilationVerifier VerifyIL(
string qualifiedMethodName,
XCData expectedIL,
bool realIL = false,
string sequencePoints = null,
[CallerFilePath] string callerPath = null,
[CallerLineNumber] int callerLine = 0)
{
return VerifyILImpl(qualifiedMethodName, expectedIL.Value, realIL, sequencePoints, callerPath, callerLine, escapeQuotes: false);
}
public CompilationVerifier VerifyIL(
string qualifiedMethodName,
string expectedIL,
bool realIL = false,
string sequencePoints = null,
[CallerFilePath] string callerPath = null,
[CallerLineNumber] int callerLine = 0,
string source = null)
{
return VerifyILImpl(qualifiedMethodName, expectedIL, realIL, sequencePoints, callerPath, callerLine, escapeQuotes: true, source: source);
}
public CompilationVerifier VerifyMissing(
string qualifiedMethodName)
{
Assert.False(_testData.TryGetMethodData(qualifiedMethodName, out _));
return this;
}
public void VerifyLocalSignature(
string qualifiedMethodName,
string expectedSignature,
[CallerLineNumber] int callerLine = 0,
[CallerFilePath] string callerPath = null)
{
var ilBuilder = _testData.GetMethodData(qualifiedMethodName).ILBuilder;
string actualSignature = ILBuilderVisualizer.LocalSignatureToString(ilBuilder);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, actualSignature, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
/// <summary>
/// Visualizes the IL for a given method, and ensures that it matches the expected IL.
/// </summary>
/// <param name="realIL">Controls whether the IL stream contains pseudo-tokens or real tokens.</param>
private CompilationVerifier VerifyILImpl(
string qualifiedMethodName,
string expectedIL,
bool realIL,
string sequencePoints,
string callerPath,
int callerLine,
bool escapeQuotes,
string source = null)
{
string actualIL = VisualizeIL(qualifiedMethodName, realIL, sequencePoints, source);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, message: null, escapeQuotes, callerPath, callerLine);
return this;
}
public string VisualizeIL(string qualifiedMethodName, bool realIL = false, string sequencePoints = null, string source = null)
{
// TODO: Currently the qualifiedMethodName is a symbol display name while PDB need metadata name.
// So we need to pass the PDB metadata name of the method to sequencePoints (instead of just bool).
return VisualizeIL(_testData.GetMethodData(qualifiedMethodName), realIL, sequencePoints, source);
}
internal string VisualizeIL(CompilationTestData.MethodData methodData, bool realIL, string sequencePoints = null, string source = null)
{
Dictionary<int, string> markers = null;
if (sequencePoints != null)
{
if (EmittedAssemblyPdb == null)
{
throw new InvalidOperationException($"{nameof(EmittedAssemblyPdb)} is not set");
}
if (EmittedAssemblyData == null)
{
throw new InvalidOperationException($"{nameof(EmittedAssemblyData)} is not set");
}
var actualPdbXml = PdbToXmlConverter.ToXml(
pdbStream: new MemoryStream(EmittedAssemblyPdb.ToArray()),
peStream: new MemoryStream(EmittedAssemblyData.ToArray()),
options: PdbToXmlOptions.ResolveTokens |
PdbToXmlOptions.ThrowOnError |
PdbToXmlOptions.ExcludeDocuments |
PdbToXmlOptions.ExcludeCustomDebugInformation |
PdbToXmlOptions.ExcludeScopes,
methodName: sequencePoints);
if (actualPdbXml.StartsWith("<error>"))
{
throw new Exception($"Failed to extract PDB information for method '{sequencePoints}'. PdbToXmlConverter returned:\r\n{actualPdbXml}");
}
markers = ILValidation.GetSequencePointMarkers(actualPdbXml, source);
}
if (!realIL)
{
return ILBuilderVisualizer.ILBuilderToString(methodData.ILBuilder, markers: markers);
}
if (_lazyModuleSymbol == null)
{
var targetReference = LoadTestEmittedExecutableForSymbolValidation(EmittedAssemblyData, _compilation.Options.OutputKind, display: _compilation.AssemblyName);
_lazyModuleSymbol = GetSymbolFromMetadata(targetReference, MetadataImportOptions.All);
}
if (_lazyModuleSymbol != null)
{
if (_visualizeRealIL == null)
{
throw new InvalidOperationException("IL visualization function is not set");
}
return _visualizeRealIL(_lazyModuleSymbol, methodData, markers, _testData.Module.GetMethodBody(methodData.Method).AreLocalsZeroed);
}
return null;
}
public CompilationVerifier VerifyMemberInIL(string methodName, bool expected)
{
Assert.Equal(expected, _testData.GetMethodsByName().ContainsKey(methodName));
return this;
}
public CompilationVerifier VerifyDiagnostics(params DiagnosticDescription[] expected)
{
_diagnostics.Verify(expected);
return this;
}
internal IModuleSymbol GetSymbolFromMetadata(MetadataReference metadataReference, MetadataImportOptions importOptions)
{
var dummy = _compilation
.RemoveAllSyntaxTrees()
.AddReferences(metadataReference)
.WithAssemblyName("Dummy")
.WithOptions(_compilation.Options.WithMetadataImportOptions(importOptions));
var symbol = dummy.GetAssemblyOrModuleSymbol(metadataReference);
if (metadataReference.Properties.Kind == MetadataImageKind.Assembly)
{
return ((IAssemblySymbol)symbol).Modules.First();
}
else
{
return (IModuleSymbol)symbol;
}
}
internal static MetadataReference LoadTestEmittedExecutableForSymbolValidation(
ImmutableArray<byte> image,
OutputKind outputKind,
string display = null)
{
var moduleMetadata = ModuleMetadata.CreateFromImage(image);
moduleMetadata.Module.PretendThereArentNoPiaLocalTypes();
if (outputKind == OutputKind.NetModule)
{
return moduleMetadata.GetReference(display: display);
}
else
{
return AssemblyMetadata.Create(moduleMetadata).GetReference(display: display);
}
}
public void VerifyOperationTree(string expectedOperationTree, bool skipImplicitlyDeclaredSymbols = false)
{
_compilation.VerifyOperationTree(expectedOperationTree, skipImplicitlyDeclaredSymbols);
}
public void VerifyOperationTree(string symbolToVerify, string expectedOperationTree, bool skipImplicitlyDeclaredSymbols = false)
{
_compilation.VerifyOperationTree(symbolToVerify, expectedOperationTree, skipImplicitlyDeclaredSymbols);
}
/// <summary>
/// Useful for verifying the expected variables are hoisted for closures, async, and iterator methods.
/// </summary>
public void VerifySynthesizedFields(string containingTypeName, params string[] expectedFields)
{
var types = TestData.Module.GetAllSynthesizedMembers();
Assert.Contains(types.Keys, t => containingTypeName == t.ToString());
var members = TestData.Module.GetAllSynthesizedMembers()
.Where(e => e.Key.ToString() == containingTypeName)
.Single()
.Value
.Where(s => s.Kind == SymbolKind.Field)
.Select(f => $"{((IFieldSymbol)f.GetISymbol()).Type.ToString()} {f.Name}")
.ToList();
AssertEx.SetEqual(expectedFields, members);
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Compilers/CSharp/Test/Symbol/Symbols/Source/UsingAliasTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source
{
public class UsingAliasTests : SemanticModelTestBase
{
[Fact]
public void GetSemanticInfo()
{
var text =
@"using O = System.Object;
partial class A : O {}
partial class A : object {}
partial class A : System.Object {}
partial class A : Object {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var a1 = root.Members[0] as TypeDeclarationSyntax;
var a2 = root.Members[1] as TypeDeclarationSyntax;
var a3 = root.Members[2] as TypeDeclarationSyntax;
var a4 = root.Members[3] as TypeDeclarationSyntax;
var base1 = a1.BaseList.Types[0].Type as TypeSyntax;
var base2 = a2.BaseList.Types[0].Type as TypeSyntax;
var base3 = a3.BaseList.Types[0].Type as TypeSyntax;
var base4 = a4.BaseList.Types[0].Type as TypeSyntax;
var model = comp.GetSemanticModel(tree);
var info1 = model.GetSemanticInfoSummary(base1);
Assert.NotNull(info1.Symbol);
var alias1 = model.GetAliasInfo((IdentifierNameSyntax)base1);
Assert.NotNull(alias1);
Assert.Equal(SymbolKind.Alias, alias1.Kind);
Assert.Equal("O", alias1.ToDisplayString());
Assert.Equal("O=System.Object", alias1.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal(info1.Symbol, alias1.Target);
var info2 = model.GetSemanticInfoSummary(base2);
Assert.NotNull(info2.Symbol);
var b2 = info2.Symbol;
Assert.Equal("System.Object", b2.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info2.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info3 = model.GetSemanticInfoSummary(base3);
Assert.NotNull(info3.Symbol);
var b3 = info3.Symbol;
Assert.Equal("System.Object", b3.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info3.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info4 = model.GetSemanticInfoSummary(base4);
Assert.Null(info4.Symbol); // no "using System;"
Assert.Equal(0, info4.CandidateSymbols.Length);
var alias4 = model.GetAliasInfo((IdentifierNameSyntax)base4);
Assert.Null(alias4);
}
[Fact]
public void GetSymbolInfoInParent()
{
var text =
@"using O = System.Object;
partial class A : O {}
partial class A : object {}
partial class A : System.Object {}
partial class A : Object {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var a1 = root.Members[0] as TypeDeclarationSyntax;
var a2 = root.Members[1] as TypeDeclarationSyntax;
var a3 = root.Members[2] as TypeDeclarationSyntax;
var a4 = root.Members[3] as TypeDeclarationSyntax;
var base1 = a1.BaseList.Types[0].Type as TypeSyntax;
var base2 = a2.BaseList.Types[0].Type as TypeSyntax;
var base3 = a3.BaseList.Types[0].Type as TypeSyntax;
var base4 = a4.BaseList.Types[0].Type as TypeSyntax;
var model = comp.GetSemanticModel(tree);
var info1 = model.GetSemanticInfoSummary(base1);
Assert.Equal("System.Object", info1.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var alias1 = model.GetAliasInfo((IdentifierNameSyntax)base1);
Assert.NotNull(alias1);
Assert.Equal(SymbolKind.Alias, alias1.Kind);
Assert.Equal("O=System.Object", alias1.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info2 = model.GetSemanticInfoSummary(base2);
Assert.NotNull(info2.Symbol);
var b2 = info2.Symbol;
Assert.Equal("System.Object", b2.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info2.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info3 = model.GetSemanticInfoSummary(base3);
Assert.NotNull(info3.Symbol);
var b3 = info3.Symbol;
Assert.Equal("System.Object", b3.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info3.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info4 = model.GetSemanticInfoSummary(base4);
Assert.Null(info4.Symbol); // no "using System;"
Assert.Equal(0, info4.CandidateSymbols.Length);
var alias4 = model.GetAliasInfo((IdentifierNameSyntax)base4);
Assert.Null(alias4);
}
[Fact]
public void BindType()
{
var text =
@"using O = System.Object;
partial class A : O {}
partial class A : object {}
partial class A : System.Object {}
partial class A : Object {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var a1 = root.Members[0] as TypeDeclarationSyntax;
var a2 = root.Members[1] as TypeDeclarationSyntax;
var a3 = root.Members[2] as TypeDeclarationSyntax;
var a4 = root.Members[3] as TypeDeclarationSyntax;
var base1 = a1.BaseList.Types[0].Type as TypeSyntax;
var base2 = a2.BaseList.Types[0].Type as TypeSyntax;
var base3 = a3.BaseList.Types[0].Type as TypeSyntax;
var base4 = a4.BaseList.Types[0].Type as TypeSyntax;
var model = comp.GetSemanticModel(tree);
var symbolInfo = model.GetSpeculativeSymbolInfo(base2.SpanStart, base2, SpeculativeBindingOption.BindAsTypeOrNamespace);
var info2 = symbolInfo.Symbol as ITypeSymbol;
Assert.NotNull(info2);
Assert.Equal("System.Object", info2.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info2.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
symbolInfo = model.GetSpeculativeSymbolInfo(base3.SpanStart, base3, SpeculativeBindingOption.BindAsTypeOrNamespace);
var info3 = symbolInfo.Symbol as ITypeSymbol;
Assert.NotNull(info3);
Assert.Equal("System.Object", info3.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info3.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
symbolInfo = model.GetSpeculativeSymbolInfo(base4.SpanStart, base4, SpeculativeBindingOption.BindAsTypeOrNamespace);
var info4 = symbolInfo.Symbol as ITypeSymbol;
Assert.Null(info4); // no "using System;"
}
[Fact]
public void GetDeclaredSymbol01()
{
var text =
@"using O = System.Object;
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var model = comp.GetSemanticModel(tree);
var alias = model.GetDeclaredSymbol(usingAlias);
Assert.Equal("O", alias.ToDisplayString());
Assert.Equal("O=System.Object", alias.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var global = (INamespaceSymbol)alias.ContainingSymbol;
Assert.Equal(NamespaceKind.Module, global.NamespaceKind);
}
[Fact]
public void GetDeclaredSymbol02()
{
var text = "using System;";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var model = comp.GetSemanticModel(tree);
var alias = model.GetDeclaredSymbol(usingAlias);
Assert.Null(alias);
}
[Fact]
public void LookupNames()
{
var text =
@"using O = System.Object;
class C {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var model = comp.GetSemanticModel(tree);
var names = model.LookupNames(root.Members[0].SpanStart);
Assert.Contains("O", names);
}
[Fact]
public void LookupSymbols()
{
var text =
@"using O = System.Object;
class C {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var model = comp.GetSemanticModel(tree);
var symbols = model.LookupSymbols(root.Members[0].SpanStart, name: "O");
Assert.Equal(1, symbols.Length);
Assert.Equal(SymbolKind.Alias, symbols[0].Kind);
Assert.Equal("O=System.Object", symbols[0].ToDisplayString(format: SymbolDisplayFormat.TestFormat));
}
[WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")]
[Fact]
public void EventEscapedIdentifier()
{
var text = @"
using @for = @foreach;
namespace @foreach { }
";
SyntaxTree syntaxTree = Parse(text);
CSharpCompilation comp = CreateCompilation(syntaxTree);
UsingDirectiveSyntax usingAlias = (syntaxTree.GetCompilationUnitRoot() as CompilationUnitSyntax).Usings.First();
var alias = comp.GetSemanticModel(syntaxTree).GetDeclaredSymbol(usingAlias);
Assert.Equal("for", alias.Name);
Assert.Equal("@for", alias.ToString());
}
[WorkItem(541937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541937")]
[Fact]
public void LocalDeclaration()
{
var text = @"
using GIBBERISH = System.Int32;
class Program
{
static void Main()
{
/*<bind>*/GIBBERISH/*</bind>*/ x;
}
}";
SyntaxTree syntaxTree = Parse(text);
CSharpCompilation comp = CreateCompilation(syntaxTree);
var model = comp.GetSemanticModel(syntaxTree);
IdentifierNameSyntax exprSyntaxToBind = (IdentifierNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(syntaxTree));
Assert.Equal(SymbolKind.Alias, model.GetAliasInfo(exprSyntaxToBind).Kind);
}
[WorkItem(576809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576809")]
[Fact]
public void AsClause()
{
var text = @"
using N = System.Nullable<int>;
class Program
{
static void Main()
{
object x = 1;
var y = x as /*<bind>*/N/*</bind>*/ + 1;
}
}
";
SyntaxTree syntaxTree = Parse(text);
CSharpCompilation comp = CreateCompilation(syntaxTree);
var model = comp.GetSemanticModel(syntaxTree);
IdentifierNameSyntax exprSyntaxToBind = (IdentifierNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(syntaxTree));
Assert.Equal("System.Int32?", model.GetAliasInfo(exprSyntaxToBind).Target.ToTestDisplayString());
}
[WorkItem(542552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542552")]
[Fact]
public void IncompleteDuplicateAlias()
{
var text = @"namespace namespace1 { }
namespace namespace2 { }
namespace prog
{
using ns = namespace1;
using ns =";
SyntaxTree syntaxTree = Parse(text);
CSharpCompilation comp = CreateCompilation(syntaxTree);
var discarded = comp.GetDiagnostics();
}
[ClrOnlyFact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")]
public void AliasWithAnError()
{
var text =
@"
namespace NS
{
using Short = LongNamespace;
class Test
{
public object Method1()
{
return (new Short.MyClass()).Prop;
}
}
}";
var compilation = CreateCompilation(text);
compilation.VerifyDiagnostics(
// (4,19): error CS0246: The type or namespace name 'LongNamespace' could not be found (are you missing a using directive or an assembly reference?)
// using Short = LongNamespace;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "LongNamespace").WithArguments("LongNamespace").WithLocation(4, 19)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Short").Skip(1).Single();
Assert.Equal("Short.MyClass", node.Parent.ToString());
var model = compilation.GetSemanticModel(tree);
var alias = model.GetAliasInfo(node);
Assert.Equal("Short=LongNamespace", alias.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, alias.Target.Kind);
Assert.Equal("LongNamespace", alias.Target.ToTestDisplayString());
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[ClrOnlyFact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")]
public void AliasWithAnErrorFileScopedNamespace()
{
var text =
@"
namespace NS;
using Short = LongNamespace;
class Test
{
public object Method1()
{
return (new Short.MyClass()).Prop;
}
}
";
var compilation = CreateCompilation(text, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview));
compilation.VerifyDiagnostics(
// (3,15): error CS0246: The type or namespace name 'LongNamespace' could not be found (are you missing a using directive or an assembly reference?)
// using Short = LongNamespace;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "LongNamespace").WithArguments("LongNamespace").WithLocation(3, 15));
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Short").Skip(1).Single();
Assert.Equal("Short.MyClass", node.Parent.ToString());
var model = compilation.GetSemanticModel(tree);
var alias = model.GetAliasInfo(node);
Assert.Equal("Short=LongNamespace", alias.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, alias.Target.Kind);
Assert.Equal("LongNamespace", alias.Target.ToTestDisplayString());
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source
{
public class UsingAliasTests : SemanticModelTestBase
{
[Fact]
public void GetSemanticInfo()
{
var text =
@"using O = System.Object;
partial class A : O {}
partial class A : object {}
partial class A : System.Object {}
partial class A : Object {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var a1 = root.Members[0] as TypeDeclarationSyntax;
var a2 = root.Members[1] as TypeDeclarationSyntax;
var a3 = root.Members[2] as TypeDeclarationSyntax;
var a4 = root.Members[3] as TypeDeclarationSyntax;
var base1 = a1.BaseList.Types[0].Type as TypeSyntax;
var base2 = a2.BaseList.Types[0].Type as TypeSyntax;
var base3 = a3.BaseList.Types[0].Type as TypeSyntax;
var base4 = a4.BaseList.Types[0].Type as TypeSyntax;
var model = comp.GetSemanticModel(tree);
var info1 = model.GetSemanticInfoSummary(base1);
Assert.NotNull(info1.Symbol);
var alias1 = model.GetAliasInfo((IdentifierNameSyntax)base1);
Assert.NotNull(alias1);
Assert.Equal(SymbolKind.Alias, alias1.Kind);
Assert.Equal("O", alias1.ToDisplayString());
Assert.Equal("O=System.Object", alias1.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal(info1.Symbol, alias1.Target);
var info2 = model.GetSemanticInfoSummary(base2);
Assert.NotNull(info2.Symbol);
var b2 = info2.Symbol;
Assert.Equal("System.Object", b2.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info2.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info3 = model.GetSemanticInfoSummary(base3);
Assert.NotNull(info3.Symbol);
var b3 = info3.Symbol;
Assert.Equal("System.Object", b3.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info3.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info4 = model.GetSemanticInfoSummary(base4);
Assert.Null(info4.Symbol); // no "using System;"
Assert.Equal(0, info4.CandidateSymbols.Length);
var alias4 = model.GetAliasInfo((IdentifierNameSyntax)base4);
Assert.Null(alias4);
}
[Fact]
public void GetSymbolInfoInParent()
{
var text =
@"using O = System.Object;
partial class A : O {}
partial class A : object {}
partial class A : System.Object {}
partial class A : Object {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var a1 = root.Members[0] as TypeDeclarationSyntax;
var a2 = root.Members[1] as TypeDeclarationSyntax;
var a3 = root.Members[2] as TypeDeclarationSyntax;
var a4 = root.Members[3] as TypeDeclarationSyntax;
var base1 = a1.BaseList.Types[0].Type as TypeSyntax;
var base2 = a2.BaseList.Types[0].Type as TypeSyntax;
var base3 = a3.BaseList.Types[0].Type as TypeSyntax;
var base4 = a4.BaseList.Types[0].Type as TypeSyntax;
var model = comp.GetSemanticModel(tree);
var info1 = model.GetSemanticInfoSummary(base1);
Assert.Equal("System.Object", info1.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var alias1 = model.GetAliasInfo((IdentifierNameSyntax)base1);
Assert.NotNull(alias1);
Assert.Equal(SymbolKind.Alias, alias1.Kind);
Assert.Equal("O=System.Object", alias1.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info2 = model.GetSemanticInfoSummary(base2);
Assert.NotNull(info2.Symbol);
var b2 = info2.Symbol;
Assert.Equal("System.Object", b2.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info2.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info3 = model.GetSemanticInfoSummary(base3);
Assert.NotNull(info3.Symbol);
var b3 = info3.Symbol;
Assert.Equal("System.Object", b3.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info3.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var info4 = model.GetSemanticInfoSummary(base4);
Assert.Null(info4.Symbol); // no "using System;"
Assert.Equal(0, info4.CandidateSymbols.Length);
var alias4 = model.GetAliasInfo((IdentifierNameSyntax)base4);
Assert.Null(alias4);
}
[Fact]
public void BindType()
{
var text =
@"using O = System.Object;
partial class A : O {}
partial class A : object {}
partial class A : System.Object {}
partial class A : Object {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var a1 = root.Members[0] as TypeDeclarationSyntax;
var a2 = root.Members[1] as TypeDeclarationSyntax;
var a3 = root.Members[2] as TypeDeclarationSyntax;
var a4 = root.Members[3] as TypeDeclarationSyntax;
var base1 = a1.BaseList.Types[0].Type as TypeSyntax;
var base2 = a2.BaseList.Types[0].Type as TypeSyntax;
var base3 = a3.BaseList.Types[0].Type as TypeSyntax;
var base4 = a4.BaseList.Types[0].Type as TypeSyntax;
var model = comp.GetSemanticModel(tree);
var symbolInfo = model.GetSpeculativeSymbolInfo(base2.SpanStart, base2, SpeculativeBindingOption.BindAsTypeOrNamespace);
var info2 = symbolInfo.Symbol as ITypeSymbol;
Assert.NotNull(info2);
Assert.Equal("System.Object", info2.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info2.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
symbolInfo = model.GetSpeculativeSymbolInfo(base3.SpanStart, base3, SpeculativeBindingOption.BindAsTypeOrNamespace);
var info3 = symbolInfo.Symbol as ITypeSymbol;
Assert.NotNull(info3);
Assert.Equal("System.Object", info3.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
Assert.Equal("System.Object", info3.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
symbolInfo = model.GetSpeculativeSymbolInfo(base4.SpanStart, base4, SpeculativeBindingOption.BindAsTypeOrNamespace);
var info4 = symbolInfo.Symbol as ITypeSymbol;
Assert.Null(info4); // no "using System;"
}
[Fact]
public void GetDeclaredSymbol01()
{
var text =
@"using O = System.Object;
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var model = comp.GetSemanticModel(tree);
var alias = model.GetDeclaredSymbol(usingAlias);
Assert.Equal("O", alias.ToDisplayString());
Assert.Equal("O=System.Object", alias.ToDisplayString(format: SymbolDisplayFormat.TestFormat));
var global = (INamespaceSymbol)alias.ContainingSymbol;
Assert.Equal(NamespaceKind.Module, global.NamespaceKind);
}
[Fact]
public void GetDeclaredSymbol02()
{
var text = "using System;";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var model = comp.GetSemanticModel(tree);
var alias = model.GetDeclaredSymbol(usingAlias);
Assert.Null(alias);
}
[Fact]
public void LookupNames()
{
var text =
@"using O = System.Object;
class C {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var model = comp.GetSemanticModel(tree);
var names = model.LookupNames(root.Members[0].SpanStart);
Assert.Contains("O", names);
}
[Fact]
public void LookupSymbols()
{
var text =
@"using O = System.Object;
class C {}
";
var tree = Parse(text);
var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax;
var comp = CreateCompilation(tree);
var usingAlias = root.Usings[0];
var model = comp.GetSemanticModel(tree);
var symbols = model.LookupSymbols(root.Members[0].SpanStart, name: "O");
Assert.Equal(1, symbols.Length);
Assert.Equal(SymbolKind.Alias, symbols[0].Kind);
Assert.Equal("O=System.Object", symbols[0].ToDisplayString(format: SymbolDisplayFormat.TestFormat));
}
[WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")]
[Fact]
public void EventEscapedIdentifier()
{
var text = @"
using @for = @foreach;
namespace @foreach { }
";
SyntaxTree syntaxTree = Parse(text);
CSharpCompilation comp = CreateCompilation(syntaxTree);
UsingDirectiveSyntax usingAlias = (syntaxTree.GetCompilationUnitRoot() as CompilationUnitSyntax).Usings.First();
var alias = comp.GetSemanticModel(syntaxTree).GetDeclaredSymbol(usingAlias);
Assert.Equal("for", alias.Name);
Assert.Equal("@for", alias.ToString());
}
[WorkItem(541937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541937")]
[Fact]
public void LocalDeclaration()
{
var text = @"
using GIBBERISH = System.Int32;
class Program
{
static void Main()
{
/*<bind>*/GIBBERISH/*</bind>*/ x;
}
}";
SyntaxTree syntaxTree = Parse(text);
CSharpCompilation comp = CreateCompilation(syntaxTree);
var model = comp.GetSemanticModel(syntaxTree);
IdentifierNameSyntax exprSyntaxToBind = (IdentifierNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(syntaxTree));
Assert.Equal(SymbolKind.Alias, model.GetAliasInfo(exprSyntaxToBind).Kind);
}
[WorkItem(576809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576809")]
[Fact]
public void AsClause()
{
var text = @"
using N = System.Nullable<int>;
class Program
{
static void Main()
{
object x = 1;
var y = x as /*<bind>*/N/*</bind>*/ + 1;
}
}
";
SyntaxTree syntaxTree = Parse(text);
CSharpCompilation comp = CreateCompilation(syntaxTree);
var model = comp.GetSemanticModel(syntaxTree);
IdentifierNameSyntax exprSyntaxToBind = (IdentifierNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(syntaxTree));
Assert.Equal("System.Int32?", model.GetAliasInfo(exprSyntaxToBind).Target.ToTestDisplayString());
}
[WorkItem(542552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542552")]
[Fact]
public void IncompleteDuplicateAlias()
{
var text = @"namespace namespace1 { }
namespace namespace2 { }
namespace prog
{
using ns = namespace1;
using ns =";
SyntaxTree syntaxTree = Parse(text);
CSharpCompilation comp = CreateCompilation(syntaxTree);
var discarded = comp.GetDiagnostics();
}
[ClrOnlyFact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")]
public void AliasWithAnError()
{
var text =
@"
namespace NS
{
using Short = LongNamespace;
class Test
{
public object Method1()
{
return (new Short.MyClass()).Prop;
}
}
}";
var compilation = CreateCompilation(text);
compilation.VerifyDiagnostics(
// (4,19): error CS0246: The type or namespace name 'LongNamespace' could not be found (are you missing a using directive or an assembly reference?)
// using Short = LongNamespace;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "LongNamespace").WithArguments("LongNamespace").WithLocation(4, 19)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Short").Skip(1).Single();
Assert.Equal("Short.MyClass", node.Parent.ToString());
var model = compilation.GetSemanticModel(tree);
var alias = model.GetAliasInfo(node);
Assert.Equal("Short=LongNamespace", alias.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, alias.Target.Kind);
Assert.Equal("LongNamespace", alias.Target.ToTestDisplayString());
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[ClrOnlyFact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")]
public void AliasWithAnErrorFileScopedNamespace()
{
var text =
@"
namespace NS;
using Short = LongNamespace;
class Test
{
public object Method1()
{
return (new Short.MyClass()).Prop;
}
}
";
var compilation = CreateCompilation(text, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview));
compilation.VerifyDiagnostics(
// (3,15): error CS0246: The type or namespace name 'LongNamespace' could not be found (are you missing a using directive or an assembly reference?)
// using Short = LongNamespace;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "LongNamespace").WithArguments("LongNamespace").WithLocation(3, 15));
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Short").Skip(1).Single();
Assert.Equal("Short.MyClass", node.Parent.ToString());
var model = compilation.GetSemanticModel(tree);
var alias = model.GetAliasInfo(node);
Assert.Equal("Short=LongNamespace", alias.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, alias.Target.Kind);
Assert.Equal("LongNamespace", alias.Target.ToTestDisplayString());
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Features/Core/Portable/AddImport/SearchScopes/ProjectSearchScope.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;
namespace Microsoft.CodeAnalysis.AddImport
{
internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax>
{
private abstract class ProjectSearchScope : SearchScope
{
protected readonly Project _project;
public ProjectSearchScope(
AbstractAddImportFeatureService<TSimpleNameSyntax> provider,
Project project,
bool exact,
CancellationToken cancellationToken)
: base(provider, exact, cancellationToken)
{
_project = project;
}
public override SymbolReference CreateReference<T>(SymbolResult<T> symbol)
{
return new ProjectSymbolReference(
provider, symbol.WithSymbol<INamespaceOrTypeSymbol>(symbol.Symbol), _project);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
namespace Microsoft.CodeAnalysis.AddImport
{
internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax>
{
private abstract class ProjectSearchScope : SearchScope
{
protected readonly Project _project;
public ProjectSearchScope(
AbstractAddImportFeatureService<TSimpleNameSyntax> provider,
Project project,
bool exact,
CancellationToken cancellationToken)
: base(provider, exact, cancellationToken)
{
_project = project;
}
public override SymbolReference CreateReference<T>(SymbolResult<T> symbol)
{
return new ProjectSymbolReference(
provider, symbol.WithSymbol<INamespaceOrTypeSymbol>(symbol.Symbol), _project);
}
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/VisualStudio/Core/Def/EditorConfigSettings/Common/IEnumSettingViewModel.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.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal interface IEnumSettingViewModel
{
string[] GetValueDescriptions();
int GetValueIndex();
void ChangeProperty(string v);
}
}
| // Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal interface IEnumSettingViewModel
{
string[] GetValueDescriptions();
int GetValueIndex();
void ChangeProperty(string v);
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/EditorFeatures/TestUtilities/BraceHighlighting/AbstractBraceHighlightingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.BraceHighlighting
{
[UseExportProvider]
public abstract class AbstractBraceHighlightingTests
{
protected async Task TestBraceHighlightingAsync(
string markup, ParseOptions options = null, bool swapAnglesWithBrackets = false)
{
MarkupTestFile.GetPositionAndSpans(markup,
out var text, out int cursorPosition, out var expectedSpans);
// needed because markup test file can't support [|[|] to indicate selecting
// just an open bracket.
if (swapAnglesWithBrackets)
{
text = text.Replace("<", "[").Replace(">", "]");
}
using (var workspace = CreateWorkspace(text, options))
{
WpfTestRunner.RequireWpfFact($"{nameof(AbstractBraceHighlightingTests)}.{nameof(TestBraceHighlightingAsync)} creates asynchronous taggers");
var provider = new BraceHighlightingViewTaggerProvider(
workspace.GetService<IThreadingContext>(),
GetBraceMatchingService(workspace),
AsynchronousOperationListenerProvider.NullProvider);
var testDocument = workspace.Documents.First();
var buffer = testDocument.GetTextBuffer();
var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault();
var context = new TaggerContext<BraceHighlightTag>(
document, buffer.CurrentSnapshot,
new SnapshotPoint(buffer.CurrentSnapshot, cursorPosition));
await provider.GetTestAccessor().ProduceTagsAsync(context);
var expectedHighlights = expectedSpans.Select(ts => ts.ToSpan()).OrderBy(s => s.Start).ToList();
var actualHighlights = context.tagSpans.Select(ts => ts.Span.Span).OrderBy(s => s.Start).ToList();
Assert.Equal(expectedHighlights, actualHighlights);
}
}
internal virtual IBraceMatchingService GetBraceMatchingService(TestWorkspace workspace)
=> workspace.GetService<IBraceMatchingService>();
protected abstract TestWorkspace CreateWorkspace(string markup, ParseOptions 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.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.BraceHighlighting
{
[UseExportProvider]
public abstract class AbstractBraceHighlightingTests
{
protected async Task TestBraceHighlightingAsync(
string markup, ParseOptions options = null, bool swapAnglesWithBrackets = false)
{
MarkupTestFile.GetPositionAndSpans(markup,
out var text, out int cursorPosition, out var expectedSpans);
// needed because markup test file can't support [|[|] to indicate selecting
// just an open bracket.
if (swapAnglesWithBrackets)
{
text = text.Replace("<", "[").Replace(">", "]");
}
using (var workspace = CreateWorkspace(text, options))
{
WpfTestRunner.RequireWpfFact($"{nameof(AbstractBraceHighlightingTests)}.{nameof(TestBraceHighlightingAsync)} creates asynchronous taggers");
var provider = new BraceHighlightingViewTaggerProvider(
workspace.GetService<IThreadingContext>(),
GetBraceMatchingService(workspace),
AsynchronousOperationListenerProvider.NullProvider);
var testDocument = workspace.Documents.First();
var buffer = testDocument.GetTextBuffer();
var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault();
var context = new TaggerContext<BraceHighlightTag>(
document, buffer.CurrentSnapshot,
new SnapshotPoint(buffer.CurrentSnapshot, cursorPosition));
await provider.GetTestAccessor().ProduceTagsAsync(context);
var expectedHighlights = expectedSpans.Select(ts => ts.ToSpan()).OrderBy(s => s.Start).ToList();
var actualHighlights = context.tagSpans.Select(ts => ts.Span.Span).OrderBy(s => s.Start).ToList();
Assert.Equal(expectedHighlights, actualHighlights);
}
}
internal virtual IBraceMatchingService GetBraceMatchingService(TestWorkspace workspace)
=> workspace.GetService<IBraceMatchingService>();
protected abstract TestWorkspace CreateWorkspace(string markup, ParseOptions options);
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Compilers/Core/Portable/PEWriter/Miscellaneous.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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Roslyn.Utilities;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
namespace Microsoft.Cci
{
/// <summary>
/// A container for static helper methods that are used for manipulating and computing iterators.
/// </summary>
internal static class IteratorHelper
{
/// <summary>
/// True if the given enumerable is not null and contains at least one element.
/// </summary>
public static bool EnumerableIsNotEmpty<T>([NotNullWhen(returnValue: true)] IEnumerable<T>? enumerable)
{
if (enumerable == null)
{
return false;
}
var asIListT = enumerable as IList<T>;
if (asIListT != null)
{
return asIListT.Count != 0;
}
var asIList = enumerable as IList;
if (asIList != null)
{
return asIList.Count != 0;
}
return enumerable.GetEnumerator().MoveNext();
}
/// <summary>
/// True if the given enumerable is null or contains no elements
/// </summary>
public static bool EnumerableIsEmpty<T>([NotNullWhen(returnValue: false)] IEnumerable<T>? enumerable)
{
return !EnumerableIsNotEmpty<T>(enumerable);
}
/// <summary>
/// Returns the number of elements in the given enumerable. A null enumerable is allowed and results in 0.
/// </summary>
public static uint EnumerableCount<T>(IEnumerable<T>? enumerable)
{
// ^ ensures result >= 0;
if (enumerable == null)
{
return 0;
}
var asIListT = enumerable as IList<T>;
if (asIListT != null)
{
return (uint)asIListT.Count;
}
var asIList = enumerable as IList;
if (asIList != null)
{
return (uint)asIList.Count;
}
uint result = 0;
IEnumerator<T> enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
{
result++;
}
return result & 0x7FFFFFFF;
}
}
/// <summary>
/// A declarative specification of a security action applied to a set of permissions. Used by the CLR loader to enforce security restrictions.
/// Each security attribute represents a serialized permission or permission set for a specified security action.
/// The union of the security attributes with identical security action, define the permission set to which the security action applies.
/// </summary>
internal struct SecurityAttribute
{
public DeclarativeSecurityAction Action { get; }
public ICustomAttribute Attribute { get; }
public SecurityAttribute(DeclarativeSecurityAction action, ICustomAttribute attribute)
{
Action = action;
Attribute = attribute;
}
}
/// <summary>
/// Information about how values of managed types should be marshalled to and from unmanaged types.
/// </summary>
internal interface IMarshallingInformation
{
/// <summary>
/// <see cref="ITypeReference"/> or a string (usually a fully-qualified type name of a type implementing the custom marshaller, but Dev11 allows any string).
/// </summary>
object GetCustomMarshaller(EmitContext context);
/// <summary>
/// An argument string (cookie) passed to the custom marshaller at run time.
/// </summary>
string CustomMarshallerRuntimeArgument
{
get;
}
/// <summary>
/// The unmanaged element type of the unmanaged array.
/// -1 if it should be omitted from the marshal blob.
/// </summary>
System.Runtime.InteropServices.UnmanagedType ElementType
{
get;
}
/// <summary>
/// Specifies the index of the parameter that contains the value of the Interface Identifier (IID) of the marshalled object.
/// -1 if it should be omitted from the marshal blob.
/// </summary>
int IidParameterIndex
{
get;
}
/// <summary>
/// The unmanaged type to which the managed type will be marshalled. This can be UnmanagedType.CustomMarshaler, in which case the unmanaged type
/// is decided at runtime.
/// </summary>
System.Runtime.InteropServices.UnmanagedType UnmanagedType { get; }
/// <summary>
/// The number of elements in the fixed size portion of the unmanaged array.
/// -1 if it should be omitted from the marshal blob.
/// </summary>
int NumberOfElements
{
get;
}
/// <summary>
/// The zero based index of the parameter in the unmanaged method that contains the number of elements in the variable portion of unmanaged array.
/// If -1, the variable portion is of size zero, or the caller conveys the size of the variable portion of the array to the unmanaged method in some other way.
/// </summary>
short ParamIndex
{
get;
}
/// <summary>
/// The type to which the variant values of all elements of the safe array must belong. See also SafeArrayElementUserDefinedSubtype.
/// (The element type of a safe array is VARIANT. The "sub type" specifies the value of all of the tag fields (vt) of the element values. )
/// -1 if it should be omitted from the marshal blob.
/// </summary>
VarEnum SafeArrayElementSubtype
{
get;
}
/// <summary>
/// A reference to the user defined type to which the variant values of all elements of the safe array must belong.
/// (The element type of a safe array is VARIANT. The tag fields will all be either VT_DISPATCH or VT_UNKNOWN or VT_RECORD.
/// The "user defined sub type" specifies the type of value the ppdispVal/ppunkVal/pvRecord fields of the element values may point to.)
/// </summary>
ITypeReference GetSafeArrayElementUserDefinedSubtype(EmitContext context);
}
/// <summary>
/// Implemented by any entity that has a name.
/// </summary>
internal interface INamedEntity
{
/// <summary>
/// The name of the entity.
/// </summary>
string? Name { get; }
}
/// <summary>
/// The name of the entity depends on other metadata (tokens, signatures) originated from
/// PeWriter.
/// </summary>
internal interface IContextualNamedEntity : INamedEntity
{
/// <summary>
/// Method must be called before calling INamedEntity.Name.
/// </summary>
void AssociateWithMetadataWriter(MetadataWriter metadataWriter);
}
/// <summary>
/// Implemented by an entity that is always a member of a particular parameter list, such as an IParameterDefinition.
/// Provides a way to determine the position where the entity appears in the parameter list.
/// </summary>
internal interface IParameterListEntry
{
/// <summary>
/// The position in the parameter list where this instance can be found.
/// </summary>
ushort Index { get; }
}
/// <summary>
/// Information that describes how a method from the underlying Platform is to be invoked.
/// </summary>
internal interface IPlatformInvokeInformation
{
/// <summary>
/// Module providing the method/field.
/// </summary>
string? ModuleName { get; }
/// <summary>
/// Name of the method providing the implementation.
/// </summary>
string? EntryPointName { get; }
/// <summary>
/// Flags that determine marshalling behavior.
/// </summary>
MethodImportAttributes Flags { get; }
}
internal class ResourceSection
{
internal ResourceSection(byte[] sectionBytes, uint[] relocations)
{
RoslynDebug.Assert(sectionBytes != null);
RoslynDebug.Assert(relocations != null);
SectionBytes = sectionBytes;
Relocations = relocations;
}
internal readonly byte[] SectionBytes;
//This is the offset into SectionBytes that should be modified.
//It should have the section's RVA added to it.
internal readonly uint[] Relocations;
}
/// <summary>
/// A resource file formatted according to Win32 API conventions and typically obtained from a Portable Executable (PE) file.
/// See the Win32 UpdateResource method for more details.
/// </summary>
internal interface IWin32Resource
{
/// <summary>
/// A string that identifies what type of resource this is. Only valid if this.TypeId < 0.
/// </summary>
string TypeName
{
get;
// ^ requires this.TypeId < 0;
}
/// <summary>
/// An integer tag that identifies what type of resource this is. If the value is less than 0, this.TypeName should be used instead.
/// </summary>
int TypeId
{
get;
}
/// <summary>
/// The name of the resource. Only valid if this.Id < 0.
/// </summary>
string Name
{
get;
// ^ requires this.Id < 0;
}
/// <summary>
/// An integer tag that identifies this resource. If the value is less than 0, this.Name should be used instead.
/// </summary>
int Id { get; }
/// <summary>
/// The language for which this resource is appropriate.
/// </summary>
uint LanguageId { get; }
/// <summary>
/// The code page for which this resource is appropriate.
/// </summary>
uint CodePage { get; }
/// <summary>
/// The data of the resource.
/// </summary>
IEnumerable<byte> Data { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Roslyn.Utilities;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
namespace Microsoft.Cci
{
/// <summary>
/// A container for static helper methods that are used for manipulating and computing iterators.
/// </summary>
internal static class IteratorHelper
{
/// <summary>
/// True if the given enumerable is not null and contains at least one element.
/// </summary>
public static bool EnumerableIsNotEmpty<T>([NotNullWhen(returnValue: true)] IEnumerable<T>? enumerable)
{
if (enumerable == null)
{
return false;
}
var asIListT = enumerable as IList<T>;
if (asIListT != null)
{
return asIListT.Count != 0;
}
var asIList = enumerable as IList;
if (asIList != null)
{
return asIList.Count != 0;
}
return enumerable.GetEnumerator().MoveNext();
}
/// <summary>
/// True if the given enumerable is null or contains no elements
/// </summary>
public static bool EnumerableIsEmpty<T>([NotNullWhen(returnValue: false)] IEnumerable<T>? enumerable)
{
return !EnumerableIsNotEmpty<T>(enumerable);
}
/// <summary>
/// Returns the number of elements in the given enumerable. A null enumerable is allowed and results in 0.
/// </summary>
public static uint EnumerableCount<T>(IEnumerable<T>? enumerable)
{
// ^ ensures result >= 0;
if (enumerable == null)
{
return 0;
}
var asIListT = enumerable as IList<T>;
if (asIListT != null)
{
return (uint)asIListT.Count;
}
var asIList = enumerable as IList;
if (asIList != null)
{
return (uint)asIList.Count;
}
uint result = 0;
IEnumerator<T> enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
{
result++;
}
return result & 0x7FFFFFFF;
}
}
/// <summary>
/// A declarative specification of a security action applied to a set of permissions. Used by the CLR loader to enforce security restrictions.
/// Each security attribute represents a serialized permission or permission set for a specified security action.
/// The union of the security attributes with identical security action, define the permission set to which the security action applies.
/// </summary>
internal struct SecurityAttribute
{
public DeclarativeSecurityAction Action { get; }
public ICustomAttribute Attribute { get; }
public SecurityAttribute(DeclarativeSecurityAction action, ICustomAttribute attribute)
{
Action = action;
Attribute = attribute;
}
}
/// <summary>
/// Information about how values of managed types should be marshalled to and from unmanaged types.
/// </summary>
internal interface IMarshallingInformation
{
/// <summary>
/// <see cref="ITypeReference"/> or a string (usually a fully-qualified type name of a type implementing the custom marshaller, but Dev11 allows any string).
/// </summary>
object GetCustomMarshaller(EmitContext context);
/// <summary>
/// An argument string (cookie) passed to the custom marshaller at run time.
/// </summary>
string CustomMarshallerRuntimeArgument
{
get;
}
/// <summary>
/// The unmanaged element type of the unmanaged array.
/// -1 if it should be omitted from the marshal blob.
/// </summary>
System.Runtime.InteropServices.UnmanagedType ElementType
{
get;
}
/// <summary>
/// Specifies the index of the parameter that contains the value of the Interface Identifier (IID) of the marshalled object.
/// -1 if it should be omitted from the marshal blob.
/// </summary>
int IidParameterIndex
{
get;
}
/// <summary>
/// The unmanaged type to which the managed type will be marshalled. This can be UnmanagedType.CustomMarshaler, in which case the unmanaged type
/// is decided at runtime.
/// </summary>
System.Runtime.InteropServices.UnmanagedType UnmanagedType { get; }
/// <summary>
/// The number of elements in the fixed size portion of the unmanaged array.
/// -1 if it should be omitted from the marshal blob.
/// </summary>
int NumberOfElements
{
get;
}
/// <summary>
/// The zero based index of the parameter in the unmanaged method that contains the number of elements in the variable portion of unmanaged array.
/// If -1, the variable portion is of size zero, or the caller conveys the size of the variable portion of the array to the unmanaged method in some other way.
/// </summary>
short ParamIndex
{
get;
}
/// <summary>
/// The type to which the variant values of all elements of the safe array must belong. See also SafeArrayElementUserDefinedSubtype.
/// (The element type of a safe array is VARIANT. The "sub type" specifies the value of all of the tag fields (vt) of the element values. )
/// -1 if it should be omitted from the marshal blob.
/// </summary>
VarEnum SafeArrayElementSubtype
{
get;
}
/// <summary>
/// A reference to the user defined type to which the variant values of all elements of the safe array must belong.
/// (The element type of a safe array is VARIANT. The tag fields will all be either VT_DISPATCH or VT_UNKNOWN or VT_RECORD.
/// The "user defined sub type" specifies the type of value the ppdispVal/ppunkVal/pvRecord fields of the element values may point to.)
/// </summary>
ITypeReference GetSafeArrayElementUserDefinedSubtype(EmitContext context);
}
/// <summary>
/// Implemented by any entity that has a name.
/// </summary>
internal interface INamedEntity
{
/// <summary>
/// The name of the entity.
/// </summary>
string? Name { get; }
}
/// <summary>
/// The name of the entity depends on other metadata (tokens, signatures) originated from
/// PeWriter.
/// </summary>
internal interface IContextualNamedEntity : INamedEntity
{
/// <summary>
/// Method must be called before calling INamedEntity.Name.
/// </summary>
void AssociateWithMetadataWriter(MetadataWriter metadataWriter);
}
/// <summary>
/// Implemented by an entity that is always a member of a particular parameter list, such as an IParameterDefinition.
/// Provides a way to determine the position where the entity appears in the parameter list.
/// </summary>
internal interface IParameterListEntry
{
/// <summary>
/// The position in the parameter list where this instance can be found.
/// </summary>
ushort Index { get; }
}
/// <summary>
/// Information that describes how a method from the underlying Platform is to be invoked.
/// </summary>
internal interface IPlatformInvokeInformation
{
/// <summary>
/// Module providing the method/field.
/// </summary>
string? ModuleName { get; }
/// <summary>
/// Name of the method providing the implementation.
/// </summary>
string? EntryPointName { get; }
/// <summary>
/// Flags that determine marshalling behavior.
/// </summary>
MethodImportAttributes Flags { get; }
}
internal class ResourceSection
{
internal ResourceSection(byte[] sectionBytes, uint[] relocations)
{
RoslynDebug.Assert(sectionBytes != null);
RoslynDebug.Assert(relocations != null);
SectionBytes = sectionBytes;
Relocations = relocations;
}
internal readonly byte[] SectionBytes;
//This is the offset into SectionBytes that should be modified.
//It should have the section's RVA added to it.
internal readonly uint[] Relocations;
}
/// <summary>
/// A resource file formatted according to Win32 API conventions and typically obtained from a Portable Executable (PE) file.
/// See the Win32 UpdateResource method for more details.
/// </summary>
internal interface IWin32Resource
{
/// <summary>
/// A string that identifies what type of resource this is. Only valid if this.TypeId < 0.
/// </summary>
string TypeName
{
get;
// ^ requires this.TypeId < 0;
}
/// <summary>
/// An integer tag that identifies what type of resource this is. If the value is less than 0, this.TypeName should be used instead.
/// </summary>
int TypeId
{
get;
}
/// <summary>
/// The name of the resource. Only valid if this.Id < 0.
/// </summary>
string Name
{
get;
// ^ requires this.Id < 0;
}
/// <summary>
/// An integer tag that identifies this resource. If the value is less than 0, this.Name should be used instead.
/// </summary>
int Id { get; }
/// <summary>
/// The language for which this resource is appropriate.
/// </summary>
uint LanguageId { get; }
/// <summary>
/// The code page for which this resource is appropriate.
/// </summary>
uint CodePage { get; }
/// <summary>
/// The data of the resource.
/// </summary>
IEnumerable<byte> Data { get; }
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/EditorFeatures/TestUtilities/AbstractTypingCommandHandlerTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
[UseExportProvider]
public abstract class AbstractTypingCommandHandlerTest<TCommandArgs> where TCommandArgs : CommandArgs
{
internal abstract ICommandHandler<TCommandArgs> GetCommandHandler(TestWorkspace workspace);
protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup);
protected abstract (TCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer);
protected void Verify(string initialMarkup, string expectedMarkup, Action<TestWorkspace> initializeWorkspace = null)
{
using (var workspace = CreateTestWorkspace(initialMarkup))
{
initializeWorkspace?.Invoke(workspace);
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
var commandHandler = GetCommandHandler(workspace);
var (args, insertionText) = CreateCommandArgs(view, view.TextBuffer);
var nextHandler = CreateInsertTextHandler(view, insertionText);
if (!commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()))
{
nextHandler();
}
MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition);
Assert.Equal(expectedCode, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
}
protected void VerifyTabs(string initialMarkup, string expectedMarkup)
=> Verify(ReplaceTabTags(initialMarkup), ReplaceTabTags(expectedMarkup));
private static string ReplaceTabTags(string markup) => markup.Replace("<tab>", "\t");
private static Action CreateInsertTextHandler(ITextView textView, string text)
{
return () =>
{
var caretPosition = textView.Caret.Position.BufferPosition;
var newSpanshot = textView.TextBuffer.Insert(caretPosition, text);
textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, (int)caretPosition + text.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.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
[UseExportProvider]
public abstract class AbstractTypingCommandHandlerTest<TCommandArgs> where TCommandArgs : CommandArgs
{
internal abstract ICommandHandler<TCommandArgs> GetCommandHandler(TestWorkspace workspace);
protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup);
protected abstract (TCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer);
protected void Verify(string initialMarkup, string expectedMarkup, Action<TestWorkspace> initializeWorkspace = null)
{
using (var workspace = CreateTestWorkspace(initialMarkup))
{
initializeWorkspace?.Invoke(workspace);
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
var commandHandler = GetCommandHandler(workspace);
var (args, insertionText) = CreateCommandArgs(view, view.TextBuffer);
var nextHandler = CreateInsertTextHandler(view, insertionText);
if (!commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()))
{
nextHandler();
}
MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition);
Assert.Equal(expectedCode, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
}
protected void VerifyTabs(string initialMarkup, string expectedMarkup)
=> Verify(ReplaceTabTags(initialMarkup), ReplaceTabTags(expectedMarkup));
private static string ReplaceTabTags(string markup) => markup.Replace("<tab>", "\t");
private static Action CreateInsertTextHandler(ITextView textView, string text)
{
return () =>
{
var caretPosition = textView.Caret.Position.BufferPosition;
var newSpanshot = textView.TextBuffer.Insert(caretPosition, text);
textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, (int)caretPosition + text.Length));
};
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Analyzers/CSharp/Tests/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementTests.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.NewLines.ConsecutiveStatementPlacement;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.NewLines.ConsecutiveStatementPlacement;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConsecutiveStatementPlacement
{
using Verify = CSharpCodeFixVerifier<
CSharpConsecutiveStatementPlacementDiagnosticAnalyzer,
ConsecutiveStatementPlacementCodeFixProvider>;
public class ConsecutiveStatementPlacementTests
{
[Fact]
public async Task TestNotAfterPropertyBlock()
{
var code =
@"
class C
{
int X { get; }
int Y { get; }
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterMethodBlock()
{
var code =
@"
class C
{
void X() { }
void Y() { }
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnSingleLine()
{
var code =
@"
class C
{
void M()
{
if (true) { } return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnSingleLineWithComment()
{
var code =
@"
class C
{
void M()
{
if (true) { }/*x*/return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnMultipleLinesWithCommentBetween1()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
/*x*/ return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnMultipleLinesWithCommentBetween2()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
/*x*/ return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsWithSingleBlankLines()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsWithSingleBlankLinesWithSpaces()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsWithMultipleBlankLines()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnMultipleLinesWithPPDirectiveBetween1()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
#pragma warning disable CS0001
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotBetweenBlockAndElseClause()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
else
{
}
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotBetweenBlockAndOuterBlocker()
{
var code =
@"
class C
{
void M()
{
if (true)
{
{
}
}
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotBetweenBlockAndCase()
{
var code =
@"
class C
{
void M()
{
switch (0)
{
case 0:
{
break;
}
case 1:
break;
}
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenBlockAndStatement1()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
if (true)
{
[|}|]
return;
}
}",
FixedCode = @"
class C
{
void M()
{
if (true)
{
}
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotBetweenBlockAndStatement1_WhenOptionOff()
{
var code = @"
class C
{
void M()
{
if (true)
{
}
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.TrueWithSilentEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenSwitchAndStatement1()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
switch (0)
{
[|}|]
return;
}
}",
FixedCode = @"
class C
{
void M()
{
switch (0)
{
}
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenBlockAndStatement2()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
if (true)
{
[|}|] // trailing comment
return;
}
}",
FixedCode = @"
class C
{
void M()
{
if (true)
{
} // trailing comment
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenBlockAndStatement3()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
if (true) { [|}|]
return;
}
}",
FixedCode = @"
class C
{
void M()
{
if (true) { }
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenBlockAndStatement4()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
switch (0)
{
case 0:
if (true) { [|}|]
return;
}
}
}",
FixedCode = @"
class C
{
void M()
{
switch (0)
{
case 0:
if (true) { }
return;
}
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestFixAll1()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
if (true)
{
[|}|]
return;
if (true)
{
[|}|]
return;
}
}",
FixedCode = @"
class C
{
void M()
{
if (true)
{
}
return;
if (true)
{
}
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestSA1513NegativeCases()
{
var code = @"using System;
using System.Linq;
using System.Collections.Generic;
public class Foo
{
private int x;
// Valid #1
public int Bar
{
get { return this.x; }
set { this.x = value; }
}
public void Baz()
{
// Valid #2
try
{
this.x++;
}
catch (Exception)
{
this.x = 0;
}
finally
{
this.x++;
}
// Valid #3
do
{
this.x++;
}
while (this.x < 10);
// Valid #4
if (this.x > 0)
{
this.x++;
}
else
{
this.x = 0;
}
// Valid #5
var y = new[] { 1, 2, 3 };
// Valid #6
if (this.x > 0)
{
if (y != null)
{
this.x = -this.x;
}
}
// Valid #7
if (this.x > 0)
{
this.x = 0;
}
#if !SOMETHING
else
{
this.x++;
}
#endif
// Valid #8
#if !SOMETHING
if (this.x > 0)
{
this.x = 0;
}
#else
if (this.x < 0)
{
this.x++;
}
#endif
// Valid #9
var q1 =
from a in new[]
{
1,
2,
3
}
from b in new[] { 4, 5, 6}
select a*b;
// Valid #10
var q2 =
from a in new[]
{
1,
2,
3
}
let b = new[]
{
a,
a * a,
a * a * a
}
select b;
// Valid #11
var q3 =
from a in new[]
{
1,
2,
3
}
where a > 0
select a;
// Valid #12
var q4 =
from a in new[]
{
new { Number = 1 },
new { Number = 2 },
new { Number = 3 }
}
join b in new[]
{
new { Number = 2 },
new { Number = 3 },
new { Number = 4 }
}
on a.Number equals b.Number
select new { Number1 = a.Number, Number2 = b.Number };
// Valid #13
var q5 =
from a in new[]
{
new { Number = 1 },
new { Number = 2 },
new { Number = 3 }
}
orderby a.Number descending
select a;
// Valid #14
var q6 =
from a in new[]
{
1,
2,
3
}
group new
{
Number = a,
Square = a * a
}
by a;
// Valid #15
var d = new[]
{
1, 2, 3
};
// Valid #16
this.Qux(i =>
{
return d[i] * 2;
});
// Valid #17
if (this.x > 2)
{
this.x = 3;
} /* Some comment */
// Valid #18
int[] testArray;
testArray =
new[]
{
1
};
// Valid #19
var z1 = new object[]
{
new
{
Id = 12
},
new
{
Id = 13
}
};
// Valid #20
var z2 = new System.Action[]
{
() =>
{
this.x = 3;
},
() =>
{
this.x = 4;
}
};
// Valid #21
var z3 = new
{
Value1 = new
{
Id = 12
},
Value2 = new
{
Id = 13
}
};
// Valid #22
var z4 = new System.Collections.Generic.List<object>
{
new
{
Id = 12
},
new
{
Id = 13
}
};
}
public void Qux(Func<int, int> function)
{
this.x = function(this.x);
}
public Func<int, int> Quux()
{
// Valid #23
#if SOMETHING
return null;
#else
return value =>
{
return value * 2;
};
#endif
}
// Valid #24 (will be handled by SA1516)
public int Corge
{
get
{
return this.x;
}
set { this.x = value; }
}
// Valid #25 (will be handled by SA1516)
public int Grault
{
set
{
this.x = value;
}
get
{
return this.x;
}
}
// Valid #26 (will be handled by SA1516)
public event EventHandler Garply
{
add
{
}
remove
{
}
}
// Valid #27 (will be handled by SA1516)
public event EventHandler Waldo
{
remove
{
}
add
{
}
}
// Valid #28 - Test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1020
private static IEnumerable<object> Method()
{
yield return new
{
prop = ""A""
};
}
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/784
public void MultiLineLinqQuery()
{
var someQuery = (from f in Enumerable.Empty<int>()
where f != 0
select new { Fish = ""Face"" }).ToList();
var someOtherQuery = (from f in Enumerable.Empty<int>()
where f != 0
select new
{
Fish = ""AreFriends"",
Not = ""Food""
}).ToList();
}
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2306
public void MultiLineGroupByLinqQuery()
{
var someQuery = from f in Enumerable.Empty<int>()
group f by new
{
f,
}
into a
select a;
var someOtherQuery = from f in Enumerable.Empty<int>()
group f by new { f }
into a
select a;
}
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1049
public object[] ExpressionBodiedProperty =>
new[]
{
new object()
};
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1049
public object[] ExpressionBodiedMethod() =>
new[]
{
new object()
};
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1049
public object[] GetterOnlyAutoProperty1 { get; } =
new[]
{
new object()
};
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1049
public object[] GetterOnlyAutoProperty2 { get; } =
{
};
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1173
bool contained =
new[]
{
1,
2,
3
}
.Contains(3);
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1583
public void TestTernaryConstruction()
{
var target = contained
? new Dictionary<string, string>
{
{ ""target"", ""_parent"" }
}
: new Dictionary<string, string>();
}
}
";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestSA1513PositiveCases()
{
await new Verify.Test()
{
TestCode = @"using System;
using System.Collections.Generic;
public class Goo
{
private int x;
// Invalid #1
public int Property1
{
get
{
return this.x;
}
set
{
this.x = value;
}
/* some comment */
}
// Invalid #2
public int Property2
{
get { return this.x; }
}
public void Baz()
{
// Invalid #3
switch (this.x)
{
case 1:
{
this.x = 1;
break;
}
case 2:
this.x = 2;
break;
}
// Invalid #4
{
var temp = this.x;
this.x = temp * temp;
[|}|]
this.x++;
// Invalid #5
if (this.x > 1)
{
this.x = 1;
[|}|]
if (this.x < 0)
{
this.x = 0;
[|}|]
switch (this.x)
{
// Invalid #6
case 0:
if (this.x < 0)
{
this.x = -1;
[|}|]
break;
// Invalid #7
case 1:
{
var temp = this.x * this.x;
this.x = temp;
[|}|]
break;
}
}
public void Example()
{
new List<Action>
{
() =>
{
if (true)
{
return;
[|}|]
return;
}
};
}
}
",
FixedCode = @"using System;
using System.Collections.Generic;
public class Goo
{
private int x;
// Invalid #1
public int Property1
{
get
{
return this.x;
}
set
{
this.x = value;
}
/* some comment */
}
// Invalid #2
public int Property2
{
get { return this.x; }
}
public void Baz()
{
// Invalid #3
switch (this.x)
{
case 1:
{
this.x = 1;
break;
}
case 2:
this.x = 2;
break;
}
// Invalid #4
{
var temp = this.x;
this.x = temp * temp;
}
this.x++;
// Invalid #5
if (this.x > 1)
{
this.x = 1;
}
if (this.x < 0)
{
this.x = 0;
}
switch (this.x)
{
// Invalid #6
case 0:
if (this.x < 0)
{
this.x = -1;
}
break;
// Invalid #7
case 1:
{
var temp = this.x * this.x;
this.x = temp;
}
break;
}
}
public void Example()
{
new List<Action>
{
() =>
{
if (true)
{
return;
}
return;
}
};
}
}
",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.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.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.NewLines.ConsecutiveStatementPlacement;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.NewLines.ConsecutiveStatementPlacement;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConsecutiveStatementPlacement
{
using Verify = CSharpCodeFixVerifier<
CSharpConsecutiveStatementPlacementDiagnosticAnalyzer,
ConsecutiveStatementPlacementCodeFixProvider>;
public class ConsecutiveStatementPlacementTests
{
[Fact]
public async Task TestNotAfterPropertyBlock()
{
var code =
@"
class C
{
int X { get; }
int Y { get; }
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterMethodBlock()
{
var code =
@"
class C
{
void X() { }
void Y() { }
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnSingleLine()
{
var code =
@"
class C
{
void M()
{
if (true) { } return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnSingleLineWithComment()
{
var code =
@"
class C
{
void M()
{
if (true) { }/*x*/return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnMultipleLinesWithCommentBetween1()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
/*x*/ return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnMultipleLinesWithCommentBetween2()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
/*x*/ return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsWithSingleBlankLines()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsWithSingleBlankLinesWithSpaces()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsWithMultipleBlankLines()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotAfterStatementsOnMultipleLinesWithPPDirectiveBetween1()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
#pragma warning disable CS0001
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotBetweenBlockAndElseClause()
{
var code =
@"
class C
{
void M()
{
if (true)
{
}
else
{
}
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotBetweenBlockAndOuterBlocker()
{
var code =
@"
class C
{
void M()
{
if (true)
{
{
}
}
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotBetweenBlockAndCase()
{
var code =
@"
class C
{
void M()
{
switch (0)
{
case 0:
{
break;
}
case 1:
break;
}
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenBlockAndStatement1()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
if (true)
{
[|}|]
return;
}
}",
FixedCode = @"
class C
{
void M()
{
if (true)
{
}
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestNotBetweenBlockAndStatement1_WhenOptionOff()
{
var code = @"
class C
{
void M()
{
if (true)
{
}
return;
}
}";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.TrueWithSilentEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenSwitchAndStatement1()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
switch (0)
{
[|}|]
return;
}
}",
FixedCode = @"
class C
{
void M()
{
switch (0)
{
}
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenBlockAndStatement2()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
if (true)
{
[|}|] // trailing comment
return;
}
}",
FixedCode = @"
class C
{
void M()
{
if (true)
{
} // trailing comment
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenBlockAndStatement3()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
if (true) { [|}|]
return;
}
}",
FixedCode = @"
class C
{
void M()
{
if (true) { }
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestBetweenBlockAndStatement4()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
switch (0)
{
case 0:
if (true) { [|}|]
return;
}
}
}",
FixedCode = @"
class C
{
void M()
{
switch (0)
{
case 0:
if (true) { }
return;
}
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestFixAll1()
{
await new Verify.Test()
{
TestCode = @"
class C
{
void M()
{
if (true)
{
[|}|]
return;
if (true)
{
[|}|]
return;
}
}",
FixedCode = @"
class C
{
void M()
{
if (true)
{
}
return;
if (true)
{
}
return;
}
}",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestSA1513NegativeCases()
{
var code = @"using System;
using System.Linq;
using System.Collections.Generic;
public class Foo
{
private int x;
// Valid #1
public int Bar
{
get { return this.x; }
set { this.x = value; }
}
public void Baz()
{
// Valid #2
try
{
this.x++;
}
catch (Exception)
{
this.x = 0;
}
finally
{
this.x++;
}
// Valid #3
do
{
this.x++;
}
while (this.x < 10);
// Valid #4
if (this.x > 0)
{
this.x++;
}
else
{
this.x = 0;
}
// Valid #5
var y = new[] { 1, 2, 3 };
// Valid #6
if (this.x > 0)
{
if (y != null)
{
this.x = -this.x;
}
}
// Valid #7
if (this.x > 0)
{
this.x = 0;
}
#if !SOMETHING
else
{
this.x++;
}
#endif
// Valid #8
#if !SOMETHING
if (this.x > 0)
{
this.x = 0;
}
#else
if (this.x < 0)
{
this.x++;
}
#endif
// Valid #9
var q1 =
from a in new[]
{
1,
2,
3
}
from b in new[] { 4, 5, 6}
select a*b;
// Valid #10
var q2 =
from a in new[]
{
1,
2,
3
}
let b = new[]
{
a,
a * a,
a * a * a
}
select b;
// Valid #11
var q3 =
from a in new[]
{
1,
2,
3
}
where a > 0
select a;
// Valid #12
var q4 =
from a in new[]
{
new { Number = 1 },
new { Number = 2 },
new { Number = 3 }
}
join b in new[]
{
new { Number = 2 },
new { Number = 3 },
new { Number = 4 }
}
on a.Number equals b.Number
select new { Number1 = a.Number, Number2 = b.Number };
// Valid #13
var q5 =
from a in new[]
{
new { Number = 1 },
new { Number = 2 },
new { Number = 3 }
}
orderby a.Number descending
select a;
// Valid #14
var q6 =
from a in new[]
{
1,
2,
3
}
group new
{
Number = a,
Square = a * a
}
by a;
// Valid #15
var d = new[]
{
1, 2, 3
};
// Valid #16
this.Qux(i =>
{
return d[i] * 2;
});
// Valid #17
if (this.x > 2)
{
this.x = 3;
} /* Some comment */
// Valid #18
int[] testArray;
testArray =
new[]
{
1
};
// Valid #19
var z1 = new object[]
{
new
{
Id = 12
},
new
{
Id = 13
}
};
// Valid #20
var z2 = new System.Action[]
{
() =>
{
this.x = 3;
},
() =>
{
this.x = 4;
}
};
// Valid #21
var z3 = new
{
Value1 = new
{
Id = 12
},
Value2 = new
{
Id = 13
}
};
// Valid #22
var z4 = new System.Collections.Generic.List<object>
{
new
{
Id = 12
},
new
{
Id = 13
}
};
}
public void Qux(Func<int, int> function)
{
this.x = function(this.x);
}
public Func<int, int> Quux()
{
// Valid #23
#if SOMETHING
return null;
#else
return value =>
{
return value * 2;
};
#endif
}
// Valid #24 (will be handled by SA1516)
public int Corge
{
get
{
return this.x;
}
set { this.x = value; }
}
// Valid #25 (will be handled by SA1516)
public int Grault
{
set
{
this.x = value;
}
get
{
return this.x;
}
}
// Valid #26 (will be handled by SA1516)
public event EventHandler Garply
{
add
{
}
remove
{
}
}
// Valid #27 (will be handled by SA1516)
public event EventHandler Waldo
{
remove
{
}
add
{
}
}
// Valid #28 - Test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1020
private static IEnumerable<object> Method()
{
yield return new
{
prop = ""A""
};
}
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/784
public void MultiLineLinqQuery()
{
var someQuery = (from f in Enumerable.Empty<int>()
where f != 0
select new { Fish = ""Face"" }).ToList();
var someOtherQuery = (from f in Enumerable.Empty<int>()
where f != 0
select new
{
Fish = ""AreFriends"",
Not = ""Food""
}).ToList();
}
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2306
public void MultiLineGroupByLinqQuery()
{
var someQuery = from f in Enumerable.Empty<int>()
group f by new
{
f,
}
into a
select a;
var someOtherQuery = from f in Enumerable.Empty<int>()
group f by new { f }
into a
select a;
}
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1049
public object[] ExpressionBodiedProperty =>
new[]
{
new object()
};
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1049
public object[] ExpressionBodiedMethod() =>
new[]
{
new object()
};
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1049
public object[] GetterOnlyAutoProperty1 { get; } =
new[]
{
new object()
};
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1049
public object[] GetterOnlyAutoProperty2 { get; } =
{
};
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1173
bool contained =
new[]
{
1,
2,
3
}
.Contains(3);
// This is a regression test for https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1583
public void TestTernaryConstruction()
{
var target = contained
? new Dictionary<string, string>
{
{ ""target"", ""_parent"" }
}
: new Dictionary<string, string>();
}
}
";
await new Verify.Test()
{
TestCode = code,
FixedCode = code,
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
[Fact]
public async Task TestSA1513PositiveCases()
{
await new Verify.Test()
{
TestCode = @"using System;
using System.Collections.Generic;
public class Goo
{
private int x;
// Invalid #1
public int Property1
{
get
{
return this.x;
}
set
{
this.x = value;
}
/* some comment */
}
// Invalid #2
public int Property2
{
get { return this.x; }
}
public void Baz()
{
// Invalid #3
switch (this.x)
{
case 1:
{
this.x = 1;
break;
}
case 2:
this.x = 2;
break;
}
// Invalid #4
{
var temp = this.x;
this.x = temp * temp;
[|}|]
this.x++;
// Invalid #5
if (this.x > 1)
{
this.x = 1;
[|}|]
if (this.x < 0)
{
this.x = 0;
[|}|]
switch (this.x)
{
// Invalid #6
case 0:
if (this.x < 0)
{
this.x = -1;
[|}|]
break;
// Invalid #7
case 1:
{
var temp = this.x * this.x;
this.x = temp;
[|}|]
break;
}
}
public void Example()
{
new List<Action>
{
() =>
{
if (true)
{
return;
[|}|]
return;
}
};
}
}
",
FixedCode = @"using System;
using System.Collections.Generic;
public class Goo
{
private int x;
// Invalid #1
public int Property1
{
get
{
return this.x;
}
set
{
this.x = value;
}
/* some comment */
}
// Invalid #2
public int Property2
{
get { return this.x; }
}
public void Baz()
{
// Invalid #3
switch (this.x)
{
case 1:
{
this.x = 1;
break;
}
case 2:
this.x = 2;
break;
}
// Invalid #4
{
var temp = this.x;
this.x = temp * temp;
}
this.x++;
// Invalid #5
if (this.x > 1)
{
this.x = 1;
}
if (this.x < 0)
{
this.x = 0;
}
switch (this.x)
{
// Invalid #6
case 0:
if (this.x < 0)
{
this.x = -1;
}
break;
// Invalid #7
case 1:
{
var temp = this.x * this.x;
this.x = temp;
}
break;
}
}
public void Example()
{
new List<Action>
{
() =>
{
if (true)
{
return;
}
return;
}
};
}
}
",
Options = { { CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
}.RunAsync();
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.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.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Castle.Core.Resource;
using Microsoft.CodeAnalysis.CommandLine;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
public class CompilerServerUnitTests : TestBase
{
internal static readonly RequestLanguage CSharpCompilerClientExecutable = RequestLanguage.CSharpCompile;
internal static readonly RequestLanguage BasicCompilerClientExecutable = RequestLanguage.VisualBasicCompile;
internal static readonly UTF8Encoding UTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
private static readonly KeyValuePair<string, string>[] s_helloWorldSrcCs =
{
new KeyValuePair<string, string>("hello.cs",
@"using System;
using System.Diagnostics;
class Hello
{
static void Main()
{
var obj = new Process();
Console.WriteLine(""Hello, world."");
}
}")
};
private static readonly KeyValuePair<string, string>[] s_helloWorldSrcVb =
{
new KeyValuePair<string, string>("hello.vb",
@"Imports System
Imports System.Diagnostics
Module Module1
Sub Main()
Dim p As New Process()
Console.WriteLine(""Hello from VB"")
End Sub
End Module")
};
private readonly TempDirectory _tempDirectory;
private readonly ICompilerServerLogger _logger;
public CompilerServerUnitTests(ITestOutputHelper testOutputHelper)
{
_tempDirectory = Temp.CreateDirectory();
_logger = new XunitCompilerServerLogger(testOutputHelper);
}
#region Helpers
private static IEnumerable<KeyValuePair<string, string>> AddForLoggingEnvironmentVars(IEnumerable<KeyValuePair<string, string>> vars)
{
vars = vars ?? new KeyValuePair<string, string>[] { };
if (!vars.Where(kvp => kvp.Key == "RoslynCommandLineLogFile").Any())
{
var list = vars.ToList();
list.Add(new KeyValuePair<string, string>(
"RoslynCommandLineLogFile",
typeof(CompilerServerUnitTests).Assembly.Location + ".client-server.log"));
return list;
}
return vars;
}
private static void CheckForBadShared(List<string> arguments)
{
bool hasShared;
string keepAlive;
string errorMessage;
string pipeName;
List<string> parsedArgs;
if (CommandLineParser.TryParseClientArgs(
arguments,
out parsedArgs,
out hasShared,
out keepAlive,
out pipeName,
out errorMessage))
{
if (hasShared && string.IsNullOrEmpty(pipeName))
{
throw new InvalidOperationException("Must specify a pipe name in these suites to ensure we're not running out of proc servers");
}
}
}
private static void ReferenceNetstandardDllIfCoreClr(TempDirectory currentDirectory, List<string> arguments)
{
#if !NET472
var filePath = Path.Combine(currentDirectory.Path, "netstandard.dll");
File.WriteAllBytes(filePath, TestMetadata.ResourcesNetStandard20.netstandard);
arguments.Add("/nostdlib");
arguments.Add("/r:netstandard.dll");
#endif
}
private static void CreateFiles(TempDirectory currentDirectory, IEnumerable<KeyValuePair<string, string>> files)
{
if (files != null)
{
foreach (var pair in files)
{
TempFile file = currentDirectory.CreateFile(pair.Key);
file.WriteAllText(pair.Value);
}
}
}
private static T ApplyEnvironmentVariables<T>(
IEnumerable<KeyValuePair<string, string>> environmentVariables,
Func<T> func)
{
if (environmentVariables == null)
{
return func();
}
var resetVariables = new Dictionary<string, string>();
try
{
foreach (var variable in environmentVariables)
{
resetVariables.Add(variable.Key, Environment.GetEnvironmentVariable(variable.Key));
Environment.SetEnvironmentVariable(variable.Key, variable.Value);
}
return func();
}
finally
{
foreach (var variable in resetVariables)
{
Environment.SetEnvironmentVariable(variable.Key, variable.Value);
}
}
}
private static (T Result, string Output) UseTextWriter<T>(Encoding encoding, Func<TextWriter, T> func)
{
MemoryStream memoryStream;
TextWriter writer;
if (encoding == null)
{
memoryStream = null;
writer = new StringWriter();
}
else
{
memoryStream = new MemoryStream();
writer = new StreamWriter(memoryStream, encoding);
}
var result = func(writer);
writer.Flush();
if (memoryStream != null)
{
return (result, encoding.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
}
else
{
return (result, ((StringWriter)writer).ToString());
}
}
internal (int ExitCode, string Output) RunCommandLineCompiler(
RequestLanguage language,
string argumentsSingle,
TempDirectory currentDirectory,
IEnumerable<KeyValuePair<string, string>> filesInDirectory = null,
IEnumerable<KeyValuePair<string, string>> additionalEnvironmentVars = null,
Encoding redirectEncoding = null,
bool shouldRunOnServer = true)
{
var arguments = new List<string>(argumentsSingle.Split(' '));
// This is validating that localization to a specific locale works no matter what the locale of the
// machine running the tests are.
arguments.Add("/preferreduilang:en");
ReferenceNetstandardDllIfCoreClr(currentDirectory, arguments);
CheckForBadShared(arguments);
CreateFiles(currentDirectory, filesInDirectory);
// Create a client to run the build. Infinite timeout is used to account for the
// case where these tests are run under extreme load. In high load scenarios the
// client will correctly drop down to a local compilation if the server doesn't respond
// fast enough.
var client = ServerUtil.CreateBuildClient(language, _logger, timeoutOverride: Timeout.Infinite);
var sdkDir = ServerUtil.DefaultSdkDirectory;
var buildPaths = new BuildPaths(
clientDir: Path.GetDirectoryName(typeof(CommonCompiler).Assembly.Location),
workingDir: currentDirectory.Path,
sdkDir: sdkDir,
tempDir: BuildServerConnection.GetTempPath(currentDirectory.Path));
var (result, output) = UseTextWriter(redirectEncoding, writer => ApplyEnvironmentVariables(additionalEnvironmentVars, () => client.RunCompilation(arguments, buildPaths, writer)));
Assert.Equal(shouldRunOnServer, result.RanOnServer);
return (result.ExitCode, output);
}
/// <summary>
/// Compiles some source code and returns the bytes that were contained in the compiled DLL file.
///
/// Each time that this function is called, it will be compiled in a different directory.
///
/// The default flags are "/shared /deterministic+ /nologo /t:library".
/// </summary>
/// <param name="source"> The source code for the program that will be compiled </param>
/// <returns> An array of bytes that were read from the compiled DLL</returns>
private async Task<(byte[] assemblyBytes, string finalFlags)> CompileAndGetBytes(string source, string flags)
{
// Setup
var tempDir = Temp.CreateDirectory();
var srcFile = tempDir.CreateFile("test.cs").WriteAllText(source).Path;
var outFile = srcFile.Replace("test.cs", "test.dll");
try
{
string finalFlags = null;
using (var serverData = await ServerUtil.CreateServer(_logger))
{
finalFlags = $"{flags} /shared:{serverData.PipeName} /pathmap:{tempDir.Path}=/ /out:{outFile} {srcFile}";
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
finalFlags,
currentDirectory: tempDir);
if (result.ExitCode != 0)
{
AssertEx.Fail($"Deterministic compile failed \n stdout: { result.Output }");
}
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
var bytes = File.ReadAllBytes(outFile);
AssertEx.NotNull(bytes);
return (bytes, finalFlags);
}
finally
{
File.Delete(srcFile);
File.Delete(outFile);
}
}
private static DisposableFile GetResultFile(TempDirectory directory, string resultFileName)
{
return new DisposableFile(Path.Combine(directory.Path, resultFileName));
}
private static void RunCompilerOutput(TempFile file, string expectedOutput)
{
if (RuntimeHostInfo.IsDesktopRuntime)
{
var result = ProcessUtilities.Run(file.Path, "", Path.GetDirectoryName(file.Path));
Assert.Equal(expectedOutput.Trim(), result.Output.Trim());
}
}
private static void VerifyResult((int ExitCode, string Output) result)
{
AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output);
Assert.Equal(0, result.ExitCode);
}
private void VerifyResultAndOutput((int ExitCode, string Output) result, TempDirectory path, string expectedOutput)
{
using (var resultFile = GetResultFile(path, "hello.exe"))
{
VerifyResult(result);
RunCompilerOutput(resultFile, expectedOutput);
}
}
#endregion
[ConditionalFact(typeof(UnixLikeOnly))]
public async Task ServerFailsWithLongTempPathUnix()
{
var newTempDir = _tempDirectory.CreateDirectory(new string('a', 100 - _tempDirectory.Path.Length));
await ApplyEnvironmentVariables(
new[] { new KeyValuePair<string, string>("TMPDIR", newTempDir.Path) },
async () =>
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo hello.cs",
_tempDirectory,
s_helloWorldSrcCs,
shouldRunOnServer: true);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
});
}
[Fact]
public async Task FallbackToCsc()
{
// Verify csc will fall back to command line when server fails to process
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs, shouldRunOnServer: false);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task CscFallBackOutputNoUtf8()
{
// Verify csc will fall back to command line when server fails to process
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var files = new Dictionary<string, string> { { "hello.cs", "♕" } };
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, files, redirectEncoding: Encoding.ASCII, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("hello.cs(1,1): error CS1056: Unexpected character '?'", result.Output.Trim());
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task CscFallBackOutputUtf8()
{
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /utf8output /nologo /t:library {srcFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding,
shouldRunOnServer: false);
Assert.Equal("test.cs(1,1): error CS1056: Unexpected character '♕'".Trim(),
result.Output.Trim().Replace(srcFile, "test.cs"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task VbcFallbackNoUtf8()
{
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText("♕").Path;
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /vbruntime* /nologo test.vb",
_tempDirectory,
redirectEncoding: Encoding.ASCII,
shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal(@"test.vb(1) : error BC30037: Character is not valid.
?
~", result.Output.Trim().Replace(srcFile, "test.vb"));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task VbcFallbackUtf8()
{
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText("♕").Path;
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /vbruntime* /utf8output /nologo /t:library {srcFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding,
shouldRunOnServer: false);
Assert.Equal(@"test.vb(1) : error BC30037: Character is not valid.
♕
~", result.Output.Trim().Replace(srcFile, "test.vb"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task FallbackToVbc()
{
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /vbruntime* hello.vb", _tempDirectory, s_helloWorldSrcVb, shouldRunOnServer: false);
VerifyResultAndOutput(result, _tempDirectory, "Hello from VB");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task HelloWorldCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task HelloWorldCSDashShared()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"-shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")]
public void CompilerBinariesAreNotX86()
{
var basePath = Path.GetDirectoryName(typeof(CompilerServerUnitTests).Assembly.Location);
var compilerServerExecutable = Path.Combine(basePath, "VBCSCompiler.exe");
Assert.NotEqual(ProcessorArchitecture.X86,
AssemblyName.GetAssemblyName(compilerServerExecutable).ProcessorArchitecture);
}
/// <summary>
/// This method tests that when a 64-bit compiler server loads a
/// 64-bit mscorlib with /platform:x86 enabled no warning about
/// emitting a reference to a 64-bit assembly is produced.
/// The test should pass on x86 or amd64, but can only fail on
/// amd64.
/// </summary>
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Platformx86MscorlibCsc()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var files = new Dictionary<string, string> { { "c.cs", "class C {}" } };
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /t:library /platform:x86 c.cs",
_tempDirectory,
files);
VerifyResult(result);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Platformx86MscorlibVbc()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var files = new Dictionary<string, string> { { "c.vb", "Class C\nEnd Class" } };
var result = RunCommandLineCompiler(BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /vbruntime* /nologo /t:library /platform:x86 c.vb",
_tempDirectory,
files);
VerifyResult(result);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[ConditionalFact(typeof(DesktopOnly))]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task ExtraMSCorLibCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /r:mscorlib.dll hello.cs",
_tempDirectory,
s_helloWorldSrcCs);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task HelloWorldVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /vbruntime* hello.vb",
_tempDirectory,
s_helloWorldSrcVb);
VerifyResultAndOutput(result, _tempDirectory, "Hello from VB");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[ConditionalFact(typeof(DesktopOnly))]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task ExtraMSCorLibVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /r:mscorlib.dll /vbruntime* hello.vb",
_tempDirectory,
s_helloWorldSrcVb);
VerifyResultAndOutput(result, _tempDirectory, "Hello from VB");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task CompileErrorsCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "hello.cs",
@"using System;
class Hello
{
static void Main()
{ Console.WriteLine(""Hello, world."") }
}"}};
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} hello.cs", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("hello.cs(5,42): error CS1002: ; expected", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "hello.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task CompileErrorsVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "hellovb.vb",
@"Imports System
Module Module1
Sub Main()
Console.WriteLine(""Hello from VB"")
End Sub
End Class"}};
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /vbruntime* hellovb.vb", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("hellovb.vb(3) : error BC30625: 'Module' statement must end with a matching 'End Module'.", result.Output, StringComparison.Ordinal);
Assert.Contains("hellovb.vb(7) : error BC30460: 'End Class' must be preceded by a matching 'Class'.", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "hello.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MissingFileErrorCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} missingfile.cs", _tempDirectory);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("error CS2001: Source file", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "missingfile.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MissingReferenceErrorCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /r:missing.dll hello.cs", _tempDirectory, s_helloWorldSrcCs);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("error CS0006: Metadata file", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "hello.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(546067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546067")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task InvalidMetadataFileErrorCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "Lib.cs", "public class C {}"},
{ "app.cs", "class Test { static void Main() {} }"},
};
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /r:Lib.cs app.cs", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("error CS0009: Metadata file", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "app.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MissingFileErrorVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /vbruntime* missingfile.vb", _tempDirectory);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("error BC2001", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "missingfile.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact, WorkItem(761131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/761131")]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MissingReferenceErrorVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "hellovb.vb",
@"Imports System.Diagnostics
Module Module1
Sub Main()
Dim p As New Process()
Console.WriteLine(""Hello from VB"")
End Sub
End Module"}};
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /vbruntime* /r:missing.dll hellovb.vb", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("error BC2017: could not find library", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "hellovb.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(546067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546067")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task InvalidMetadataFileErrorVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "Lib.vb",
@"Class C
End Class" },
{ "app.vb",
@"Module M1
Sub Main()
End Sub
End Module"}};
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /vbruntime* /r:Lib.vb app.vb", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("error BC31519", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "app.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/20345")]
[WorkItem(723280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/723280")]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task ReferenceCachingVB()
{
TempDirectory rootDirectory = _tempDirectory.CreateDirectory("ReferenceCachingVB");
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "src1.vb",
@"Imports System
Public Class Library
Public Shared Function GetString() As String
Return ""library1""
End Function
End Class
"}};
using (var serverData = await ServerUtil.CreateServer(_logger))
using (var tmpFile = GetResultFile(rootDirectory, "lib.dll"))
{
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"src1.vb /shared:{serverData.PipeName} /nologo /t:library /out:lib.dll", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
using (var hello1_file = GetResultFile(rootDirectory, "hello1.exe"))
{
// Create EXE "hello1.exe"
files = new Dictionary<string, string> {
{ "hello1.vb",
@"Imports System
Module Module1
Public Sub Main()
Console.WriteLine(""Hello1 from {0}"", Library.GetString())
End Sub
End Module
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"hello1.vb /shared:{serverData.PipeName} /nologo /vbruntime* /r:lib.dll /out:hello1.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello1.exe.
RunCompilerOutput(hello1_file, "Hello1 from library1");
using (var hello2_file = GetResultFile(rootDirectory, "hello2.exe"))
{
// Create EXE "hello2.exe" referencing same DLL
files = new Dictionary<string, string> {
{ "hello2.vb",
@"Imports System
Module Module1
Public Sub Main()
Console.WriteLine(""Hello2 from {0}"", Library.GetString())
End Sub
End Module
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"hello2.vb /shared:{serverData.PipeName} /nologo /vbruntime* /r:lib.dll /out:hello2.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello2.exe.
RunCompilerOutput(hello2_file, "Hello2 from library1");
// Change DLL "lib.dll" to something new.
files =
new Dictionary<string, string> {
{ "src2.vb",
@"Imports System
Public Class Library
Public Shared Function GetString() As String
Return ""library2""
End Function
Public Shared Function GetString2() As String
Return ""library3""
End Function
End Class
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"src2.vb /shared:{serverData.PipeName} /nologo /t:library /out:lib.dll", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
using (var hello3_file = GetResultFile(rootDirectory, "hello3.exe"))
{
// Create EXE "hello3.exe" referencing new DLL
files = new Dictionary<string, string> {
{ "hello3.vb",
@"Imports System
Module Module1
Public Sub Main()
Console.WriteLine(""Hello3 from {0}"", Library.GetString2())
End Sub
End Module
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"hello3.vb /shared:{serverData.PipeName} /nologo /vbruntime* /r:lib.dll /out:hello3.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello3.exe. Should work.
RunCompilerOutput(hello3_file, "Hello3 from library3");
// Run hello2.exe one more time. Should have different output than before from updated library.
RunCompilerOutput(hello2_file, "Hello2 from library2");
}
}
}
var listener = await serverData.Complete();
Assert.Equal(5, listener.CompletionDataList.Count);
Assert.All(listener.CompletionDataList, completionData => Assert.Equal(CompletionReason.RequestCompleted, completionData.Reason));
}
GC.KeepAlive(rootDirectory);
}
[ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/19763")]
[WorkItem(723280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/723280")]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task ReferenceCachingCS()
{
TempDirectory rootDirectory = _tempDirectory.CreateDirectory("ReferenceCachingCS");
using (var serverData = await ServerUtil.CreateServer(_logger))
using (var tmpFile = GetResultFile(rootDirectory, "lib.dll"))
{
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "src1.cs",
@"using System;
public class Library
{
public static string GetString()
{ return ""library1""; }
}"}};
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"src1.cs /shared:{serverData.PipeName} /nologo /t:library /out:lib.dll", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
using (var hello1_file = GetResultFile(rootDirectory, "hello1.exe"))
{
// Create EXE "hello1.exe"
files = new Dictionary<string, string> {
{ "hello1.cs",
@"using System;
class Hello
{
public static void Main()
{ Console.WriteLine(""Hello1 from {0}"", Library.GetString()); }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"hello1.cs /shared:{serverData.PipeName} /nologo /r:lib.dll /out:hello1.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello1.exe.
RunCompilerOutput(hello1_file, "Hello1 from library1");
using (var hello2_file = GetResultFile(rootDirectory, "hello2.exe"))
{
var hello2exe = Temp.AddFile(hello2_file);
// Create EXE "hello2.exe" referencing same DLL
files = new Dictionary<string, string> {
{ "hello2.cs",
@"using System;
class Hello
{
public static void Main()
{ Console.WriteLine(""Hello2 from {0}"", Library.GetString()); }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"hello2.cs /shared:{serverData.PipeName} /nologo /r:lib.dll /out:hello2.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello2.exe.
RunCompilerOutput(hello2exe, "Hello2 from library1");
// Change DLL "lib.dll" to something new.
files =
new Dictionary<string, string> {
{ "src2.cs",
@"using System;
public class Library
{
public static string GetString()
{ return ""library2""; }
public static string GetString2()
{ return ""library3""; }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"src2.cs /shared:{serverData.PipeName} /nologo /t:library /out:lib.dll", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
using (var hello3_file = GetResultFile(rootDirectory, "hello3.exe"))
{
// Create EXE "hello3.exe" referencing new DLL
files = new Dictionary<string, string> {
{ "hello3.cs",
@"using System;
class Hello
{
public static void Main()
{ Console.WriteLine(""Hello3 from {0}"", Library.GetString2()); }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"hello3.cs /shared:{serverData.PipeName} /nologo /r:lib.dll /out:hello3.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello3.exe. Should work.
RunCompilerOutput(hello3_file, "Hello3 from library3");
// Run hello2.exe one more time. Should have different output than before from updated library.
RunCompilerOutput(hello2_file, "Hello2 from library2");
}
}
}
var listener = await serverData.Complete();
Assert.Equal(5, listener.CompletionDataList.Count);
Assert.All(listener.CompletionDataList, completionData => Assert.Equal(CompletionReason.RequestCompleted, completionData.Reason));
}
GC.KeepAlive(rootDirectory);
}
private Task<DisposableFile> RunCompilationAsync(RequestLanguage language, string pipeName, int i, TempDirectory compilationDir)
{
string sourceFile;
string exeFileName;
string prefix;
string sourceText;
string additionalArgument;
if (language == RequestLanguage.CSharpCompile)
{
exeFileName = $"hellocs{i}.exe";
prefix = "CS";
sourceFile = $"hello{i}.cs";
sourceText =
$@"using System;
class Hello
{{
public static void Main()
{{ Console.WriteLine(""{prefix} Hello number {i}""); }}
}}";
additionalArgument = "";
}
else
{
exeFileName = $"hellovb{i}.exe";
prefix = "VB";
sourceFile = $"hello{i}.vb";
sourceText =
$@"Imports System
Module Hello
Sub Main()
Console.WriteLine(""{prefix} Hello number {i}"")
End Sub
End Module";
additionalArgument = " /vbruntime*";
}
var arguments = $"/shared:{pipeName} /nologo {sourceFile} /out:{exeFileName}{additionalArgument}";
var filesInDirectory = new Dictionary<string, string>()
{
{ sourceFile, sourceText }
};
return Task.Run(() =>
{
var result = RunCommandLineCompiler(language, string.Join(" ", arguments), compilationDir, filesInDirectory: filesInDirectory);
Assert.Equal(0, result.ExitCode);
// Run the EXE and verify it prints the desired output.
var exeFile = GetResultFile(compilationDir, exeFileName);
RunCompilerOutput(exeFile, $"{prefix} Hello number {i}");
return exeFile;
});
}
[WorkItem(997372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997372")]
[WorkItem(761326, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/761326")]
[ConditionalFact(typeof(WindowsOnly))]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MultipleSimultaneousCompiles()
{
using var serverData = await ServerUtil.CreateServer(_logger);
// Run this many compiles simultaneously in different directories.
const int numberOfCompiles = 20;
var tasks = new Task<DisposableFile>[numberOfCompiles];
for (int i = 0; i < numberOfCompiles; ++i)
{
var language = i % 2 == 0 ? RequestLanguage.CSharpCompile : RequestLanguage.VisualBasicCompile;
var compilationDir = Temp.CreateDirectory();
tasks[i] = RunCompilationAsync(language, serverData.PipeName, i, compilationDir);
}
await Task.WhenAll(tasks);
var listener = await serverData.Complete();
Assert.Equal(numberOfCompiles, listener.CompletionDataList.Count);
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task UseLibVariableCS()
{
var libDirectory = _tempDirectory.CreateDirectory("LibraryDir");
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "src1.cs",
@"
public class Library
{
public static string GetString()
{ return ""library1""; }
}"}};
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"src1.cs /shared:{serverData.PipeName} /nologo /t:library /out:" + Path.Combine(libDirectory.Path, "lib.dll"),
_tempDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
Temp.AddFile(GetResultFile(libDirectory, "lib.dll"));
// Create EXE "hello1.exe"
files = new Dictionary<string, string> {
{ "hello1.cs",
@"using System;
class Hello
{
public static void Main()
{ Console.WriteLine(""Hello1 from {0}"", Library.GetString()); }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"hello1.cs /shared:{serverData.PipeName} /nologo /r:lib.dll /out:hello1.exe", _tempDirectory, files,
additionalEnvironmentVars: new Dictionary<string, string>() { { "LIB", libDirectory.Path } });
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
var resultFile = Temp.AddFile(GetResultFile(_tempDirectory, "hello1.exe"));
var listener = await serverData.Complete();
Assert.Equal(2, listener.CompletionDataList.Count);
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task UseLibVariableVB()
{
var libDirectory = _tempDirectory.CreateDirectory("LibraryDir");
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "src1.vb",
@"Imports System
Public Class Library
Public Shared Function GetString() As String
Return ""library1""
End Function
End Class
"}};
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable,
$"src1.vb /shared:{serverData.PipeName} /vbruntime* /nologo /t:library /out:" + Path.Combine(libDirectory.Path, "lib.dll"),
_tempDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
Temp.AddFile(GetResultFile(libDirectory, "lib.dll"));
// Create EXE "hello1.exe"
files = new Dictionary<string, string> {
{ "hello1.vb",
@"Imports System
Module Module1
Public Sub Main()
Console.WriteLine(""Hello1 from {0}"", Library.GetString())
End Sub
End Module
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"hello1.vb /shared:{serverData.PipeName} /nologo /vbruntime* /r:lib.dll /out:hello1.exe", _tempDirectory, files,
additionalEnvironmentVars: new Dictionary<string, string>() { { "LIB", libDirectory.Path } });
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
var resultFile = Temp.AddFile(GetResultFile(_tempDirectory, "hello1.exe"));
var listener = await serverData.Complete();
Assert.Equal(2, listener.CompletionDataList.Count);
}
[WorkItem(545446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545446")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Utf8Output_WithRedirecting_Off_Shared()
{
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /t:library {srcFile}",
_tempDirectory,
redirectEncoding: Encoding.ASCII);
Assert.Equal("test.cs(1,1): error CS1056: Unexpected character '?'".Trim(),
result.Output.Trim());
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(545446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545446")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Utf8Output_WithRedirecting_Off_Share()
{
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText(@"♕").Path;
var tempOut = _tempDirectory.CreateFile("output.txt");
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /vbruntime* /t:library {srcFile}",
_tempDirectory,
redirectEncoding: Encoding.ASCII);
Assert.Equal(@"SRC.VB(1) : error BC30037: Character is not valid.
?
~
".Trim(),
result.Output.Trim().Replace(srcFile, "SRC.VB"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(545446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545446")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Utf8Output_WithRedirecting_On_Shared_CS()
{
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /utf8output /nologo /t:library {srcFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding);
Assert.Equal("test.cs(1,1): error CS1056: Unexpected character '♕'".Trim(),
result.Output.Trim());
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(545446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545446")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Utf8Output_WithRedirecting_On_Shared_VB()
{
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText(@"♕").Path;
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /utf8output /nologo /vbruntime* /t:library {srcFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding);
Assert.Equal(@"SRC.VB(1) : error BC30037: Character is not valid.
♕
~
".Trim(),
result.Output.Trim().Replace(srcFile, "SRC.VB"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(871477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/871477")]
[ConditionalFact(typeof(DesktopOnly))]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task AssemblyIdentityComparer1()
{
_tempDirectory.CreateFile("mscorlib20.dll").WriteAllBytes(TestMetadata.ResourcesNet20.mscorlib);
_tempDirectory.CreateFile("mscorlib40.dll").WriteAllBytes(TestMetadata.ResourcesNet40.mscorlib);
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "ref_mscorlib2.cs",
@"public class C
{
public System.Exception GetException()
{
return new System.Exception();
}
}
"}};
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"ref_mscorlib2.cs /shared:{serverData.PipeName} /nologo /nostdlib /noconfig /t:library /r:mscorlib20.dll",
_tempDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
Temp.AddFile(GetResultFile(_tempDirectory, "ref_mscorlib2.dll"));
// Create EXE "main.exe"
files = new Dictionary<string, string> {
{ "main.cs",
@"using System;
class Program
{
static void Main(string[] args)
{
var e = new C().GetException();
Console.WriteLine(e);
}
}
"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"main.cs /shared:{serverData.PipeName} /nologo /nostdlib /noconfig /r:mscorlib40.dll /r:ref_mscorlib2.dll",
_tempDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(2, listener.CompletionDataList.Count);
}
[WorkItem(979588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/979588")]
[Fact]
public async Task Utf8OutputInRspFileCsc()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
var rspFile = _tempDirectory.CreateFile("temp.rsp").WriteAllText(
string.Format("/utf8output /nologo /t:library {0}", srcFile));
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /noconfig @{rspFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding);
Assert.Equal("test.cs(1,1): error CS1056: Unexpected character '♕'",
result.Output.Trim());
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(979588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/979588")]
[Fact]
public async Task Utf8OutputInRspFileVbc()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
var rspFile = _tempDirectory.CreateFile("temp.rsp").WriteAllText(
string.Format("/utf8output /nologo /vbruntime* /t:library {0}", srcFile));
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /noconfig @{rspFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding);
Assert.Equal(@"src.vb(1) : error BC30037: Character is not valid.
♕
~", result.Output.Trim().Replace(srcFile, "src.vb"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(25777, "https://github.com/dotnet/roslyn/issues/25777")]
[ConditionalFact(typeof(DesktopOnly), typeof(IsEnglishLocal))]
public void BadKeepAlive1()
{
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, "/shared /keepalive", _tempDirectory, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("Missing argument for '/keepalive' option.", result.Output.Trim());
}
[WorkItem(25777, "https://github.com/dotnet/roslyn/issues/25777")]
[ConditionalFact(typeof(DesktopOnly), typeof(IsEnglishLocal))]
public void BadKeepAlive2()
{
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, "/shared /keepalive:goo", _tempDirectory, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("Argument to '/keepalive' option is not a 32-bit integer.", result.Output.Trim());
}
[WorkItem(25777, "https://github.com/dotnet/roslyn/issues/25777")]
[ConditionalFact(typeof(DesktopOnly), typeof(IsEnglishLocal))]
public void BadKeepAlive3()
{
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, "/shared /keepalive:-100", _tempDirectory, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("Arguments to '/keepalive' option below -1 are invalid.", result.Output.Trim());
}
[WorkItem(25777, "https://github.com/dotnet/roslyn/issues/25777")]
[ConditionalFact(typeof(DesktopOnly), typeof(IsEnglishLocal))]
public void BadKeepAlive4()
{
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, "/shared /keepalive:9999999999", _tempDirectory, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("Argument to '/keepalive' option is not a 32-bit integer.", result.Output.Trim());
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(1024619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024619")]
public async Task Bug1024619_01()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("").Path;
_tempDirectory.CreateDirectory("Temp");
var tmp = Path.Combine(_tempDirectory.Path, "Temp");
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /t:library {srcFile}",
_tempDirectory,
additionalEnvironmentVars: new Dictionary<string, string> { { "TMP", tmp } });
Assert.Equal(0, result.ExitCode);
Directory.Delete(tmp);
result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/nologo /t:library {srcFile}",
_tempDirectory,
shouldRunOnServer: false);
Assert.Equal("", result.Output.Trim());
Assert.Equal(0, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[WorkItem(1024619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024619")]
public async Task Bug1024619_02()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText("").Path;
_tempDirectory.CreateDirectory("Temp");
var tmp = Path.Combine(_tempDirectory.Path, "Temp");
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /vbruntime* /nologo /t:library {srcFile}",
_tempDirectory,
additionalEnvironmentVars: new Dictionary<string, string> { { "TMP", tmp } });
Assert.Equal("", result.Output.Trim());
Assert.Equal(0, result.ExitCode);
Directory.Delete(tmp);
result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /t:library {srcFile}",
_tempDirectory);
Assert.Equal("", result.Output.Trim());
Assert.Equal(0, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(2, listener.CompletionDataList.Count);
}
[WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")]
[ConditionalFact(typeof(DesktopOnly))]
public void MissingCompilerAssembly_CompilerServer()
{
var basePath = Path.GetDirectoryName(typeof(CompilerServerUnitTests).Assembly.Location);
var compilerServerExecutable = Path.Combine(basePath, "VBCSCompiler.exe");
var dir = Temp.CreateDirectory();
var workingDirectory = dir.Path;
var serverExe = dir.CopyFile(compilerServerExecutable).Path;
dir.CopyFile(typeof(System.Collections.Immutable.ImmutableArray).Assembly.Location);
// Missing Microsoft.CodeAnalysis.dll launching server.
var result = ProcessUtilities.Run(serverExe, arguments: $"-pipename:{GetUniqueName()}", workingDirectory: workingDirectory);
Assert.Equal(1, result.ExitCode);
// Exception is logged rather than written to output/error streams.
Assert.Equal("", result.Output.Trim());
}
[WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")]
[WorkItem(19213, "https://github.com/dotnet/roslyn/issues/19213")]
[Fact(Skip = "19213")]
public async Task MissingCompilerAssembly_CompilerServerHost()
{
var host = new TestableCompilerServerHost((request, cancellationToken) =>
{
throw new FileNotFoundException();
});
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: host);
var request = new BuildRequest(RequestLanguage.CSharpCompile, string.Empty, new BuildRequest.Argument[0]);
var compileTask = serverData.SendAsync(request);
var response = await compileTask;
Assert.Equal(BuildResponse.ResponseType.Completed, response.Type);
Assert.Equal(0, ((CompletedBuildResponse)response).ReturnCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
/// <summary>
/// Runs CompileAndGetBytes twice and compares the output.
/// </summary>
/// <param name="source"> The source of the program that will be compiled </param>
private async Task RunDeterministicTest(string source)
{
var flags = "/deterministic+ /nologo /t:library /pdb:none";
var (first, finalFlags1) = await CompileAndGetBytes(source, flags);
var (second, finalFlags2) = await CompileAndGetBytes(source, flags);
Assert.Equal(first.Length, second.Length);
for (int i = 0; i < first.Length; i++)
{
if (first[i] != second[i])
{
AssertEx.Fail($"Bytes were different at position { i } ({ first[i] } vs { second[i] }). Flags used were (\"{ finalFlags1 }\" vs \"{ finalFlags2 }\")");
}
}
}
[Fact]
public async Task DeterminismHelloWorld()
{
var source = @"using System;
class Hello
{
static void Main()
{
Console.WriteLine(""Hello, world."");
}
}";
await RunDeterministicTest(source);
}
[Fact]
public async Task DeterminismCallerInfo()
{
var source = @"using System;
class CallerInfo {
public static void DoProcessing()
{
TraceMessage(""Something happened."");
}
public static void TraceMessage(string message,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = """",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = """",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
System.Diagnostics.Trace.WriteLine(""message: "" + message);
System.Diagnostics.Trace.WriteLine(""member name: "" + memberName);
System.Diagnostics.Trace.WriteLine(""source file path: "" + sourceFilePath);
System.Diagnostics.Trace.WriteLine(""source line number: "" + sourceLineNumber);
}
static void Main() {
DoProcessing();
}
}";
await RunDeterministicTest(source);
}
[Fact]
public async Task DeterminismAnonType()
{
var source = @"using System;
class AnonType {
public static void Main() {
var person = new { firstName = ""john"", lastName = ""Smith"" };
var date = new { year = 2015, month = ""jan"", day = 5 };
var color = new { red = 255, green = 125, blue = 0 };
Console.WriteLine(person);
Console.WriteLine(date);
Console.WriteLine(color);
}
}";
await RunDeterministicTest(source);
}
[Fact]
public async Task DeterminismLineDirective()
{
var source = @"using System;
class CallerInfo {
public static void TraceMessage(string message,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = """",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = """",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
System.Diagnostics.Trace.WriteLine(""message: "" + message);
System.Diagnostics.Trace.WriteLine(""member name: "" + memberName);
System.Diagnostics.Trace.WriteLine(""source file path: "" + sourceFilePath);
System.Diagnostics.Trace.WriteLine(""source line number: "" + sourceLineNumber);
}
static void Main() {
TraceMessage(""from main"");
#line 10 ""coolFile.cs""
TraceMessage(""from the cool file"");
#line default
TraceMessage(""back in main"");
}
}";
await RunDeterministicTest(source);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Castle.Core.Resource;
using Microsoft.CodeAnalysis.CommandLine;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
public class CompilerServerUnitTests : TestBase
{
internal static readonly RequestLanguage CSharpCompilerClientExecutable = RequestLanguage.CSharpCompile;
internal static readonly RequestLanguage BasicCompilerClientExecutable = RequestLanguage.VisualBasicCompile;
internal static readonly UTF8Encoding UTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
private static readonly KeyValuePair<string, string>[] s_helloWorldSrcCs =
{
new KeyValuePair<string, string>("hello.cs",
@"using System;
using System.Diagnostics;
class Hello
{
static void Main()
{
var obj = new Process();
Console.WriteLine(""Hello, world."");
}
}")
};
private static readonly KeyValuePair<string, string>[] s_helloWorldSrcVb =
{
new KeyValuePair<string, string>("hello.vb",
@"Imports System
Imports System.Diagnostics
Module Module1
Sub Main()
Dim p As New Process()
Console.WriteLine(""Hello from VB"")
End Sub
End Module")
};
private readonly TempDirectory _tempDirectory;
private readonly ICompilerServerLogger _logger;
public CompilerServerUnitTests(ITestOutputHelper testOutputHelper)
{
_tempDirectory = Temp.CreateDirectory();
_logger = new XunitCompilerServerLogger(testOutputHelper);
}
#region Helpers
private static IEnumerable<KeyValuePair<string, string>> AddForLoggingEnvironmentVars(IEnumerable<KeyValuePair<string, string>> vars)
{
vars = vars ?? new KeyValuePair<string, string>[] { };
if (!vars.Where(kvp => kvp.Key == "RoslynCommandLineLogFile").Any())
{
var list = vars.ToList();
list.Add(new KeyValuePair<string, string>(
"RoslynCommandLineLogFile",
typeof(CompilerServerUnitTests).Assembly.Location + ".client-server.log"));
return list;
}
return vars;
}
private static void CheckForBadShared(List<string> arguments)
{
bool hasShared;
string keepAlive;
string errorMessage;
string pipeName;
List<string> parsedArgs;
if (CommandLineParser.TryParseClientArgs(
arguments,
out parsedArgs,
out hasShared,
out keepAlive,
out pipeName,
out errorMessage))
{
if (hasShared && string.IsNullOrEmpty(pipeName))
{
throw new InvalidOperationException("Must specify a pipe name in these suites to ensure we're not running out of proc servers");
}
}
}
private static void ReferenceNetstandardDllIfCoreClr(TempDirectory currentDirectory, List<string> arguments)
{
#if !NET472
var filePath = Path.Combine(currentDirectory.Path, "netstandard.dll");
File.WriteAllBytes(filePath, TestMetadata.ResourcesNetStandard20.netstandard);
arguments.Add("/nostdlib");
arguments.Add("/r:netstandard.dll");
#endif
}
private static void CreateFiles(TempDirectory currentDirectory, IEnumerable<KeyValuePair<string, string>> files)
{
if (files != null)
{
foreach (var pair in files)
{
TempFile file = currentDirectory.CreateFile(pair.Key);
file.WriteAllText(pair.Value);
}
}
}
private static T ApplyEnvironmentVariables<T>(
IEnumerable<KeyValuePair<string, string>> environmentVariables,
Func<T> func)
{
if (environmentVariables == null)
{
return func();
}
var resetVariables = new Dictionary<string, string>();
try
{
foreach (var variable in environmentVariables)
{
resetVariables.Add(variable.Key, Environment.GetEnvironmentVariable(variable.Key));
Environment.SetEnvironmentVariable(variable.Key, variable.Value);
}
return func();
}
finally
{
foreach (var variable in resetVariables)
{
Environment.SetEnvironmentVariable(variable.Key, variable.Value);
}
}
}
private static (T Result, string Output) UseTextWriter<T>(Encoding encoding, Func<TextWriter, T> func)
{
MemoryStream memoryStream;
TextWriter writer;
if (encoding == null)
{
memoryStream = null;
writer = new StringWriter();
}
else
{
memoryStream = new MemoryStream();
writer = new StreamWriter(memoryStream, encoding);
}
var result = func(writer);
writer.Flush();
if (memoryStream != null)
{
return (result, encoding.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
}
else
{
return (result, ((StringWriter)writer).ToString());
}
}
internal (int ExitCode, string Output) RunCommandLineCompiler(
RequestLanguage language,
string argumentsSingle,
TempDirectory currentDirectory,
IEnumerable<KeyValuePair<string, string>> filesInDirectory = null,
IEnumerable<KeyValuePair<string, string>> additionalEnvironmentVars = null,
Encoding redirectEncoding = null,
bool shouldRunOnServer = true)
{
var arguments = new List<string>(argumentsSingle.Split(' '));
// This is validating that localization to a specific locale works no matter what the locale of the
// machine running the tests are.
arguments.Add("/preferreduilang:en");
ReferenceNetstandardDllIfCoreClr(currentDirectory, arguments);
CheckForBadShared(arguments);
CreateFiles(currentDirectory, filesInDirectory);
// Create a client to run the build. Infinite timeout is used to account for the
// case where these tests are run under extreme load. In high load scenarios the
// client will correctly drop down to a local compilation if the server doesn't respond
// fast enough.
var client = ServerUtil.CreateBuildClient(language, _logger, timeoutOverride: Timeout.Infinite);
var sdkDir = ServerUtil.DefaultSdkDirectory;
var buildPaths = new BuildPaths(
clientDir: Path.GetDirectoryName(typeof(CommonCompiler).Assembly.Location),
workingDir: currentDirectory.Path,
sdkDir: sdkDir,
tempDir: BuildServerConnection.GetTempPath(currentDirectory.Path));
var (result, output) = UseTextWriter(redirectEncoding, writer => ApplyEnvironmentVariables(additionalEnvironmentVars, () => client.RunCompilation(arguments, buildPaths, writer)));
Assert.Equal(shouldRunOnServer, result.RanOnServer);
return (result.ExitCode, output);
}
/// <summary>
/// Compiles some source code and returns the bytes that were contained in the compiled DLL file.
///
/// Each time that this function is called, it will be compiled in a different directory.
///
/// The default flags are "/shared /deterministic+ /nologo /t:library".
/// </summary>
/// <param name="source"> The source code for the program that will be compiled </param>
/// <returns> An array of bytes that were read from the compiled DLL</returns>
private async Task<(byte[] assemblyBytes, string finalFlags)> CompileAndGetBytes(string source, string flags)
{
// Setup
var tempDir = Temp.CreateDirectory();
var srcFile = tempDir.CreateFile("test.cs").WriteAllText(source).Path;
var outFile = srcFile.Replace("test.cs", "test.dll");
try
{
string finalFlags = null;
using (var serverData = await ServerUtil.CreateServer(_logger))
{
finalFlags = $"{flags} /shared:{serverData.PipeName} /pathmap:{tempDir.Path}=/ /out:{outFile} {srcFile}";
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
finalFlags,
currentDirectory: tempDir);
if (result.ExitCode != 0)
{
AssertEx.Fail($"Deterministic compile failed \n stdout: { result.Output }");
}
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
var bytes = File.ReadAllBytes(outFile);
AssertEx.NotNull(bytes);
return (bytes, finalFlags);
}
finally
{
File.Delete(srcFile);
File.Delete(outFile);
}
}
private static DisposableFile GetResultFile(TempDirectory directory, string resultFileName)
{
return new DisposableFile(Path.Combine(directory.Path, resultFileName));
}
private static void RunCompilerOutput(TempFile file, string expectedOutput)
{
if (RuntimeHostInfo.IsDesktopRuntime)
{
var result = ProcessUtilities.Run(file.Path, "", Path.GetDirectoryName(file.Path));
Assert.Equal(expectedOutput.Trim(), result.Output.Trim());
}
}
private static void VerifyResult((int ExitCode, string Output) result)
{
AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output);
Assert.Equal(0, result.ExitCode);
}
private void VerifyResultAndOutput((int ExitCode, string Output) result, TempDirectory path, string expectedOutput)
{
using (var resultFile = GetResultFile(path, "hello.exe"))
{
VerifyResult(result);
RunCompilerOutput(resultFile, expectedOutput);
}
}
#endregion
[ConditionalFact(typeof(UnixLikeOnly))]
public async Task ServerFailsWithLongTempPathUnix()
{
var newTempDir = _tempDirectory.CreateDirectory(new string('a', 100 - _tempDirectory.Path.Length));
await ApplyEnvironmentVariables(
new[] { new KeyValuePair<string, string>("TMPDIR", newTempDir.Path) },
async () =>
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo hello.cs",
_tempDirectory,
s_helloWorldSrcCs,
shouldRunOnServer: true);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
});
}
[Fact]
public async Task FallbackToCsc()
{
// Verify csc will fall back to command line when server fails to process
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs, shouldRunOnServer: false);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task CscFallBackOutputNoUtf8()
{
// Verify csc will fall back to command line when server fails to process
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var files = new Dictionary<string, string> { { "hello.cs", "♕" } };
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, files, redirectEncoding: Encoding.ASCII, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("hello.cs(1,1): error CS1056: Unexpected character '?'", result.Output.Trim());
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task CscFallBackOutputUtf8()
{
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /utf8output /nologo /t:library {srcFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding,
shouldRunOnServer: false);
Assert.Equal("test.cs(1,1): error CS1056: Unexpected character '♕'".Trim(),
result.Output.Trim().Replace(srcFile, "test.cs"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task VbcFallbackNoUtf8()
{
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText("♕").Path;
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /vbruntime* /nologo test.vb",
_tempDirectory,
redirectEncoding: Encoding.ASCII,
shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal(@"test.vb(1) : error BC30037: Character is not valid.
?
~", result.Output.Trim().Replace(srcFile, "test.vb"));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task VbcFallbackUtf8()
{
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText("♕").Path;
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /vbruntime* /utf8output /nologo /t:library {srcFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding,
shouldRunOnServer: false);
Assert.Equal(@"test.vb(1) : error BC30037: Character is not valid.
♕
~", result.Output.Trim().Replace(srcFile, "test.vb"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
public async Task FallbackToVbc()
{
var testableCompilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); });
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: testableCompilerServerHost);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /vbruntime* hello.vb", _tempDirectory, s_helloWorldSrcVb, shouldRunOnServer: false);
VerifyResultAndOutput(result, _tempDirectory, "Hello from VB");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestError, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task HelloWorldCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task HelloWorldCSDashShared()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"-shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")]
public void CompilerBinariesAreNotX86()
{
var basePath = Path.GetDirectoryName(typeof(CompilerServerUnitTests).Assembly.Location);
var compilerServerExecutable = Path.Combine(basePath, "VBCSCompiler.exe");
Assert.NotEqual(ProcessorArchitecture.X86,
AssemblyName.GetAssemblyName(compilerServerExecutable).ProcessorArchitecture);
}
/// <summary>
/// This method tests that when a 64-bit compiler server loads a
/// 64-bit mscorlib with /platform:x86 enabled no warning about
/// emitting a reference to a 64-bit assembly is produced.
/// The test should pass on x86 or amd64, but can only fail on
/// amd64.
/// </summary>
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Platformx86MscorlibCsc()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var files = new Dictionary<string, string> { { "c.cs", "class C {}" } };
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /t:library /platform:x86 c.cs",
_tempDirectory,
files);
VerifyResult(result);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Platformx86MscorlibVbc()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var files = new Dictionary<string, string> { { "c.vb", "Class C\nEnd Class" } };
var result = RunCommandLineCompiler(BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /vbruntime* /nologo /t:library /platform:x86 c.vb",
_tempDirectory,
files);
VerifyResult(result);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[ConditionalFact(typeof(DesktopOnly))]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task ExtraMSCorLibCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /r:mscorlib.dll hello.cs",
_tempDirectory,
s_helloWorldSrcCs);
VerifyResultAndOutput(result, _tempDirectory, "Hello, world.");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task HelloWorldVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /vbruntime* hello.vb",
_tempDirectory,
s_helloWorldSrcVb);
VerifyResultAndOutput(result, _tempDirectory, "Hello from VB");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[ConditionalFact(typeof(DesktopOnly))]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task ExtraMSCorLibVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /r:mscorlib.dll /vbruntime* hello.vb",
_tempDirectory,
s_helloWorldSrcVb);
VerifyResultAndOutput(result, _tempDirectory, "Hello from VB");
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task CompileErrorsCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "hello.cs",
@"using System;
class Hello
{
static void Main()
{ Console.WriteLine(""Hello, world."") }
}"}};
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} hello.cs", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("hello.cs(5,42): error CS1002: ; expected", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "hello.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task CompileErrorsVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "hellovb.vb",
@"Imports System
Module Module1
Sub Main()
Console.WriteLine(""Hello from VB"")
End Sub
End Class"}};
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /vbruntime* hellovb.vb", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("hellovb.vb(3) : error BC30625: 'Module' statement must end with a matching 'End Module'.", result.Output, StringComparison.Ordinal);
Assert.Contains("hellovb.vb(7) : error BC30460: 'End Class' must be preceded by a matching 'Class'.", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "hello.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MissingFileErrorCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} missingfile.cs", _tempDirectory);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("error CS2001: Source file", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "missingfile.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MissingReferenceErrorCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /r:missing.dll hello.cs", _tempDirectory, s_helloWorldSrcCs);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("error CS0006: Metadata file", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "hello.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(546067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546067")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task InvalidMetadataFileErrorCS()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "Lib.cs", "public class C {}"},
{ "app.cs", "class Test { static void Main() {} }"},
};
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"/shared:{serverData.PipeName} /r:Lib.cs app.cs", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("error CS0009: Metadata file", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "app.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MissingFileErrorVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /vbruntime* missingfile.vb", _tempDirectory);
// Should output errors, but not create output file.
Assert.Contains("Copyright (C) Microsoft Corporation. All rights reserved.", result.Output, StringComparison.Ordinal);
Assert.Contains("error BC2001", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "missingfile.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact, WorkItem(761131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/761131")]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MissingReferenceErrorVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "hellovb.vb",
@"Imports System.Diagnostics
Module Module1
Sub Main()
Dim p As New Process()
Console.WriteLine(""Hello from VB"")
End Sub
End Module"}};
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /vbruntime* /r:missing.dll hellovb.vb", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("error BC2017: could not find library", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "hellovb.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(546067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546067")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task InvalidMetadataFileErrorVB()
{
using var serverData = await ServerUtil.CreateServer(_logger);
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "Lib.vb",
@"Class C
End Class" },
{ "app.vb",
@"Module M1
Sub Main()
End Sub
End Module"}};
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"/shared:{serverData.PipeName} /nologo /vbruntime* /r:Lib.vb app.vb", _tempDirectory, files);
// Should output errors, but not create output file.
Assert.Contains("error BC31519", result.Output, StringComparison.Ordinal);
Assert.Equal(1, result.ExitCode);
Assert.False(File.Exists(Path.Combine(_tempDirectory.Path, "app.exe")));
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/20345")]
[WorkItem(723280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/723280")]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task ReferenceCachingVB()
{
TempDirectory rootDirectory = _tempDirectory.CreateDirectory("ReferenceCachingVB");
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "src1.vb",
@"Imports System
Public Class Library
Public Shared Function GetString() As String
Return ""library1""
End Function
End Class
"}};
using (var serverData = await ServerUtil.CreateServer(_logger))
using (var tmpFile = GetResultFile(rootDirectory, "lib.dll"))
{
var result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"src1.vb /shared:{serverData.PipeName} /nologo /t:library /out:lib.dll", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
using (var hello1_file = GetResultFile(rootDirectory, "hello1.exe"))
{
// Create EXE "hello1.exe"
files = new Dictionary<string, string> {
{ "hello1.vb",
@"Imports System
Module Module1
Public Sub Main()
Console.WriteLine(""Hello1 from {0}"", Library.GetString())
End Sub
End Module
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"hello1.vb /shared:{serverData.PipeName} /nologo /vbruntime* /r:lib.dll /out:hello1.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello1.exe.
RunCompilerOutput(hello1_file, "Hello1 from library1");
using (var hello2_file = GetResultFile(rootDirectory, "hello2.exe"))
{
// Create EXE "hello2.exe" referencing same DLL
files = new Dictionary<string, string> {
{ "hello2.vb",
@"Imports System
Module Module1
Public Sub Main()
Console.WriteLine(""Hello2 from {0}"", Library.GetString())
End Sub
End Module
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"hello2.vb /shared:{serverData.PipeName} /nologo /vbruntime* /r:lib.dll /out:hello2.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello2.exe.
RunCompilerOutput(hello2_file, "Hello2 from library1");
// Change DLL "lib.dll" to something new.
files =
new Dictionary<string, string> {
{ "src2.vb",
@"Imports System
Public Class Library
Public Shared Function GetString() As String
Return ""library2""
End Function
Public Shared Function GetString2() As String
Return ""library3""
End Function
End Class
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"src2.vb /shared:{serverData.PipeName} /nologo /t:library /out:lib.dll", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
using (var hello3_file = GetResultFile(rootDirectory, "hello3.exe"))
{
// Create EXE "hello3.exe" referencing new DLL
files = new Dictionary<string, string> {
{ "hello3.vb",
@"Imports System
Module Module1
Public Sub Main()
Console.WriteLine(""Hello3 from {0}"", Library.GetString2())
End Sub
End Module
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"hello3.vb /shared:{serverData.PipeName} /nologo /vbruntime* /r:lib.dll /out:hello3.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello3.exe. Should work.
RunCompilerOutput(hello3_file, "Hello3 from library3");
// Run hello2.exe one more time. Should have different output than before from updated library.
RunCompilerOutput(hello2_file, "Hello2 from library2");
}
}
}
var listener = await serverData.Complete();
Assert.Equal(5, listener.CompletionDataList.Count);
Assert.All(listener.CompletionDataList, completionData => Assert.Equal(CompletionReason.RequestCompleted, completionData.Reason));
}
GC.KeepAlive(rootDirectory);
}
[ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/19763")]
[WorkItem(723280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/723280")]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task ReferenceCachingCS()
{
TempDirectory rootDirectory = _tempDirectory.CreateDirectory("ReferenceCachingCS");
using (var serverData = await ServerUtil.CreateServer(_logger))
using (var tmpFile = GetResultFile(rootDirectory, "lib.dll"))
{
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "src1.cs",
@"using System;
public class Library
{
public static string GetString()
{ return ""library1""; }
}"}};
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"src1.cs /shared:{serverData.PipeName} /nologo /t:library /out:lib.dll", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
using (var hello1_file = GetResultFile(rootDirectory, "hello1.exe"))
{
// Create EXE "hello1.exe"
files = new Dictionary<string, string> {
{ "hello1.cs",
@"using System;
class Hello
{
public static void Main()
{ Console.WriteLine(""Hello1 from {0}"", Library.GetString()); }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"hello1.cs /shared:{serverData.PipeName} /nologo /r:lib.dll /out:hello1.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello1.exe.
RunCompilerOutput(hello1_file, "Hello1 from library1");
using (var hello2_file = GetResultFile(rootDirectory, "hello2.exe"))
{
var hello2exe = Temp.AddFile(hello2_file);
// Create EXE "hello2.exe" referencing same DLL
files = new Dictionary<string, string> {
{ "hello2.cs",
@"using System;
class Hello
{
public static void Main()
{ Console.WriteLine(""Hello2 from {0}"", Library.GetString()); }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"hello2.cs /shared:{serverData.PipeName} /nologo /r:lib.dll /out:hello2.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello2.exe.
RunCompilerOutput(hello2exe, "Hello2 from library1");
// Change DLL "lib.dll" to something new.
files =
new Dictionary<string, string> {
{ "src2.cs",
@"using System;
public class Library
{
public static string GetString()
{ return ""library2""; }
public static string GetString2()
{ return ""library3""; }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"src2.cs /shared:{serverData.PipeName} /nologo /t:library /out:lib.dll", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
using (var hello3_file = GetResultFile(rootDirectory, "hello3.exe"))
{
// Create EXE "hello3.exe" referencing new DLL
files = new Dictionary<string, string> {
{ "hello3.cs",
@"using System;
class Hello
{
public static void Main()
{ Console.WriteLine(""Hello3 from {0}"", Library.GetString2()); }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"hello3.cs /shared:{serverData.PipeName} /nologo /r:lib.dll /out:hello3.exe", rootDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
// Run hello3.exe. Should work.
RunCompilerOutput(hello3_file, "Hello3 from library3");
// Run hello2.exe one more time. Should have different output than before from updated library.
RunCompilerOutput(hello2_file, "Hello2 from library2");
}
}
}
var listener = await serverData.Complete();
Assert.Equal(5, listener.CompletionDataList.Count);
Assert.All(listener.CompletionDataList, completionData => Assert.Equal(CompletionReason.RequestCompleted, completionData.Reason));
}
GC.KeepAlive(rootDirectory);
}
private Task<DisposableFile> RunCompilationAsync(RequestLanguage language, string pipeName, int i, TempDirectory compilationDir)
{
string sourceFile;
string exeFileName;
string prefix;
string sourceText;
string additionalArgument;
if (language == RequestLanguage.CSharpCompile)
{
exeFileName = $"hellocs{i}.exe";
prefix = "CS";
sourceFile = $"hello{i}.cs";
sourceText =
$@"using System;
class Hello
{{
public static void Main()
{{ Console.WriteLine(""{prefix} Hello number {i}""); }}
}}";
additionalArgument = "";
}
else
{
exeFileName = $"hellovb{i}.exe";
prefix = "VB";
sourceFile = $"hello{i}.vb";
sourceText =
$@"Imports System
Module Hello
Sub Main()
Console.WriteLine(""{prefix} Hello number {i}"")
End Sub
End Module";
additionalArgument = " /vbruntime*";
}
var arguments = $"/shared:{pipeName} /nologo {sourceFile} /out:{exeFileName}{additionalArgument}";
var filesInDirectory = new Dictionary<string, string>()
{
{ sourceFile, sourceText }
};
return Task.Run(() =>
{
var result = RunCommandLineCompiler(language, string.Join(" ", arguments), compilationDir, filesInDirectory: filesInDirectory);
Assert.Equal(0, result.ExitCode);
// Run the EXE and verify it prints the desired output.
var exeFile = GetResultFile(compilationDir, exeFileName);
RunCompilerOutput(exeFile, $"{prefix} Hello number {i}");
return exeFile;
});
}
[WorkItem(997372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997372")]
[WorkItem(761326, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/761326")]
[ConditionalFact(typeof(WindowsOnly))]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task MultipleSimultaneousCompiles()
{
using var serverData = await ServerUtil.CreateServer(_logger);
// Run this many compiles simultaneously in different directories.
const int numberOfCompiles = 20;
var tasks = new Task<DisposableFile>[numberOfCompiles];
for (int i = 0; i < numberOfCompiles; ++i)
{
var language = i % 2 == 0 ? RequestLanguage.CSharpCompile : RequestLanguage.VisualBasicCompile;
var compilationDir = Temp.CreateDirectory();
tasks[i] = RunCompilationAsync(language, serverData.PipeName, i, compilationDir);
}
await Task.WhenAll(tasks);
var listener = await serverData.Complete();
Assert.Equal(numberOfCompiles, listener.CompletionDataList.Count);
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task UseLibVariableCS()
{
var libDirectory = _tempDirectory.CreateDirectory("LibraryDir");
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "src1.cs",
@"
public class Library
{
public static string GetString()
{ return ""library1""; }
}"}};
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"src1.cs /shared:{serverData.PipeName} /nologo /t:library /out:" + Path.Combine(libDirectory.Path, "lib.dll"),
_tempDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
Temp.AddFile(GetResultFile(libDirectory, "lib.dll"));
// Create EXE "hello1.exe"
files = new Dictionary<string, string> {
{ "hello1.cs",
@"using System;
class Hello
{
public static void Main()
{ Console.WriteLine(""Hello1 from {0}"", Library.GetString()); }
}"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"hello1.cs /shared:{serverData.PipeName} /nologo /r:lib.dll /out:hello1.exe", _tempDirectory, files,
additionalEnvironmentVars: new Dictionary<string, string>() { { "LIB", libDirectory.Path } });
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
var resultFile = Temp.AddFile(GetResultFile(_tempDirectory, "hello1.exe"));
var listener = await serverData.Complete();
Assert.Equal(2, listener.CompletionDataList.Count);
}
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task UseLibVariableVB()
{
var libDirectory = _tempDirectory.CreateDirectory("LibraryDir");
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "src1.vb",
@"Imports System
Public Class Library
Public Shared Function GetString() As String
Return ""library1""
End Function
End Class
"}};
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(BasicCompilerClientExecutable,
$"src1.vb /shared:{serverData.PipeName} /vbruntime* /nologo /t:library /out:" + Path.Combine(libDirectory.Path, "lib.dll"),
_tempDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
Temp.AddFile(GetResultFile(libDirectory, "lib.dll"));
// Create EXE "hello1.exe"
files = new Dictionary<string, string> {
{ "hello1.vb",
@"Imports System
Module Module1
Public Sub Main()
Console.WriteLine(""Hello1 from {0}"", Library.GetString())
End Sub
End Module
"}};
result = RunCommandLineCompiler(BasicCompilerClientExecutable, $"hello1.vb /shared:{serverData.PipeName} /nologo /vbruntime* /r:lib.dll /out:hello1.exe", _tempDirectory, files,
additionalEnvironmentVars: new Dictionary<string, string>() { { "LIB", libDirectory.Path } });
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
var resultFile = Temp.AddFile(GetResultFile(_tempDirectory, "hello1.exe"));
var listener = await serverData.Complete();
Assert.Equal(2, listener.CompletionDataList.Count);
}
[WorkItem(545446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545446")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Utf8Output_WithRedirecting_Off_Shared()
{
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /t:library {srcFile}",
_tempDirectory,
redirectEncoding: Encoding.ASCII);
Assert.Equal("test.cs(1,1): error CS1056: Unexpected character '?'".Trim(),
result.Output.Trim());
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(545446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545446")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Utf8Output_WithRedirecting_Off_Share()
{
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText(@"♕").Path;
var tempOut = _tempDirectory.CreateFile("output.txt");
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /vbruntime* /t:library {srcFile}",
_tempDirectory,
redirectEncoding: Encoding.ASCII);
Assert.Equal(@"SRC.VB(1) : error BC30037: Character is not valid.
?
~
".Trim(),
result.Output.Trim().Replace(srcFile, "SRC.VB"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(545446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545446")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Utf8Output_WithRedirecting_On_Shared_CS()
{
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /utf8output /nologo /t:library {srcFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding);
Assert.Equal("test.cs(1,1): error CS1056: Unexpected character '♕'".Trim(),
result.Output.Trim());
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(545446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545446")]
[Fact]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task Utf8Output_WithRedirecting_On_Shared_VB()
{
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText(@"♕").Path;
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /utf8output /nologo /vbruntime* /t:library {srcFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding);
Assert.Equal(@"SRC.VB(1) : error BC30037: Character is not valid.
♕
~
".Trim(),
result.Output.Trim().Replace(srcFile, "SRC.VB"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(871477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/871477")]
[ConditionalFact(typeof(DesktopOnly))]
[Trait(Traits.Environment, Traits.Environments.VSProductInstall)]
public async Task AssemblyIdentityComparer1()
{
_tempDirectory.CreateFile("mscorlib20.dll").WriteAllBytes(TestMetadata.ResourcesNet20.mscorlib);
_tempDirectory.CreateFile("mscorlib40.dll").WriteAllBytes(TestMetadata.ResourcesNet40.mscorlib);
// Create DLL "lib.dll"
Dictionary<string, string> files =
new Dictionary<string, string> {
{ "ref_mscorlib2.cs",
@"public class C
{
public System.Exception GetException()
{
return new System.Exception();
}
}
"}};
using var serverData = await ServerUtil.CreateServer(_logger);
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"ref_mscorlib2.cs /shared:{serverData.PipeName} /nologo /nostdlib /noconfig /t:library /r:mscorlib20.dll",
_tempDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
Temp.AddFile(GetResultFile(_tempDirectory, "ref_mscorlib2.dll"));
// Create EXE "main.exe"
files = new Dictionary<string, string> {
{ "main.cs",
@"using System;
class Program
{
static void Main(string[] args)
{
var e = new C().GetException();
Console.WriteLine(e);
}
}
"}};
result = RunCommandLineCompiler(CSharpCompilerClientExecutable,
$"main.cs /shared:{serverData.PipeName} /nologo /nostdlib /noconfig /r:mscorlib40.dll /r:ref_mscorlib2.dll",
_tempDirectory, files);
Assert.Equal("", result.Output);
Assert.Equal(0, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(2, listener.CompletionDataList.Count);
}
[WorkItem(979588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/979588")]
[Fact]
public async Task Utf8OutputInRspFileCsc()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
var rspFile = _tempDirectory.CreateFile("temp.rsp").WriteAllText(
string.Format("/utf8output /nologo /t:library {0}", srcFile));
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /noconfig @{rspFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding);
Assert.Equal("test.cs(1,1): error CS1056: Unexpected character '♕'",
result.Output.Trim());
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(979588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/979588")]
[Fact]
public async Task Utf8OutputInRspFileVbc()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("♕").Path;
var rspFile = _tempDirectory.CreateFile("temp.rsp").WriteAllText(
string.Format("/utf8output /nologo /vbruntime* /t:library {0}", srcFile));
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /noconfig @{rspFile}",
_tempDirectory,
redirectEncoding: UTF8Encoding);
Assert.Equal(@"src.vb(1) : error BC30037: Character is not valid.
♕
~", result.Output.Trim().Replace(srcFile, "src.vb"));
Assert.Equal(1, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[WorkItem(25777, "https://github.com/dotnet/roslyn/issues/25777")]
[ConditionalFact(typeof(DesktopOnly), typeof(IsEnglishLocal))]
public void BadKeepAlive1()
{
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, "/shared /keepalive", _tempDirectory, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("Missing argument for '/keepalive' option.", result.Output.Trim());
}
[WorkItem(25777, "https://github.com/dotnet/roslyn/issues/25777")]
[ConditionalFact(typeof(DesktopOnly), typeof(IsEnglishLocal))]
public void BadKeepAlive2()
{
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, "/shared /keepalive:goo", _tempDirectory, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("Argument to '/keepalive' option is not a 32-bit integer.", result.Output.Trim());
}
[WorkItem(25777, "https://github.com/dotnet/roslyn/issues/25777")]
[ConditionalFact(typeof(DesktopOnly), typeof(IsEnglishLocal))]
public void BadKeepAlive3()
{
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, "/shared /keepalive:-100", _tempDirectory, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("Arguments to '/keepalive' option below -1 are invalid.", result.Output.Trim());
}
[WorkItem(25777, "https://github.com/dotnet/roslyn/issues/25777")]
[ConditionalFact(typeof(DesktopOnly), typeof(IsEnglishLocal))]
public void BadKeepAlive4()
{
var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, "/shared /keepalive:9999999999", _tempDirectory, shouldRunOnServer: false);
Assert.Equal(1, result.ExitCode);
Assert.Equal("Argument to '/keepalive' option is not a 32-bit integer.", result.Output.Trim());
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(1024619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024619")]
public async Task Bug1024619_01()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var srcFile = _tempDirectory.CreateFile("test.cs").WriteAllText("").Path;
_tempDirectory.CreateDirectory("Temp");
var tmp = Path.Combine(_tempDirectory.Path, "Temp");
var result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /t:library {srcFile}",
_tempDirectory,
additionalEnvironmentVars: new Dictionary<string, string> { { "TMP", tmp } });
Assert.Equal(0, result.ExitCode);
Directory.Delete(tmp);
result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/nologo /t:library {srcFile}",
_tempDirectory,
shouldRunOnServer: false);
Assert.Equal("", result.Output.Trim());
Assert.Equal(0, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
[Fact]
[WorkItem(1024619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024619")]
public async Task Bug1024619_02()
{
using var serverData = await ServerUtil.CreateServer(_logger);
var srcFile = _tempDirectory.CreateFile("test.vb").WriteAllText("").Path;
_tempDirectory.CreateDirectory("Temp");
var tmp = Path.Combine(_tempDirectory.Path, "Temp");
var result = RunCommandLineCompiler(
BasicCompilerClientExecutable,
$"/shared:{serverData.PipeName} /vbruntime* /nologo /t:library {srcFile}",
_tempDirectory,
additionalEnvironmentVars: new Dictionary<string, string> { { "TMP", tmp } });
Assert.Equal("", result.Output.Trim());
Assert.Equal(0, result.ExitCode);
Directory.Delete(tmp);
result = RunCommandLineCompiler(
CSharpCompilerClientExecutable,
$"/shared:{serverData.PipeName} /nologo /t:library {srcFile}",
_tempDirectory);
Assert.Equal("", result.Output.Trim());
Assert.Equal(0, result.ExitCode);
var listener = await serverData.Complete();
Assert.Equal(2, listener.CompletionDataList.Count);
}
[WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")]
[ConditionalFact(typeof(DesktopOnly))]
public void MissingCompilerAssembly_CompilerServer()
{
var basePath = Path.GetDirectoryName(typeof(CompilerServerUnitTests).Assembly.Location);
var compilerServerExecutable = Path.Combine(basePath, "VBCSCompiler.exe");
var dir = Temp.CreateDirectory();
var workingDirectory = dir.Path;
var serverExe = dir.CopyFile(compilerServerExecutable).Path;
dir.CopyFile(typeof(System.Collections.Immutable.ImmutableArray).Assembly.Location);
// Missing Microsoft.CodeAnalysis.dll launching server.
var result = ProcessUtilities.Run(serverExe, arguments: $"-pipename:{GetUniqueName()}", workingDirectory: workingDirectory);
Assert.Equal(1, result.ExitCode);
// Exception is logged rather than written to output/error streams.
Assert.Equal("", result.Output.Trim());
}
[WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")]
[WorkItem(19213, "https://github.com/dotnet/roslyn/issues/19213")]
[Fact(Skip = "19213")]
public async Task MissingCompilerAssembly_CompilerServerHost()
{
var host = new TestableCompilerServerHost((request, cancellationToken) =>
{
throw new FileNotFoundException();
});
using var serverData = await ServerUtil.CreateServer(_logger, compilerServerHost: host);
var request = new BuildRequest(RequestLanguage.CSharpCompile, string.Empty, new BuildRequest.Argument[0]);
var compileTask = serverData.SendAsync(request);
var response = await compileTask;
Assert.Equal(BuildResponse.ResponseType.Completed, response.Type);
Assert.Equal(0, ((CompletedBuildResponse)response).ReturnCode);
var listener = await serverData.Complete();
Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single());
}
/// <summary>
/// Runs CompileAndGetBytes twice and compares the output.
/// </summary>
/// <param name="source"> The source of the program that will be compiled </param>
private async Task RunDeterministicTest(string source)
{
var flags = "/deterministic+ /nologo /t:library /pdb:none";
var (first, finalFlags1) = await CompileAndGetBytes(source, flags);
var (second, finalFlags2) = await CompileAndGetBytes(source, flags);
Assert.Equal(first.Length, second.Length);
for (int i = 0; i < first.Length; i++)
{
if (first[i] != second[i])
{
AssertEx.Fail($"Bytes were different at position { i } ({ first[i] } vs { second[i] }). Flags used were (\"{ finalFlags1 }\" vs \"{ finalFlags2 }\")");
}
}
}
[Fact]
public async Task DeterminismHelloWorld()
{
var source = @"using System;
class Hello
{
static void Main()
{
Console.WriteLine(""Hello, world."");
}
}";
await RunDeterministicTest(source);
}
[Fact]
public async Task DeterminismCallerInfo()
{
var source = @"using System;
class CallerInfo {
public static void DoProcessing()
{
TraceMessage(""Something happened."");
}
public static void TraceMessage(string message,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = """",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = """",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
System.Diagnostics.Trace.WriteLine(""message: "" + message);
System.Diagnostics.Trace.WriteLine(""member name: "" + memberName);
System.Diagnostics.Trace.WriteLine(""source file path: "" + sourceFilePath);
System.Diagnostics.Trace.WriteLine(""source line number: "" + sourceLineNumber);
}
static void Main() {
DoProcessing();
}
}";
await RunDeterministicTest(source);
}
[Fact]
public async Task DeterminismAnonType()
{
var source = @"using System;
class AnonType {
public static void Main() {
var person = new { firstName = ""john"", lastName = ""Smith"" };
var date = new { year = 2015, month = ""jan"", day = 5 };
var color = new { red = 255, green = 125, blue = 0 };
Console.WriteLine(person);
Console.WriteLine(date);
Console.WriteLine(color);
}
}";
await RunDeterministicTest(source);
}
[Fact]
public async Task DeterminismLineDirective()
{
var source = @"using System;
class CallerInfo {
public static void TraceMessage(string message,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = """",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = """",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
System.Diagnostics.Trace.WriteLine(""message: "" + message);
System.Diagnostics.Trace.WriteLine(""member name: "" + memberName);
System.Diagnostics.Trace.WriteLine(""source file path: "" + sourceFilePath);
System.Diagnostics.Trace.WriteLine(""source line number: "" + sourceLineNumber);
}
static void Main() {
TraceMessage(""from main"");
#line 10 ""coolFile.cs""
TraceMessage(""from the cool file"");
#line default
TraceMessage(""back in main"");
}
}";
await RunDeterministicTest(source);
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./eng/common/templates/post-build/setup-maestro-vars.yml | parameters:
BARBuildId: ''
PromoteToChannelIds: ''
jobs:
- job: setupMaestroVars
displayName: Setup Maestro Vars
variables:
- template: common-variables.yml
pool:
vmImage: 'windows-2019'
steps:
- checkout: none
- ${{ if eq(coalesce(parameters.PromoteToChannelIds, 0), 0) }}:
- task: DownloadBuildArtifacts@0
displayName: Download Release Configs
inputs:
buildType: current
artifactName: ReleaseConfigs
checkDownloadedFiles: true
- task: PowerShell@2
name: setReleaseVars
displayName: Set Release Configs Vars
inputs:
targetType: inline
script: |
try {
if (!$Env:PromoteToMaestroChannels -or $Env:PromoteToMaestroChannels.Trim() -eq '') {
$Content = Get-Content $(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt
$BarId = $Content | Select -Index 0
$Channels = $Content | Select -Index 1
$IsStableBuild = $Content | Select -Index 2
$AzureDevOpsProject = $Env:System_TeamProject
$AzureDevOpsBuildDefinitionId = $Env:System_DefinitionId
$AzureDevOpsBuildId = $Env:Build_BuildId
}
else {
$buildApiEndpoint = "${Env:MaestroApiEndPoint}/api/builds/${Env:BARBuildId}?api-version=${Env:MaestroApiVersion}"
$apiHeaders = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]'
$apiHeaders.Add('Accept', 'application/json')
$apiHeaders.Add('Authorization',"Bearer ${Env:MAESTRO_API_TOKEN}")
$buildInfo = try { Invoke-WebRequest -Method Get -Uri $buildApiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" }
$BarId = $Env:BARBuildId
$Channels = $Env:PromoteToMaestroChannels -split ","
$Channels = $Channels -join "]["
$Channels = "[$Channels]"
$IsStableBuild = $buildInfo.stable
$AzureDevOpsProject = $buildInfo.azureDevOpsProject
$AzureDevOpsBuildDefinitionId = $buildInfo.azureDevOpsBuildDefinitionId
$AzureDevOpsBuildId = $buildInfo.azureDevOpsBuildId
}
Write-Host "##vso[task.setvariable variable=BARBuildId;isOutput=true]$BarId"
Write-Host "##vso[task.setvariable variable=TargetChannels;isOutput=true]$Channels"
Write-Host "##vso[task.setvariable variable=IsStableBuild;isOutput=true]$IsStableBuild"
Write-Host "##vso[task.setvariable variable=AzDOProjectName;isOutput=true]$AzureDevOpsProject"
Write-Host "##vso[task.setvariable variable=AzDOPipelineId;isOutput=true]$AzureDevOpsBuildDefinitionId"
Write-Host "##vso[task.setvariable variable=AzDOBuildId;isOutput=true]$AzureDevOpsBuildId"
}
catch {
Write-Host $_
Write-Host $_.Exception
Write-Host $_.ScriptStackTrace
exit 1
}
env:
MAESTRO_API_TOKEN: $(MaestroApiAccessToken)
BARBuildId: ${{ parameters.BARBuildId }}
PromoteToMaestroChannels: ${{ parameters.PromoteToChannelIds }}
| parameters:
BARBuildId: ''
PromoteToChannelIds: ''
jobs:
- job: setupMaestroVars
displayName: Setup Maestro Vars
variables:
- template: common-variables.yml
pool:
vmImage: 'windows-2019'
steps:
- checkout: none
- ${{ if eq(coalesce(parameters.PromoteToChannelIds, 0), 0) }}:
- task: DownloadBuildArtifacts@0
displayName: Download Release Configs
inputs:
buildType: current
artifactName: ReleaseConfigs
checkDownloadedFiles: true
- task: PowerShell@2
name: setReleaseVars
displayName: Set Release Configs Vars
inputs:
targetType: inline
script: |
try {
if (!$Env:PromoteToMaestroChannels -or $Env:PromoteToMaestroChannels.Trim() -eq '') {
$Content = Get-Content $(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt
$BarId = $Content | Select -Index 0
$Channels = $Content | Select -Index 1
$IsStableBuild = $Content | Select -Index 2
$AzureDevOpsProject = $Env:System_TeamProject
$AzureDevOpsBuildDefinitionId = $Env:System_DefinitionId
$AzureDevOpsBuildId = $Env:Build_BuildId
}
else {
$buildApiEndpoint = "${Env:MaestroApiEndPoint}/api/builds/${Env:BARBuildId}?api-version=${Env:MaestroApiVersion}"
$apiHeaders = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]'
$apiHeaders.Add('Accept', 'application/json')
$apiHeaders.Add('Authorization',"Bearer ${Env:MAESTRO_API_TOKEN}")
$buildInfo = try { Invoke-WebRequest -Method Get -Uri $buildApiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" }
$BarId = $Env:BARBuildId
$Channels = $Env:PromoteToMaestroChannels -split ","
$Channels = $Channels -join "]["
$Channels = "[$Channels]"
$IsStableBuild = $buildInfo.stable
$AzureDevOpsProject = $buildInfo.azureDevOpsProject
$AzureDevOpsBuildDefinitionId = $buildInfo.azureDevOpsBuildDefinitionId
$AzureDevOpsBuildId = $buildInfo.azureDevOpsBuildId
}
Write-Host "##vso[task.setvariable variable=BARBuildId;isOutput=true]$BarId"
Write-Host "##vso[task.setvariable variable=TargetChannels;isOutput=true]$Channels"
Write-Host "##vso[task.setvariable variable=IsStableBuild;isOutput=true]$IsStableBuild"
Write-Host "##vso[task.setvariable variable=AzDOProjectName;isOutput=true]$AzureDevOpsProject"
Write-Host "##vso[task.setvariable variable=AzDOPipelineId;isOutput=true]$AzureDevOpsBuildDefinitionId"
Write-Host "##vso[task.setvariable variable=AzDOBuildId;isOutput=true]$AzureDevOpsBuildId"
}
catch {
Write-Host $_
Write-Host $_.Exception
Write-Host $_.ScriptStackTrace
exit 1
}
env:
MAESTRO_API_TOKEN: $(MaestroApiAccessToken)
BARBuildId: ${{ parameters.BARBuildId }}
PromoteToMaestroChannels: ${{ parameters.PromoteToChannelIds }}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Workspaces/Core/Portable/FindSymbols/StreamingProgressCollector.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.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
/// <summary>
/// Collects all the <see cref="ISymbol"/> definitions and <see cref="ReferenceLocation"/>
/// references that are reported independently and packages them up into the final list
/// of <see cref="ReferencedSymbol" />. This is used by the old non-streaming Find-References
/// APIs to return all the results at the end of the operation, as opposed to broadcasting
/// the results as they are found.
/// </summary>
internal class StreamingProgressCollector : IStreamingFindReferencesProgress
{
private readonly object _gate = new();
private readonly IStreamingFindReferencesProgress _underlyingProgress;
private readonly Dictionary<ISymbol, List<ReferenceLocation>> _symbolToLocations =
new();
public IStreamingProgressTracker ProgressTracker => _underlyingProgress.ProgressTracker;
public StreamingProgressCollector()
: this(NoOpStreamingFindReferencesProgress.Instance)
{
}
public StreamingProgressCollector(
IStreamingFindReferencesProgress underlyingProgress)
{
_underlyingProgress = underlyingProgress;
}
public ImmutableArray<ReferencedSymbol> GetReferencedSymbols()
{
lock (_gate)
{
using var _ = ArrayBuilder<ReferencedSymbol>.GetInstance(out var result);
foreach (var (symbol, locations) in _symbolToLocations)
result.Add(new ReferencedSymbol(symbol, locations.ToImmutableArray()));
return result.ToImmutable();
}
}
public ValueTask OnStartedAsync(CancellationToken cancellationToken) => _underlyingProgress.OnStartedAsync(cancellationToken);
public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => _underlyingProgress.OnCompletedAsync(cancellationToken);
public ValueTask OnFindInDocumentCompletedAsync(Document document, CancellationToken cancellationToken) => _underlyingProgress.OnFindInDocumentCompletedAsync(document, cancellationToken);
public ValueTask OnFindInDocumentStartedAsync(Document document, CancellationToken cancellationToken) => _underlyingProgress.OnFindInDocumentStartedAsync(document, cancellationToken);
public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken)
{
lock (_gate)
{
foreach (var definition in group.Symbols)
_symbolToLocations[definition] = new List<ReferenceLocation>();
}
return _underlyingProgress.OnDefinitionFoundAsync(group, cancellationToken);
}
public ValueTask OnReferenceFoundAsync(SymbolGroup group, ISymbol definition, ReferenceLocation location, CancellationToken cancellationToken)
{
lock (_gate)
{
_symbolToLocations[definition].Add(location);
}
return _underlyingProgress.OnReferenceFoundAsync(group, definition, location, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
/// <summary>
/// Collects all the <see cref="ISymbol"/> definitions and <see cref="ReferenceLocation"/>
/// references that are reported independently and packages them up into the final list
/// of <see cref="ReferencedSymbol" />. This is used by the old non-streaming Find-References
/// APIs to return all the results at the end of the operation, as opposed to broadcasting
/// the results as they are found.
/// </summary>
internal class StreamingProgressCollector : IStreamingFindReferencesProgress
{
private readonly object _gate = new();
private readonly IStreamingFindReferencesProgress _underlyingProgress;
private readonly Dictionary<ISymbol, List<ReferenceLocation>> _symbolToLocations =
new();
public IStreamingProgressTracker ProgressTracker => _underlyingProgress.ProgressTracker;
public StreamingProgressCollector()
: this(NoOpStreamingFindReferencesProgress.Instance)
{
}
public StreamingProgressCollector(
IStreamingFindReferencesProgress underlyingProgress)
{
_underlyingProgress = underlyingProgress;
}
public ImmutableArray<ReferencedSymbol> GetReferencedSymbols()
{
lock (_gate)
{
using var _ = ArrayBuilder<ReferencedSymbol>.GetInstance(out var result);
foreach (var (symbol, locations) in _symbolToLocations)
result.Add(new ReferencedSymbol(symbol, locations.ToImmutableArray()));
return result.ToImmutable();
}
}
public ValueTask OnStartedAsync(CancellationToken cancellationToken) => _underlyingProgress.OnStartedAsync(cancellationToken);
public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => _underlyingProgress.OnCompletedAsync(cancellationToken);
public ValueTask OnFindInDocumentCompletedAsync(Document document, CancellationToken cancellationToken) => _underlyingProgress.OnFindInDocumentCompletedAsync(document, cancellationToken);
public ValueTask OnFindInDocumentStartedAsync(Document document, CancellationToken cancellationToken) => _underlyingProgress.OnFindInDocumentStartedAsync(document, cancellationToken);
public ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken)
{
lock (_gate)
{
foreach (var definition in group.Symbols)
_symbolToLocations[definition] = new List<ReferenceLocation>();
}
return _underlyingProgress.OnDefinitionFoundAsync(group, cancellationToken);
}
public ValueTask OnReferenceFoundAsync(SymbolGroup group, ISymbol definition, ReferenceLocation location, CancellationToken cancellationToken)
{
lock (_gate)
{
_symbolToLocations[definition].Add(location);
}
return _underlyingProgress.OnReferenceFoundAsync(group, definition, location, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/PreviewChangesDialog_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 System;
using System.Threading;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
public class PreviewChangesDialog_OutOfProc : OutOfProcComponent
{
public PreviewChangesDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance)
{
}
/// <summary>
/// Verifies that the Preview Changes dialog is showing with the
/// specified title. The dialog does not have an AutomationId and the
/// title can be changed by features, so callers of this method must
/// specify a title.
/// </summary>
/// <param name="expectedTitle"></param>
public void VerifyOpen(string expectedTitle, TimeSpan? timeout = null)
{
using (var cancellationTokenSource = timeout != null ? new CancellationTokenSource(timeout.Value) : null)
{
var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None;
DialogHelpers.FindDialogByName(GetMainWindowHWnd(), expectedTitle, isOpen: true, cancellationToken);
// Wait for application idle to ensure the dialog is fully initialized
VisualStudioInstance.WaitForApplicationIdle(cancellationToken);
}
}
public void VerifyClosed(string expectedTitle)
=> DialogHelpers.FindDialogByName(GetMainWindowHWnd(), expectedTitle, isOpen: false, CancellationToken.None);
public void ClickApplyAndWaitForFeature(string expectedTitle, string featureName)
{
DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), expectedTitle, "Apply");
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, featureName);
}
public void ClickCancel(string expectedTitle)
=> DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), expectedTitle, "Cancel");
private IntPtr GetMainWindowHWnd()
=> VisualStudioInstance.Shell.GetHWnd();
}
}
| // Licensed to the .NET Foundation under one or more 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.Threading;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
public class PreviewChangesDialog_OutOfProc : OutOfProcComponent
{
public PreviewChangesDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance)
{
}
/// <summary>
/// Verifies that the Preview Changes dialog is showing with the
/// specified title. The dialog does not have an AutomationId and the
/// title can be changed by features, so callers of this method must
/// specify a title.
/// </summary>
/// <param name="expectedTitle"></param>
public void VerifyOpen(string expectedTitle, TimeSpan? timeout = null)
{
using (var cancellationTokenSource = timeout != null ? new CancellationTokenSource(timeout.Value) : null)
{
var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None;
DialogHelpers.FindDialogByName(GetMainWindowHWnd(), expectedTitle, isOpen: true, cancellationToken);
// Wait for application idle to ensure the dialog is fully initialized
VisualStudioInstance.WaitForApplicationIdle(cancellationToken);
}
}
public void VerifyClosed(string expectedTitle)
=> DialogHelpers.FindDialogByName(GetMainWindowHWnd(), expectedTitle, isOpen: false, CancellationToken.None);
public void ClickApplyAndWaitForFeature(string expectedTitle, string featureName)
{
DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), expectedTitle, "Apply");
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, featureName);
}
public void ClickCancel(string expectedTitle)
=> DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), expectedTitle, "Cancel");
private IntPtr GetMainWindowHWnd()
=> VisualStudioInstance.Shell.GetHWnd();
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Compilers/Test/Utilities/VisualBasic/BasicTrackingDiagnosticAnalyzer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Text.RegularExpressions
Imports Microsoft.CodeAnalysis.Test.Utilities
Public Class BasicTrackingDiagnosticAnalyzer
Inherits TrackingDiagnosticAnalyzer(Of SyntaxKind)
Private Shared ReadOnly s_omittedSyntaxKindRegex As Regex = New Regex(
"End|Exit|Empty|Imports|Option|Module|Sub|Function|Inherits|Implements|Handles|Argument|Yield|NameColonEquals|" &
"Print|With|Label|Stop|Continue|Resume|SingleLine|Error|Clause|Forever|Re[Dd]im|Mid|Type|Cast|Exponentiate|Erase|Date|Concatenate|Like|Divide|UnaryPlus")
Protected Overrides Function IsOnCodeBlockSupported(symbolKind As SymbolKind, methodKind As MethodKind, returnsVoid As Boolean) As Boolean
Return MyBase.IsOnCodeBlockSupported(symbolKind, methodKind, returnsVoid) AndAlso
methodKind <> MethodKind.Destructor AndAlso
methodKind <> MethodKind.ExplicitInterfaceImplementation
End Function
Protected Overrides Function IsAnalyzeNodeSupported(syntaxKind As SyntaxKind) As Boolean
Return MyBase.IsAnalyzeNodeSupported(syntaxKind) AndAlso Not s_omittedSyntaxKindRegex.IsMatch(syntaxKind.ToString())
End Function
End Class
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Text.RegularExpressions
Imports Microsoft.CodeAnalysis.Test.Utilities
Public Class BasicTrackingDiagnosticAnalyzer
Inherits TrackingDiagnosticAnalyzer(Of SyntaxKind)
Private Shared ReadOnly s_omittedSyntaxKindRegex As Regex = New Regex(
"End|Exit|Empty|Imports|Option|Module|Sub|Function|Inherits|Implements|Handles|Argument|Yield|NameColonEquals|" &
"Print|With|Label|Stop|Continue|Resume|SingleLine|Error|Clause|Forever|Re[Dd]im|Mid|Type|Cast|Exponentiate|Erase|Date|Concatenate|Like|Divide|UnaryPlus")
Protected Overrides Function IsOnCodeBlockSupported(symbolKind As SymbolKind, methodKind As MethodKind, returnsVoid As Boolean) As Boolean
Return MyBase.IsOnCodeBlockSupported(symbolKind, methodKind, returnsVoid) AndAlso
methodKind <> MethodKind.Destructor AndAlso
methodKind <> MethodKind.ExplicitInterfaceImplementation
End Function
Protected Overrides Function IsAnalyzeNodeSupported(syntaxKind As SyntaxKind) As Boolean
Return MyBase.IsAnalyzeNodeSupported(syntaxKind) AndAlso Not s_omittedSyntaxKindRegex.IsMatch(syntaxKind.ToString())
End Function
End Class
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/EditorFeatures/Test/AssemblyReferenceTests.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 Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
/// <summary>
/// VS for mac has some restrictions on the assemblies that they can load.
/// These tests are created to make sure we don't accidentally add references to the dlls that they cannot load.
/// </summary>
public class AssemblyReferenceTests
{
[Fact, WorkItem(26642, "https://github.com/dotnet/roslyn/issues/26642")]
public void TestNoReferenceToImageCatalog()
{
var editorsFeatureAssembly = typeof(Microsoft.CodeAnalysis.Editor.Shared.Extensions.GlyphExtensions).Assembly;
var dependencies = editorsFeatureAssembly.GetReferencedAssemblies();
Assert.Empty(dependencies.Where(a => a.FullName.Contains("Microsoft.VisualStudio.ImageCatalog")));
}
[Fact]
public void TestNoReferenceToImagingInterop()
{
var editorsFeatureAssembly = typeof(Microsoft.CodeAnalysis.Editor.Shared.Extensions.GlyphExtensions).Assembly;
var dependencies = editorsFeatureAssembly.GetReferencedAssemblies();
Assert.Empty(dependencies.Where(a => a.FullName.Contains("Microsoft.VisualStudio.Imaging.Interop")));
}
}
}
| // Licensed to the .NET Foundation under one or more 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 Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
/// <summary>
/// VS for mac has some restrictions on the assemblies that they can load.
/// These tests are created to make sure we don't accidentally add references to the dlls that they cannot load.
/// </summary>
public class AssemblyReferenceTests
{
[Fact, WorkItem(26642, "https://github.com/dotnet/roslyn/issues/26642")]
public void TestNoReferenceToImageCatalog()
{
var editorsFeatureAssembly = typeof(Microsoft.CodeAnalysis.Editor.Shared.Extensions.GlyphExtensions).Assembly;
var dependencies = editorsFeatureAssembly.GetReferencedAssemblies();
Assert.Empty(dependencies.Where(a => a.FullName.Contains("Microsoft.VisualStudio.ImageCatalog")));
}
[Fact]
public void TestNoReferenceToImagingInterop()
{
var editorsFeatureAssembly = typeof(Microsoft.CodeAnalysis.Editor.Shared.Extensions.GlyphExtensions).Assembly;
var dependencies = editorsFeatureAssembly.GetReferencedAssemblies();
Assert.Empty(dependencies.Where(a => a.FullName.Contains("Microsoft.VisualStudio.Imaging.Interop")));
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/VisualStudio/Core/Def/Storage/VisualStudioCloudCacheStorageService.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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.VisualStudio.RpcContracts.Caching;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.ServiceBroker;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Storage
{
internal class VisualStudioCloudCacheStorageService : AbstractCloudCachePersistentStorageService
{
private readonly IAsyncServiceProvider _serviceProvider;
private readonly IThreadingContext _threadingContext;
public VisualStudioCloudCacheStorageService(IAsyncServiceProvider serviceProvider, IThreadingContext threadingContext, IPersistentStorageLocationService locationService)
: base(locationService)
{
_serviceProvider = serviceProvider;
_threadingContext = threadingContext;
}
protected sealed override void DisposeCacheService(ICacheService cacheService)
{
if (cacheService is IAsyncDisposable asyncDisposable)
{
_threadingContext.JoinableTaskFactory.Run(
() => asyncDisposable.DisposeAsync().AsTask());
}
else if (cacheService is IDisposable disposable)
{
disposable.Dispose();
}
}
protected sealed override async ValueTask<ICacheService> CreateCacheServiceAsync(CancellationToken cancellationToken)
{
var serviceContainer = await _serviceProvider.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>().ConfigureAwait(false);
var serviceBroker = serviceContainer.GetFullAccessServiceBroker();
#pragma warning disable ISB001 // Dispose of proxies
// cache service will be disposed inside VisualStudioCloudCachePersistentStorage.Dispose
var cacheService = await serviceBroker.GetProxyAsync<ICacheService>(VisualStudioServices.VS2019_10.CacheService, cancellationToken: cancellationToken).ConfigureAwait(false);
#pragma warning restore ISB001 // Dispose of proxies
Contract.ThrowIfNull(cacheService);
return cacheService;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.VisualStudio.RpcContracts.Caching;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.ServiceBroker;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Storage
{
internal class VisualStudioCloudCacheStorageService : AbstractCloudCachePersistentStorageService
{
private readonly IAsyncServiceProvider _serviceProvider;
private readonly IThreadingContext _threadingContext;
public VisualStudioCloudCacheStorageService(IAsyncServiceProvider serviceProvider, IThreadingContext threadingContext, IPersistentStorageLocationService locationService)
: base(locationService)
{
_serviceProvider = serviceProvider;
_threadingContext = threadingContext;
}
protected sealed override void DisposeCacheService(ICacheService cacheService)
{
if (cacheService is IAsyncDisposable asyncDisposable)
{
_threadingContext.JoinableTaskFactory.Run(
() => asyncDisposable.DisposeAsync().AsTask());
}
else if (cacheService is IDisposable disposable)
{
disposable.Dispose();
}
}
protected sealed override async ValueTask<ICacheService> CreateCacheServiceAsync(CancellationToken cancellationToken)
{
var serviceContainer = await _serviceProvider.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>().ConfigureAwait(false);
var serviceBroker = serviceContainer.GetFullAccessServiceBroker();
#pragma warning disable ISB001 // Dispose of proxies
// cache service will be disposed inside VisualStudioCloudCachePersistentStorage.Dispose
var cacheService = await serviceBroker.GetProxyAsync<ICacheService>(VisualStudioServices.VS2019_10.CacheService, cancellationToken: cancellationToken).ConfigureAwait(false);
#pragma warning restore ISB001 // Dispose of proxies
Contract.ThrowIfNull(cacheService);
return cacheService;
}
}
}
| -1 |
dotnet/roslyn | 55,143 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression | Fixes: #54878
| akhera99 | 2021-07-27T19:18:23Z | 2021-07-27T22:17:46Z | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | fd1e0e1fb698991be846fb152528d3e53924fc99 | Introduce Parameter: Do not show code action if highlighted expression's parent is member access expression. Fixes: #54878
| ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/ThrowKeywordRecommender.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 "Throw" keyword for the statement context
''' </summary>
Friend Class ThrowKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Throw", VBFeaturesResources.Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsSingleLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Throw" keyword for the statement context
''' </summary>
Friend Class ThrowKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Throw", VBFeaturesResources.Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsSingleLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,138 | Avoid cancellation exceptions in intermediate operations | Addresses the following exceptions:

| sharwell | 2021-07-27T15:51:28Z | 2021-07-27T21:36:45Z | 3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2 | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions:

| ./src/Workspaces/Core/Portable/Serialization/SerializableSourceText.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Serialization
{
/// <summary>
/// Represents a <see cref="SourceText"/> which can be serialized for sending to another process. The text is not
/// required to be a live object in the current process, and can instead be held in temporary storage accessible by
/// both processes.
/// </summary>
internal sealed class SerializableSourceText
{
/// <summary>
/// The storage location for <see cref="SourceText"/>.
/// </summary>
/// <remarks>
/// Exactly one of <see cref="Storage"/> or <see cref="Text"/> will be non-<see langword="null"/>.
/// </remarks>
public ITemporaryTextStorageWithName? Storage { get; }
/// <summary>
/// The <see cref="SourceText"/> in the current process.
/// </summary>
/// <remarks>
/// <inheritdoc cref="Storage"/>
/// </remarks>
public SourceText? Text { get; }
public SerializableSourceText(ITemporaryTextStorageWithName storage)
: this(storage, text: null)
{
}
public SerializableSourceText(SourceText text)
: this(storage: null, text)
{
}
private SerializableSourceText(ITemporaryTextStorageWithName? storage, SourceText? text)
{
Debug.Assert(storage is null != text is null);
Storage = storage;
Text = text;
}
public ImmutableArray<byte> GetChecksum()
{
return Text?.GetChecksum() ?? Storage!.GetChecksum();
}
public async ValueTask<SourceText> GetTextAsync(CancellationToken cancellationToken)
{
if (Text is not null)
return Text;
return await Storage!.ReadTextAsync(cancellationToken).ConfigureAwait(false);
}
public static async ValueTask<SerializableSourceText> FromTextDocumentStateAsync(TextDocumentState state, CancellationToken cancellationToken)
{
if (state.Storage is ITemporaryTextStorageWithName storage)
{
return new SerializableSourceText(storage);
}
else
{
return new SerializableSourceText(await state.GetTextAsync(cancellationToken).ConfigureAwait(false));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Serialization
{
/// <summary>
/// Represents a <see cref="SourceText"/> which can be serialized for sending to another process. The text is not
/// required to be a live object in the current process, and can instead be held in temporary storage accessible by
/// both processes.
/// </summary>
internal sealed class SerializableSourceText
{
/// <summary>
/// The storage location for <see cref="SourceText"/>.
/// </summary>
/// <remarks>
/// Exactly one of <see cref="Storage"/> or <see cref="Text"/> will be non-<see langword="null"/>.
/// </remarks>
public ITemporaryTextStorageWithName? Storage { get; }
/// <summary>
/// The <see cref="SourceText"/> in the current process.
/// </summary>
/// <remarks>
/// <inheritdoc cref="Storage"/>
/// </remarks>
public SourceText? Text { get; }
public SerializableSourceText(ITemporaryTextStorageWithName storage)
: this(storage, text: null)
{
}
public SerializableSourceText(SourceText text)
: this(storage: null, text)
{
}
private SerializableSourceText(ITemporaryTextStorageWithName? storage, SourceText? text)
{
Debug.Assert(storage is null != text is null);
Storage = storage;
Text = text;
}
public ImmutableArray<byte> GetChecksum()
{
return Text?.GetChecksum() ?? Storage!.GetChecksum();
}
public async ValueTask<SourceText> GetTextAsync(CancellationToken cancellationToken)
{
if (Text is not null)
return Text;
return await Storage!.ReadTextAsync(cancellationToken).ConfigureAwait(false);
}
public static ValueTask<SerializableSourceText> FromTextDocumentStateAsync(TextDocumentState state, CancellationToken cancellationToken)
{
if (state.Storage is ITemporaryTextStorageWithName storage)
{
return new ValueTask<SerializableSourceText>(new SerializableSourceText(storage));
}
else
{
return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(
static (state, cancellationToken) => state.GetTextAsync(cancellationToken),
static (text, _) => new SerializableSourceText(text),
state,
cancellationToken);
}
}
}
}
| 1 |
dotnet/roslyn | 55,138 | Avoid cancellation exceptions in intermediate operations | Addresses the following exceptions:

| sharwell | 2021-07-27T15:51:28Z | 2021-07-27T21:36:45Z | 3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2 | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions:

| ./src/Workspaces/Core/Portable/Workspace/Solution/ProjectState_Checksum.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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class ProjectState
{
public bool TryGetStateChecksums(out ProjectStateChecksums stateChecksums)
=> _lazyChecksums.TryGetValue(out stateChecksums);
public Task<ProjectStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken)
=> _lazyChecksums.GetValueAsync(cancellationToken);
public async Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken)
{
var collection = await _lazyChecksums.GetValueAsync(cancellationToken).ConfigureAwait(false);
return collection.Checksum;
}
public Checksum GetParseOptionsChecksum()
=> GetParseOptionsChecksum(_solutionServices.Workspace.Services.GetService<ISerializerService>());
private Checksum GetParseOptionsChecksum(ISerializerService serializer)
=> this.SupportsCompilation
? ChecksumCache.GetOrCreate(this.ParseOptions, _ => serializer.CreateParseOptionsChecksum(this.ParseOptions))
: Checksum.Null;
private async Task<ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken))
{
var documentChecksumsTasks = DocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken);
var additionalDocumentChecksumTasks = AdditionalDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken);
var analyzerConfigDocumentChecksumTasks = AnalyzerConfigDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken);
var serializer = _solutionServices.Workspace.Services.GetService<ISerializerService>();
var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken);
// these compiler objects doesn't have good place to cache checksum. but rarely ever get changed.
var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null;
cancellationToken.ThrowIfCancellationRequested();
var parseOptionsChecksum = GetParseOptionsChecksum(serializer);
var projectReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(ProjectReferences, _ => new ChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
var metadataReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(MetadataReferences, _ => new ChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
var analyzerReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(AnalyzerReferences, _ => new ChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false);
var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false);
var analyzerConfigDocumentChecksums = await Task.WhenAll(analyzerConfigDocumentChecksumTasks).ConfigureAwait(false);
return new ProjectStateChecksums(
infoChecksum,
compilationOptionsChecksum,
parseOptionsChecksum,
documentChecksums: new ChecksumCollection(documentChecksums),
projectReferenceChecksums,
metadataReferenceChecksums,
analyzerReferenceChecksums,
additionalDocumentChecksums: new ChecksumCollection(additionalChecksums),
analyzerConfigDocumentChecksumCollection: new ChecksumCollection(analyzerConfigDocumentChecksums));
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class ProjectState
{
public bool TryGetStateChecksums(out ProjectStateChecksums stateChecksums)
=> _lazyChecksums.TryGetValue(out stateChecksums);
public Task<ProjectStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken)
=> _lazyChecksums.GetValueAsync(cancellationToken);
public Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken)
{
return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(
static (lazyChecksums, cancellationToken) => new ValueTask<ProjectStateChecksums>(lazyChecksums.GetValueAsync(cancellationToken)),
static (projectStateChecksums, _) => projectStateChecksums.Checksum,
_lazyChecksums,
cancellationToken).AsTask();
}
public Checksum GetParseOptionsChecksum()
=> GetParseOptionsChecksum(_solutionServices.Workspace.Services.GetService<ISerializerService>());
private Checksum GetParseOptionsChecksum(ISerializerService serializer)
=> this.SupportsCompilation
? ChecksumCache.GetOrCreate(this.ParseOptions, _ => serializer.CreateParseOptionsChecksum(this.ParseOptions))
: Checksum.Null;
private async Task<ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken))
{
var documentChecksumsTasks = DocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken);
var additionalDocumentChecksumTasks = AdditionalDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken);
var analyzerConfigDocumentChecksumTasks = AnalyzerConfigDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken);
var serializer = _solutionServices.Workspace.Services.GetService<ISerializerService>();
var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken);
// these compiler objects doesn't have good place to cache checksum. but rarely ever get changed.
var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null;
cancellationToken.ThrowIfCancellationRequested();
var parseOptionsChecksum = GetParseOptionsChecksum(serializer);
var projectReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(ProjectReferences, _ => new ChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
var metadataReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(MetadataReferences, _ => new ChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
var analyzerReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(AnalyzerReferences, _ => new ChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false);
var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false);
var analyzerConfigDocumentChecksums = await Task.WhenAll(analyzerConfigDocumentChecksumTasks).ConfigureAwait(false);
return new ProjectStateChecksums(
infoChecksum,
compilationOptionsChecksum,
parseOptionsChecksum,
documentChecksums: new ChecksumCollection(documentChecksums),
projectReferenceChecksums,
metadataReferenceChecksums,
analyzerReferenceChecksums,
additionalDocumentChecksums: new ChecksumCollection(additionalChecksums),
analyzerConfigDocumentChecksumCollection: new ChecksumCollection(analyzerConfigDocumentChecksums));
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
}
}
| 1 |
dotnet/roslyn | 55,138 | Avoid cancellation exceptions in intermediate operations | Addresses the following exceptions:

| sharwell | 2021-07-27T15:51:28Z | 2021-07-27T21:36:45Z | 3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2 | 719d4ffa2be734463e5d7d4d74b23b8006fd7727 | Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions:

| ./src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.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.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class TextDocumentState
{
protected readonly SolutionServices solutionServices;
/// <summary>
/// A direct reference to our source text. This is only kept around in specialized scenarios.
/// Specifically, we keep this around when a document is opened. By providing this we can allow
/// clients to easily get to the text of the document in a non-blocking fashion if that's all
/// that they need.
///
/// Note: this facility does not extend to getting the version as well. That's because the
/// version of a document depends on both the current source contents and the contents from
/// the previous version of the document. (i.e. if the contents are the same, then we will
/// preserve the same version, otherwise we'll move the version forward). Because determining
/// the version depends on comparing text, and because getting the old text may block, we
/// do not have the ability to know the version of the document up front, and instead can
/// only retrieve is asynchronously through <see cref="TextAndVersionSource"/>.
/// </summary>
protected readonly SourceText? sourceText;
protected ValueSource<TextAndVersion> TextAndVersionSource { get; }
// Checksums for this solution state
private readonly ValueSource<DocumentStateChecksums> _lazyChecksums;
public DocumentInfo.DocumentAttributes Attributes { get; }
/// <summary>
/// A <see cref="IDocumentServiceProvider"/> associated with this document
/// </summary>
public IDocumentServiceProvider Services { get; }
protected TextDocumentState(
SolutionServices solutionServices,
IDocumentServiceProvider? documentServiceProvider,
DocumentInfo.DocumentAttributes attributes,
SourceText? sourceText,
ValueSource<TextAndVersion> textAndVersionSource)
{
this.solutionServices = solutionServices;
this.sourceText = sourceText;
this.TextAndVersionSource = textAndVersionSource;
Attributes = attributes;
Services = documentServiceProvider ?? DefaultTextDocumentServiceProvider.Instance;
// This constructor is called whenever we're creating a new TextDocumentState from another
// TextDocumentState, and so we populate all the fields from the inputs. We will always create
// a new AsyncLazy to compute the checksum though, and that's because there's no practical way for
// the newly created TextDocumentState to have the same checksum as a previous TextDocumentState:
// if we're creating a new state, it's because something changed, and we'll have to create a new checksum.
_lazyChecksums = new AsyncLazy<DocumentStateChecksums>(ComputeChecksumsAsync, cacheResult: true);
}
public TextDocumentState(DocumentInfo info, SolutionServices services)
: this(services,
info.DocumentServiceProvider,
info.Attributes,
sourceText: null,
textAndVersionSource: info.TextLoader != null
? CreateRecoverableText(info.TextLoader, info.Id, services)
: CreateStrongText(TextAndVersion.Create(SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, info.FilePath)))
{
}
public DocumentId Id => Attributes.Id;
public string? FilePath => Attributes.FilePath;
public IReadOnlyList<string> Folders => Attributes.Folders;
public string Name => Attributes.Name;
protected static ValueSource<TextAndVersion> CreateStrongText(TextAndVersion text)
=> new ConstantValueSource<TextAndVersion>(text);
protected static ValueSource<TextAndVersion> CreateStrongText(TextLoader loader, DocumentId documentId, SolutionServices services)
{
return new AsyncLazy<TextAndVersion>(
asynchronousComputeFunction: cancellationToken => loader.LoadTextAsync(services.Workspace, documentId, cancellationToken),
synchronousComputeFunction: cancellationToken => loader.LoadTextSynchronously(services.Workspace, documentId, cancellationToken),
cacheResult: true);
}
protected static ValueSource<TextAndVersion> CreateRecoverableText(TextAndVersion text, SolutionServices services)
{
var result = new RecoverableTextAndVersion(CreateStrongText(text), services.TemporaryStorage);
// This RecoverableTextAndVersion is created directly from a TextAndVersion instance. In its initial state,
// the RecoverableTextAndVersion keeps a strong reference to the initial TextAndVersion, and only
// transitions to a weak reference backed by temporary storage after the first time GetValue (or
// GetValueAsync) is called. Since we know we are creating a RecoverableTextAndVersion for the purpose of
// avoiding problematic address space overhead, we call GetValue immediately to force the object to weakly
// hold its data from the start.
result.GetValue();
return result;
}
protected static ValueSource<TextAndVersion> CreateRecoverableText(TextLoader loader, DocumentId documentId, SolutionServices services)
{
return new RecoverableTextAndVersion(
new AsyncLazy<TextAndVersion>(
asynchronousComputeFunction: cancellationToken => loader.LoadTextAsync(services.Workspace, documentId, cancellationToken),
synchronousComputeFunction: cancellationToken => loader.LoadTextSynchronously(services.Workspace, documentId, cancellationToken),
cacheResult: false),
services.TemporaryStorage);
}
public ITemporaryTextStorage? Storage
{
get
{
var recoverableText = this.TextAndVersionSource as RecoverableTextAndVersion;
if (recoverableText == null)
{
return null;
}
return recoverableText.Storage;
}
}
public bool TryGetText([NotNullWhen(returnValue: true)] out SourceText? text)
{
if (this.sourceText != null)
{
text = sourceText;
return true;
}
if (this.TextAndVersionSource.TryGetValue(out var textAndVersion))
{
text = textAndVersion.Text;
return true;
}
else
{
text = null;
return false;
}
}
public bool TryGetTextVersion(out VersionStamp version)
{
// try fast path first
if (this.TextAndVersionSource is ITextVersionable versionable)
{
return versionable.TryGetTextVersion(out version);
}
if (this.TextAndVersionSource.TryGetValue(out var textAndVersion))
{
version = textAndVersion.Version;
return true;
}
else
{
version = default;
return false;
}
}
public bool TryGetTextAndVersion([NotNullWhen(true)] out TextAndVersion? textAndVersion)
=> TextAndVersionSource.TryGetValue(out textAndVersion);
public async ValueTask<SourceText> GetTextAsync(CancellationToken cancellationToken)
{
if (sourceText != null)
{
return sourceText;
}
if (TryGetText(out var text))
{
return text;
}
var textAndVersion = await GetTextAndVersionAsync(cancellationToken).ConfigureAwait(false);
return textAndVersion.Text;
}
public SourceText GetTextSynchronously(CancellationToken cancellationToken)
{
var textAndVersion = this.TextAndVersionSource.GetValue(cancellationToken);
return textAndVersion.Text;
}
public VersionStamp GetTextVersionSynchronously(CancellationToken cancellationToken)
{
var textAndVersion = this.TextAndVersionSource.GetValue(cancellationToken);
return textAndVersion.Version;
}
public async Task<VersionStamp> GetTextVersionAsync(CancellationToken cancellationToken)
{
// try fast path first
if (TryGetTextVersion(out var version))
{
return version;
}
var textAndVersion = await GetTextAndVersionAsync(cancellationToken).ConfigureAwait(false);
return textAndVersion.Version;
}
public TextDocumentState UpdateText(TextAndVersion newTextAndVersion, PreservationMode mode)
{
var newTextSource = mode == PreservationMode.PreserveIdentity
? CreateStrongText(newTextAndVersion)
: CreateRecoverableText(newTextAndVersion, this.solutionServices);
return UpdateText(newTextSource, mode, incremental: true);
}
public TextDocumentState UpdateText(SourceText newText, PreservationMode mode)
{
var newVersion = GetNewerVersion();
var newTextAndVersion = TextAndVersion.Create(newText, newVersion, FilePath);
return UpdateText(newTextAndVersion, mode);
}
public TextDocumentState UpdateText(TextLoader loader, PreservationMode mode)
{
// don't blow up on non-text documents.
var newTextSource = mode == PreservationMode.PreserveIdentity
? CreateStrongText(loader, Id, solutionServices)
: CreateRecoverableText(loader, Id, solutionServices);
return UpdateText(newTextSource, mode, incremental: false);
}
protected virtual TextDocumentState UpdateText(ValueSource<TextAndVersion> newTextSource, PreservationMode mode, bool incremental)
{
return new TextDocumentState(
this.solutionServices,
this.Services,
this.Attributes,
sourceText: null,
textAndVersionSource: newTextSource);
}
private async Task<TextAndVersion> GetTextAndVersionAsync(CancellationToken cancellationToken)
{
if (this.TextAndVersionSource.TryGetValue(out var textAndVersion))
{
return textAndVersion;
}
else
{
return await this.TextAndVersionSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
}
}
internal virtual async Task<Diagnostic?> GetLoadDiagnosticAsync(CancellationToken cancellationToken)
=> (await GetTextAndVersionAsync(cancellationToken).ConfigureAwait(false)).LoadDiagnostic;
private VersionStamp GetNewerVersion()
{
if (this.TextAndVersionSource.TryGetValue(out var textAndVersion))
{
return textAndVersion.Version.GetNewerVersion();
}
return VersionStamp.Create();
}
public virtual async Task<VersionStamp> GetTopLevelChangeTextVersionAsync(CancellationToken cancellationToken)
{
var textAndVersion = await this.TextAndVersionSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
return textAndVersion.Version;
}
/// <summary>
/// Only checks if the source of the text has changed, no content check is done.
/// </summary>
public bool HasTextChanged(TextDocumentState oldState, bool ignoreUnchangeableDocument)
{
if (ignoreUnchangeableDocument && !oldState.CanApplyChange())
{
return false;
}
return oldState.TextAndVersionSource != TextAndVersionSource;
}
public bool HasInfoChanged(TextDocumentState oldState)
=> oldState.Attributes != Attributes;
}
}
| // Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class TextDocumentState
{
protected readonly SolutionServices solutionServices;
/// <summary>
/// A direct reference to our source text. This is only kept around in specialized scenarios.
/// Specifically, we keep this around when a document is opened. By providing this we can allow
/// clients to easily get to the text of the document in a non-blocking fashion if that's all
/// that they need.
///
/// Note: this facility does not extend to getting the version as well. That's because the
/// version of a document depends on both the current source contents and the contents from
/// the previous version of the document. (i.e. if the contents are the same, then we will
/// preserve the same version, otherwise we'll move the version forward). Because determining
/// the version depends on comparing text, and because getting the old text may block, we
/// do not have the ability to know the version of the document up front, and instead can
/// only retrieve is asynchronously through <see cref="TextAndVersionSource"/>.
/// </summary>
protected readonly SourceText? sourceText;
protected ValueSource<TextAndVersion> TextAndVersionSource { get; }
// Checksums for this solution state
private readonly ValueSource<DocumentStateChecksums> _lazyChecksums;
public DocumentInfo.DocumentAttributes Attributes { get; }
/// <summary>
/// A <see cref="IDocumentServiceProvider"/> associated with this document
/// </summary>
public IDocumentServiceProvider Services { get; }
protected TextDocumentState(
SolutionServices solutionServices,
IDocumentServiceProvider? documentServiceProvider,
DocumentInfo.DocumentAttributes attributes,
SourceText? sourceText,
ValueSource<TextAndVersion> textAndVersionSource)
{
this.solutionServices = solutionServices;
this.sourceText = sourceText;
this.TextAndVersionSource = textAndVersionSource;
Attributes = attributes;
Services = documentServiceProvider ?? DefaultTextDocumentServiceProvider.Instance;
// This constructor is called whenever we're creating a new TextDocumentState from another
// TextDocumentState, and so we populate all the fields from the inputs. We will always create
// a new AsyncLazy to compute the checksum though, and that's because there's no practical way for
// the newly created TextDocumentState to have the same checksum as a previous TextDocumentState:
// if we're creating a new state, it's because something changed, and we'll have to create a new checksum.
_lazyChecksums = new AsyncLazy<DocumentStateChecksums>(ComputeChecksumsAsync, cacheResult: true);
}
public TextDocumentState(DocumentInfo info, SolutionServices services)
: this(services,
info.DocumentServiceProvider,
info.Attributes,
sourceText: null,
textAndVersionSource: info.TextLoader != null
? CreateRecoverableText(info.TextLoader, info.Id, services)
: CreateStrongText(TextAndVersion.Create(SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, info.FilePath)))
{
}
public DocumentId Id => Attributes.Id;
public string? FilePath => Attributes.FilePath;
public IReadOnlyList<string> Folders => Attributes.Folders;
public string Name => Attributes.Name;
protected static ValueSource<TextAndVersion> CreateStrongText(TextAndVersion text)
=> new ConstantValueSource<TextAndVersion>(text);
protected static ValueSource<TextAndVersion> CreateStrongText(TextLoader loader, DocumentId documentId, SolutionServices services)
{
return new AsyncLazy<TextAndVersion>(
asynchronousComputeFunction: cancellationToken => loader.LoadTextAsync(services.Workspace, documentId, cancellationToken),
synchronousComputeFunction: cancellationToken => loader.LoadTextSynchronously(services.Workspace, documentId, cancellationToken),
cacheResult: true);
}
protected static ValueSource<TextAndVersion> CreateRecoverableText(TextAndVersion text, SolutionServices services)
{
var result = new RecoverableTextAndVersion(CreateStrongText(text), services.TemporaryStorage);
// This RecoverableTextAndVersion is created directly from a TextAndVersion instance. In its initial state,
// the RecoverableTextAndVersion keeps a strong reference to the initial TextAndVersion, and only
// transitions to a weak reference backed by temporary storage after the first time GetValue (or
// GetValueAsync) is called. Since we know we are creating a RecoverableTextAndVersion for the purpose of
// avoiding problematic address space overhead, we call GetValue immediately to force the object to weakly
// hold its data from the start.
result.GetValue();
return result;
}
protected static ValueSource<TextAndVersion> CreateRecoverableText(TextLoader loader, DocumentId documentId, SolutionServices services)
{
return new RecoverableTextAndVersion(
new AsyncLazy<TextAndVersion>(
asynchronousComputeFunction: cancellationToken => loader.LoadTextAsync(services.Workspace, documentId, cancellationToken),
synchronousComputeFunction: cancellationToken => loader.LoadTextSynchronously(services.Workspace, documentId, cancellationToken),
cacheResult: false),
services.TemporaryStorage);
}
public ITemporaryTextStorage? Storage
{
get
{
var recoverableText = this.TextAndVersionSource as RecoverableTextAndVersion;
if (recoverableText == null)
{
return null;
}
return recoverableText.Storage;
}
}
public bool TryGetText([NotNullWhen(returnValue: true)] out SourceText? text)
{
if (this.sourceText != null)
{
text = sourceText;
return true;
}
if (this.TextAndVersionSource.TryGetValue(out var textAndVersion))
{
text = textAndVersion.Text;
return true;
}
else
{
text = null;
return false;
}
}
public bool TryGetTextVersion(out VersionStamp version)
{
// try fast path first
if (this.TextAndVersionSource is ITextVersionable versionable)
{
return versionable.TryGetTextVersion(out version);
}
if (this.TextAndVersionSource.TryGetValue(out var textAndVersion))
{
version = textAndVersion.Version;
return true;
}
else
{
version = default;
return false;
}
}
public bool TryGetTextAndVersion([NotNullWhen(true)] out TextAndVersion? textAndVersion)
=> TextAndVersionSource.TryGetValue(out textAndVersion);
public ValueTask<SourceText> GetTextAsync(CancellationToken cancellationToken)
{
if (sourceText != null)
{
return new ValueTask<SourceText>(sourceText);
}
if (TryGetText(out var text))
{
return new ValueTask<SourceText>(text);
}
return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(
static (self, cancellationToken) => self.GetTextAndVersionAsync(cancellationToken),
static (textAndVersion, _) => textAndVersion.Text,
this,
cancellationToken);
}
public SourceText GetTextSynchronously(CancellationToken cancellationToken)
{
var textAndVersion = this.TextAndVersionSource.GetValue(cancellationToken);
return textAndVersion.Text;
}
public VersionStamp GetTextVersionSynchronously(CancellationToken cancellationToken)
{
var textAndVersion = this.TextAndVersionSource.GetValue(cancellationToken);
return textAndVersion.Version;
}
public async Task<VersionStamp> GetTextVersionAsync(CancellationToken cancellationToken)
{
// try fast path first
if (TryGetTextVersion(out var version))
{
return version;
}
var textAndVersion = await GetTextAndVersionAsync(cancellationToken).ConfigureAwait(false);
return textAndVersion.Version;
}
public TextDocumentState UpdateText(TextAndVersion newTextAndVersion, PreservationMode mode)
{
var newTextSource = mode == PreservationMode.PreserveIdentity
? CreateStrongText(newTextAndVersion)
: CreateRecoverableText(newTextAndVersion, this.solutionServices);
return UpdateText(newTextSource, mode, incremental: true);
}
public TextDocumentState UpdateText(SourceText newText, PreservationMode mode)
{
var newVersion = GetNewerVersion();
var newTextAndVersion = TextAndVersion.Create(newText, newVersion, FilePath);
return UpdateText(newTextAndVersion, mode);
}
public TextDocumentState UpdateText(TextLoader loader, PreservationMode mode)
{
// don't blow up on non-text documents.
var newTextSource = mode == PreservationMode.PreserveIdentity
? CreateStrongText(loader, Id, solutionServices)
: CreateRecoverableText(loader, Id, solutionServices);
return UpdateText(newTextSource, mode, incremental: false);
}
protected virtual TextDocumentState UpdateText(ValueSource<TextAndVersion> newTextSource, PreservationMode mode, bool incremental)
{
return new TextDocumentState(
this.solutionServices,
this.Services,
this.Attributes,
sourceText: null,
textAndVersionSource: newTextSource);
}
private ValueTask<TextAndVersion> GetTextAndVersionAsync(CancellationToken cancellationToken)
{
if (this.TextAndVersionSource.TryGetValue(out var textAndVersion))
{
return new ValueTask<TextAndVersion>(textAndVersion);
}
else
{
return new ValueTask<TextAndVersion>(TextAndVersionSource.GetValueAsync(cancellationToken));
}
}
internal virtual async Task<Diagnostic?> GetLoadDiagnosticAsync(CancellationToken cancellationToken)
=> (await GetTextAndVersionAsync(cancellationToken).ConfigureAwait(false)).LoadDiagnostic;
private VersionStamp GetNewerVersion()
{
if (this.TextAndVersionSource.TryGetValue(out var textAndVersion))
{
return textAndVersion.Version.GetNewerVersion();
}
return VersionStamp.Create();
}
public virtual async Task<VersionStamp> GetTopLevelChangeTextVersionAsync(CancellationToken cancellationToken)
{
var textAndVersion = await this.TextAndVersionSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
return textAndVersion.Version;
}
/// <summary>
/// Only checks if the source of the text has changed, no content check is done.
/// </summary>
public bool HasTextChanged(TextDocumentState oldState, bool ignoreUnchangeableDocument)
{
if (ignoreUnchangeableDocument && !oldState.CanApplyChange())
{
return false;
}
return oldState.TextAndVersionSource != TextAndVersionSource;
}
public bool HasInfoChanged(TextDocumentState oldState)
=> oldState.Attributes != Attributes;
}
}
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.