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
unknown | date_merged
unknown | 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 | 56,545 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data. | Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| ./src/Analyzers/VisualBasic/Analyzers/SimplifyInterpolation/VisualBasicSimplifyInterpolationDiagnosticAnalyzer.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.Diagnostics
Imports Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SimplifyInterpolation
Imports Microsoft.CodeAnalysis.VisualBasic.EmbeddedLanguages.VirtualChars
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyInterpolation
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend Class VisualBasicSimplifyInterpolationDiagnosticAnalyzer
Inherits AbstractSimplifyInterpolationDiagnosticAnalyzer(Of InterpolationSyntax, ExpressionSyntax)
Protected Overrides Function GetHelpers() As AbstractSimplifyInterpolationHelpers
Return VisualBasicSimplifyInterpolationHelpers.Instance
End Function
Protected Overrides Function GetVirtualCharService() As IVirtualCharService
Return VisualBasicVirtualCharService.Instance
End Function
Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts
Return VisualBasicSyntaxFacts.Instance
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.Diagnostics
Imports Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SimplifyInterpolation
Imports Microsoft.CodeAnalysis.VisualBasic.EmbeddedLanguages.VirtualChars
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyInterpolation
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend Class VisualBasicSimplifyInterpolationDiagnosticAnalyzer
Inherits AbstractSimplifyInterpolationDiagnosticAnalyzer(Of InterpolationSyntax, ExpressionSyntax)
Protected Overrides Function GetHelpers() As AbstractSimplifyInterpolationHelpers
Return VisualBasicSimplifyInterpolationHelpers.Instance
End Function
Protected Overrides Function GetVirtualCharService() As IVirtualCharService
Return VisualBasicVirtualCharService.Instance
End Function
Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts
Return VisualBasicSyntaxFacts.Instance
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,545 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data. | Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.LanguageServices.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy
{
/// <summary>
/// Base type for legacy C# and VB project system shim implementations.
/// These legacy shims are based on legacy project system interfaces defined in csproj/msvbprj.
/// </summary>
internal abstract partial class AbstractLegacyProject : ForegroundThreadAffinitizedObject
{
public IVsHierarchy Hierarchy { get; }
protected VisualStudioProject VisualStudioProject { get; }
internal VisualStudioProjectOptionsProcessor VisualStudioProjectOptionsProcessor { get; set; }
protected IProjectCodeModel ProjectCodeModel { get; set; }
protected VisualStudioWorkspace Workspace { get; }
internal VisualStudioProject Test_VisualStudioProject => VisualStudioProject;
/// <summary>
/// The path to the directory of the project. Read-only, since although you can rename
/// a project in Visual Studio you can't change the folder of a project without an
/// unload/reload.
/// </summary>
private readonly string _projectDirectory = null;
/// <summary>
/// Whether we should ignore the output path for this project because it's a special project.
/// </summary>
private readonly bool _ignoreOutputPath;
private static readonly char[] PathSeparatorCharacters = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
#region Mutable fields that should only be used from the UI thread
private readonly SolutionEventsBatchScopeCreator _batchScopeCreator;
#endregion
public AbstractLegacyProject(
string projectSystemName,
IVsHierarchy hierarchy,
string language,
bool isVsIntellisenseProject,
IServiceProvider serviceProvider,
IThreadingContext threadingContext,
string externalErrorReportingPrefix)
: base(threadingContext, assertIsForeground: true)
{
Contract.ThrowIfNull(hierarchy);
var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
Workspace = componentModel.GetService<VisualStudioWorkspace>();
var workspaceImpl = (VisualStudioWorkspaceImpl)Workspace;
var projectFilePath = hierarchy.TryGetProjectFilePath();
if (projectFilePath != null && !File.Exists(projectFilePath))
{
projectFilePath = null;
}
if (projectFilePath != null)
{
_projectDirectory = Path.GetDirectoryName(projectFilePath);
}
if (isVsIntellisenseProject)
{
// IVsIntellisenseProjects are usually used for contained language cases, which means these projects don't have any real
// output path that we should consider. Since those point to the same IVsHierarchy as another project, we end up with two projects
// with the same output path, which potentially breaks conversion of metadata references to project references. However they're
// also used for database projects and a few other cases where there there isn't a "primary" IVsHierarchy.
// As a heuristic here we'll ignore the output path if we already have another project tied to the IVsHierarchy.
foreach (var projectId in Workspace.CurrentSolution.ProjectIds)
{
if (Workspace.GetHierarchy(projectId) == hierarchy)
{
_ignoreOutputPath = true;
break;
}
}
}
var projectFactory = componentModel.GetService<VisualStudioProjectFactory>();
VisualStudioProject = threadingContext.JoinableTaskFactory.Run(() => projectFactory.CreateAndAddToWorkspaceAsync(
projectSystemName,
language,
new VisualStudioProjectCreationInfo
{
// The workspace requires an assembly name so we can make compilations. We'll use
// projectSystemName because they'll have a better one eventually.
AssemblyName = projectSystemName,
FilePath = projectFilePath,
Hierarchy = hierarchy,
ProjectGuid = GetProjectIDGuid(hierarchy),
},
CancellationToken.None));
workspaceImpl.AddProjectRuleSetFileToInternalMaps(
VisualStudioProject,
() => VisualStudioProjectOptionsProcessor.EffectiveRuleSetFilePath);
// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
// by assigning the value of the project's root namespace to it. So various feature can choose to
// use it for their own purpose.
// In the future, we might consider officially exposing "default namespace" for VB project
// (e.g. through a <defaultnamespace> msbuild property)
VisualStudioProject.DefaultNamespace = GetRootNamespacePropertyValue(hierarchy);
if (TryGetPropertyValue(hierarchy, AdditionalPropertyNames.MaxSupportedLangVersion, out var maxLangVer))
{
VisualStudioProject.MaxLangVersion = maxLangVer;
}
if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzers, out var runAnayzers))
{
VisualStudioProject.RunAnalyzers = runAnayzers;
}
if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, out var runAnayzersDuringLiveAnalysis))
{
VisualStudioProject.RunAnalyzersDuringLiveAnalysis = runAnayzersDuringLiveAnalysis;
}
Hierarchy = hierarchy;
ConnectHierarchyEvents();
RefreshBinOutputPath();
workspaceImpl.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents();
_externalErrorReporter = new ProjectExternalErrorReporter(VisualStudioProject.Id, externalErrorReportingPrefix, language, workspaceImpl);
_batchScopeCreator = componentModel.GetService<SolutionEventsBatchScopeCreator>();
_batchScopeCreator.StartTrackingProject(VisualStudioProject, Hierarchy);
}
public string AssemblyName => VisualStudioProject.AssemblyName;
public string GetOutputFileName()
=> VisualStudioProject.CompilationOutputAssemblyFilePath;
public virtual void Disconnect()
{
_batchScopeCreator.StopTrackingProject(VisualStudioProject);
VisualStudioProjectOptionsProcessor?.Dispose();
ProjectCodeModel.OnProjectClosed();
VisualStudioProject.RemoveFromWorkspace();
// Unsubscribe IVsHierarchyEvents
DisconnectHierarchyEvents();
}
protected void AddFile(
string filename,
SourceCodeKind sourceCodeKind)
{
AssertIsForeground();
// We have tests that assert that XOML files should not get added; this was similar
// behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored
// them. XOML support is planned to go away for Dev16, but for now leave the logic there.
if (filename.EndsWith(".xoml"))
{
return;
}
ImmutableArray<string> folders = default;
var itemid = Hierarchy.TryGetItemId(filename);
if (itemid != VSConstants.VSITEMID_NIL)
{
folders = GetFolderNamesForDocument(itemid);
}
VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders);
}
protected void AddFile(
string filename,
string linkMetadata,
SourceCodeKind sourceCodeKind)
{
// We have tests that assert that XOML files should not get added; this was similar
// behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored
// them. XOML support is planned to go away for Dev16, but for now leave the logic there.
if (filename.EndsWith(".xoml"))
{
return;
}
var folders = ImmutableArray<string>.Empty;
if (!string.IsNullOrEmpty(linkMetadata))
{
var linkFolderPath = Path.GetDirectoryName(linkMetadata);
folders = linkFolderPath.Split(PathSeparatorCharacters, StringSplitOptions.RemoveEmptyEntries).ToImmutableArray();
}
else if (!string.IsNullOrEmpty(VisualStudioProject.FilePath))
{
var relativePath = PathUtilities.GetRelativePath(_projectDirectory, filename);
var relativePathParts = relativePath.Split(PathSeparatorCharacters);
folders = ImmutableArray.Create(relativePathParts, start: 0, length: relativePathParts.Length - 1);
}
VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders);
}
protected void RemoveFile(string filename)
{
// We have tests that assert that XOML files should not get added; this was similar
// behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored
// them. XOML support is planned to go away for Dev16, but for now leave the logic there.
if (filename.EndsWith(".xoml"))
{
return;
}
VisualStudioProject.RemoveSourceFile(filename);
ProjectCodeModel.OnSourceFileRemoved(filename);
}
protected void RefreshBinOutputPath()
{
// These projects are created against the same hierarchy as the "main" project that
// hosts the rest of the code; if we query the IVsHierarchy for the output path
// we'll end up with duplicate output paths which can break P2P referencing. Since the output
// path doesn't make sense for these, we'll ignore them.
if (_ignoreOutputPath)
{
return;
}
if (Hierarchy is not IVsBuildPropertyStorage storage)
{
return;
}
if (ErrorHandler.Failed(storage.GetPropertyValue("OutDir", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var outputDirectory)) ||
ErrorHandler.Failed(storage.GetPropertyValue("TargetFileName", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetFileName)))
{
return;
}
if (targetFileName == null)
{
return;
}
// web app case
if (!PathUtilities.IsAbsolute(outputDirectory))
{
if (VisualStudioProject.FilePath == null)
{
return;
}
outputDirectory = FileUtilities.ResolveRelativePath(outputDirectory, Path.GetDirectoryName(VisualStudioProject.FilePath));
}
if (outputDirectory == null)
{
return;
}
VisualStudioProject.OutputFilePath = FileUtilities.NormalizeAbsolutePath(Path.Combine(outputDirectory, targetFileName));
if (ErrorHandler.Succeeded(storage.GetPropertyValue("TargetRefPath", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetRefPath)) && !string.IsNullOrEmpty(targetRefPath))
{
VisualStudioProject.OutputRefFilePath = targetRefPath;
}
else
{
VisualStudioProject.OutputRefFilePath = null;
}
}
private static Guid GetProjectIDGuid(IVsHierarchy hierarchy)
{
if (hierarchy.TryGetGuidProperty(__VSHPROPID.VSHPROPID_ProjectIDGuid, out var guid))
{
return guid;
}
return Guid.Empty;
}
/// <summary>
/// Map of folder item IDs in the workspace to the string version of their path.
/// </summary>
/// <remarks>Using item IDs as a key like this in a long-lived way is considered unsupported by CPS and other
/// IVsHierarchy providers, but this code (which is fairly old) still makes the assumptions anyways.</remarks>
private readonly Dictionary<uint, ImmutableArray<string>> _folderNameMap = new();
private ImmutableArray<string> GetFolderNamesForDocument(uint documentItemID)
{
AssertIsForeground();
if (documentItemID != (uint)VSConstants.VSITEMID.Nil && Hierarchy.GetProperty(documentItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK)
{
var parentID = UnboxVSItemId(parentObj);
if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root))
{
return GetFolderNamesForFolder(parentID);
}
}
return ImmutableArray<string>.Empty;
}
private ImmutableArray<string> GetFolderNamesForFolder(uint folderItemID)
{
AssertIsForeground();
using var pooledObject = SharedPools.Default<List<string>>().GetPooledObject();
var newFolderNames = pooledObject.Object;
if (!_folderNameMap.TryGetValue(folderItemID, out var folderNames))
{
ComputeFolderNames(folderItemID, newFolderNames, Hierarchy);
folderNames = newFolderNames.ToImmutableArray();
_folderNameMap.Add(folderItemID, folderNames);
}
else
{
// verify names, and change map if we get a different set.
// this is necessary because we only get document adds/removes from the project system
// when a document name or folder name changes.
ComputeFolderNames(folderItemID, newFolderNames, Hierarchy);
if (!Enumerable.SequenceEqual(folderNames, newFolderNames))
{
folderNames = newFolderNames.ToImmutableArray();
_folderNameMap[folderItemID] = folderNames;
}
}
return folderNames;
}
// Different hierarchies are inconsistent on whether they return ints or uints for VSItemIds.
// Technically it should be a uint. However, there's no enforcement of this, and marshalling
// from native to managed can end up resulting in boxed ints instead. Handle both here so
// we're resilient to however the IVsHierarchy was actually implemented.
private static uint UnboxVSItemId(object id)
=> id is uint ? (uint)id : unchecked((uint)(int)id);
private static void ComputeFolderNames(uint folderItemID, List<string> names, IVsHierarchy hierarchy)
{
if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Name, out var nameObj) == VSConstants.S_OK)
{
// For 'Shared' projects, IVSHierarchy returns a hierarchy item with < character in its name (i.e. <SharedProjectName>)
// as a child of the root item. There is no such item in the 'visual' hierarchy in solution explorer and no such folder
// is present on disk either. Since this is not a real 'folder', we exclude it from the contents of Document.Folders.
// Note: The parent of the hierarchy item that contains < character in its name is VSITEMID.Root. So we don't need to
// worry about accidental propagation out of the Shared project to any containing 'Solution' folders - the check for
// VSITEMID.Root below already takes care of that.
var name = (string)nameObj;
if (!name.StartsWith("<", StringComparison.OrdinalIgnoreCase))
{
names.Insert(0, name);
}
}
if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK)
{
var parentID = UnboxVSItemId(parentObj);
if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root))
{
ComputeFolderNames(parentID, names, hierarchy);
}
}
}
/// <summary>
/// Get the value of "rootnamespace" property of the project ("" if not defined, which means global namespace),
/// or null if it is unknown or not applicable.
/// </summary>
/// <remarks>
/// This property has different meaning between C# and VB, each project type can decide how to interpret the value.
/// </remarks>>
private static string GetRootNamespacePropertyValue(IVsHierarchy hierarchy)
{
// While both csproj and vbproj might define <rootnamespace> property in the project file,
// they are very different things.
//
// In C#, it's called default namespace (even though we got the value from rootnamespace property),
// and it doesn't affect the semantic of the code in anyway, just something used by VS.
// For example, when you create a new class, the namespace for the new class is based on it.
// Therefore, we can't get this info from compiler.
//
// However, in VB, it's actually called root namespace, and that info is part of the VB compilation
// (parsed from arguments), because VB compiler needs it to determine the root of all the namespace
// declared in the compilation.
//
// Unfortunately, although being different concepts, default namespace and root namespace are almost
// used interchangeably in VS. For example, (1) the value is define in "rootnamespace" property in project
// files and, (2) the property name we use to call into hierarchy below to retrieve the value is
// called "DefaultNamespace".
if (hierarchy.TryGetProperty(__VSHPROPID.VSHPROPID_DefaultNamespace, out string value))
{
return value;
}
return null;
}
private static bool TryGetPropertyValue(IVsHierarchy hierarchy, string propertyName, out string propertyValue)
{
if (hierarchy is not IVsBuildPropertyStorage storage)
{
propertyValue = null;
return false;
}
return ErrorHandler.Succeeded(storage.GetPropertyValue(propertyName, null, (uint)_PersistStorageType.PST_PROJECT_FILE, out propertyValue));
}
private static bool TryGetBoolPropertyValue(IVsHierarchy hierarchy, string propertyName, out bool? propertyValue)
{
if (!TryGetPropertyValue(hierarchy, propertyName, out var stringPropertyValue))
{
propertyValue = null;
return false;
}
propertyValue = bool.TryParse(stringPropertyValue, out var parsedBoolValue) ? parsedBoolValue : (bool?)null;
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.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.LanguageServices.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy
{
/// <summary>
/// Base type for legacy C# and VB project system shim implementations.
/// These legacy shims are based on legacy project system interfaces defined in csproj/msvbprj.
/// </summary>
internal abstract partial class AbstractLegacyProject : ForegroundThreadAffinitizedObject
{
public IVsHierarchy Hierarchy { get; }
protected VisualStudioProject VisualStudioProject { get; }
internal VisualStudioProjectOptionsProcessor VisualStudioProjectOptionsProcessor { get; set; }
protected IProjectCodeModel ProjectCodeModel { get; set; }
protected VisualStudioWorkspace Workspace { get; }
internal VisualStudioProject Test_VisualStudioProject => VisualStudioProject;
/// <summary>
/// The path to the directory of the project. Read-only, since although you can rename
/// a project in Visual Studio you can't change the folder of a project without an
/// unload/reload.
/// </summary>
private readonly string _projectDirectory = null;
/// <summary>
/// Whether we should ignore the output path for this project because it's a special project.
/// </summary>
private readonly bool _ignoreOutputPath;
private static readonly char[] PathSeparatorCharacters = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
#region Mutable fields that should only be used from the UI thread
private readonly SolutionEventsBatchScopeCreator _batchScopeCreator;
#endregion
public AbstractLegacyProject(
string projectSystemName,
IVsHierarchy hierarchy,
string language,
bool isVsIntellisenseProject,
IServiceProvider serviceProvider,
IThreadingContext threadingContext,
string externalErrorReportingPrefix)
: base(threadingContext, assertIsForeground: true)
{
Contract.ThrowIfNull(hierarchy);
var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
Workspace = componentModel.GetService<VisualStudioWorkspace>();
var workspaceImpl = (VisualStudioWorkspaceImpl)Workspace;
var projectFilePath = hierarchy.TryGetProjectFilePath();
if (projectFilePath != null && !File.Exists(projectFilePath))
{
projectFilePath = null;
}
if (projectFilePath != null)
{
_projectDirectory = Path.GetDirectoryName(projectFilePath);
}
if (isVsIntellisenseProject)
{
// IVsIntellisenseProjects are usually used for contained language cases, which means these projects don't have any real
// output path that we should consider. Since those point to the same IVsHierarchy as another project, we end up with two projects
// with the same output path, which potentially breaks conversion of metadata references to project references. However they're
// also used for database projects and a few other cases where there there isn't a "primary" IVsHierarchy.
// As a heuristic here we'll ignore the output path if we already have another project tied to the IVsHierarchy.
foreach (var projectId in Workspace.CurrentSolution.ProjectIds)
{
if (Workspace.GetHierarchy(projectId) == hierarchy)
{
_ignoreOutputPath = true;
break;
}
}
}
var projectFactory = componentModel.GetService<VisualStudioProjectFactory>();
VisualStudioProject = threadingContext.JoinableTaskFactory.Run(() => projectFactory.CreateAndAddToWorkspaceAsync(
projectSystemName,
language,
new VisualStudioProjectCreationInfo
{
// The workspace requires an assembly name so we can make compilations. We'll use
// projectSystemName because they'll have a better one eventually.
AssemblyName = projectSystemName,
FilePath = projectFilePath,
Hierarchy = hierarchy,
ProjectGuid = GetProjectIDGuid(hierarchy),
},
CancellationToken.None));
workspaceImpl.AddProjectRuleSetFileToInternalMaps(
VisualStudioProject,
() => VisualStudioProjectOptionsProcessor.EffectiveRuleSetFilePath);
// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
// by assigning the value of the project's root namespace to it. So various feature can choose to
// use it for their own purpose.
// In the future, we might consider officially exposing "default namespace" for VB project
// (e.g. through a <defaultnamespace> msbuild property)
VisualStudioProject.DefaultNamespace = GetRootNamespacePropertyValue(hierarchy);
if (TryGetPropertyValue(hierarchy, AdditionalPropertyNames.MaxSupportedLangVersion, out var maxLangVer))
{
VisualStudioProject.MaxLangVersion = maxLangVer;
}
if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzers, out var runAnayzers))
{
VisualStudioProject.RunAnalyzers = runAnayzers;
}
if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, out var runAnayzersDuringLiveAnalysis))
{
VisualStudioProject.RunAnalyzersDuringLiveAnalysis = runAnayzersDuringLiveAnalysis;
}
Hierarchy = hierarchy;
ConnectHierarchyEvents();
RefreshBinOutputPath();
workspaceImpl.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents();
_externalErrorReporter = new ProjectExternalErrorReporter(VisualStudioProject.Id, externalErrorReportingPrefix, language, workspaceImpl);
_batchScopeCreator = componentModel.GetService<SolutionEventsBatchScopeCreator>();
_batchScopeCreator.StartTrackingProject(VisualStudioProject, Hierarchy);
}
public string AssemblyName => VisualStudioProject.AssemblyName;
public string GetOutputFileName()
=> VisualStudioProject.CompilationOutputAssemblyFilePath;
public virtual void Disconnect()
{
_batchScopeCreator.StopTrackingProject(VisualStudioProject);
VisualStudioProjectOptionsProcessor?.Dispose();
ProjectCodeModel.OnProjectClosed();
VisualStudioProject.RemoveFromWorkspace();
// Unsubscribe IVsHierarchyEvents
DisconnectHierarchyEvents();
}
protected void AddFile(
string filename,
SourceCodeKind sourceCodeKind)
{
AssertIsForeground();
// We have tests that assert that XOML files should not get added; this was similar
// behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored
// them. XOML support is planned to go away for Dev16, but for now leave the logic there.
if (filename.EndsWith(".xoml"))
{
return;
}
ImmutableArray<string> folders = default;
var itemid = Hierarchy.TryGetItemId(filename);
if (itemid != VSConstants.VSITEMID_NIL)
{
folders = GetFolderNamesForDocument(itemid);
}
VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders);
}
protected void AddFile(
string filename,
string linkMetadata,
SourceCodeKind sourceCodeKind)
{
// We have tests that assert that XOML files should not get added; this was similar
// behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored
// them. XOML support is planned to go away for Dev16, but for now leave the logic there.
if (filename.EndsWith(".xoml"))
{
return;
}
var folders = ImmutableArray<string>.Empty;
if (!string.IsNullOrEmpty(linkMetadata))
{
var linkFolderPath = Path.GetDirectoryName(linkMetadata);
folders = linkFolderPath.Split(PathSeparatorCharacters, StringSplitOptions.RemoveEmptyEntries).ToImmutableArray();
}
else if (!string.IsNullOrEmpty(VisualStudioProject.FilePath))
{
var relativePath = PathUtilities.GetRelativePath(_projectDirectory, filename);
var relativePathParts = relativePath.Split(PathSeparatorCharacters);
folders = ImmutableArray.Create(relativePathParts, start: 0, length: relativePathParts.Length - 1);
}
VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders);
}
protected void RemoveFile(string filename)
{
// We have tests that assert that XOML files should not get added; this was similar
// behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored
// them. XOML support is planned to go away for Dev16, but for now leave the logic there.
if (filename.EndsWith(".xoml"))
{
return;
}
VisualStudioProject.RemoveSourceFile(filename);
ProjectCodeModel.OnSourceFileRemoved(filename);
}
protected void RefreshBinOutputPath()
{
// These projects are created against the same hierarchy as the "main" project that
// hosts the rest of the code; if we query the IVsHierarchy for the output path
// we'll end up with duplicate output paths which can break P2P referencing. Since the output
// path doesn't make sense for these, we'll ignore them.
if (_ignoreOutputPath)
{
return;
}
if (Hierarchy is not IVsBuildPropertyStorage storage)
{
return;
}
if (ErrorHandler.Failed(storage.GetPropertyValue("OutDir", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var outputDirectory)) ||
ErrorHandler.Failed(storage.GetPropertyValue("TargetFileName", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetFileName)))
{
return;
}
if (targetFileName == null)
{
return;
}
// web app case
if (!PathUtilities.IsAbsolute(outputDirectory))
{
if (VisualStudioProject.FilePath == null)
{
return;
}
outputDirectory = FileUtilities.ResolveRelativePath(outputDirectory, Path.GetDirectoryName(VisualStudioProject.FilePath));
}
if (outputDirectory == null)
{
return;
}
VisualStudioProject.OutputFilePath = FileUtilities.NormalizeAbsolutePath(Path.Combine(outputDirectory, targetFileName));
if (ErrorHandler.Succeeded(storage.GetPropertyValue("TargetRefPath", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetRefPath)) && !string.IsNullOrEmpty(targetRefPath))
{
VisualStudioProject.OutputRefFilePath = targetRefPath;
}
else
{
VisualStudioProject.OutputRefFilePath = null;
}
}
private static Guid GetProjectIDGuid(IVsHierarchy hierarchy)
{
if (hierarchy.TryGetGuidProperty(__VSHPROPID.VSHPROPID_ProjectIDGuid, out var guid))
{
return guid;
}
return Guid.Empty;
}
/// <summary>
/// Map of folder item IDs in the workspace to the string version of their path.
/// </summary>
/// <remarks>Using item IDs as a key like this in a long-lived way is considered unsupported by CPS and other
/// IVsHierarchy providers, but this code (which is fairly old) still makes the assumptions anyways.</remarks>
private readonly Dictionary<uint, ImmutableArray<string>> _folderNameMap = new();
private ImmutableArray<string> GetFolderNamesForDocument(uint documentItemID)
{
AssertIsForeground();
if (documentItemID != (uint)VSConstants.VSITEMID.Nil && Hierarchy.GetProperty(documentItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK)
{
var parentID = UnboxVSItemId(parentObj);
if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root))
{
return GetFolderNamesForFolder(parentID);
}
}
return ImmutableArray<string>.Empty;
}
private ImmutableArray<string> GetFolderNamesForFolder(uint folderItemID)
{
AssertIsForeground();
using var pooledObject = SharedPools.Default<List<string>>().GetPooledObject();
var newFolderNames = pooledObject.Object;
if (!_folderNameMap.TryGetValue(folderItemID, out var folderNames))
{
ComputeFolderNames(folderItemID, newFolderNames, Hierarchy);
folderNames = newFolderNames.ToImmutableArray();
_folderNameMap.Add(folderItemID, folderNames);
}
else
{
// verify names, and change map if we get a different set.
// this is necessary because we only get document adds/removes from the project system
// when a document name or folder name changes.
ComputeFolderNames(folderItemID, newFolderNames, Hierarchy);
if (!Enumerable.SequenceEqual(folderNames, newFolderNames))
{
folderNames = newFolderNames.ToImmutableArray();
_folderNameMap[folderItemID] = folderNames;
}
}
return folderNames;
}
// Different hierarchies are inconsistent on whether they return ints or uints for VSItemIds.
// Technically it should be a uint. However, there's no enforcement of this, and marshalling
// from native to managed can end up resulting in boxed ints instead. Handle both here so
// we're resilient to however the IVsHierarchy was actually implemented.
private static uint UnboxVSItemId(object id)
=> id is uint ? (uint)id : unchecked((uint)(int)id);
private static void ComputeFolderNames(uint folderItemID, List<string> names, IVsHierarchy hierarchy)
{
if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Name, out var nameObj) == VSConstants.S_OK)
{
// For 'Shared' projects, IVSHierarchy returns a hierarchy item with < character in its name (i.e. <SharedProjectName>)
// as a child of the root item. There is no such item in the 'visual' hierarchy in solution explorer and no such folder
// is present on disk either. Since this is not a real 'folder', we exclude it from the contents of Document.Folders.
// Note: The parent of the hierarchy item that contains < character in its name is VSITEMID.Root. So we don't need to
// worry about accidental propagation out of the Shared project to any containing 'Solution' folders - the check for
// VSITEMID.Root below already takes care of that.
var name = (string)nameObj;
if (!name.StartsWith("<", StringComparison.OrdinalIgnoreCase))
{
names.Insert(0, name);
}
}
if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK)
{
var parentID = UnboxVSItemId(parentObj);
if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root))
{
ComputeFolderNames(parentID, names, hierarchy);
}
}
}
/// <summary>
/// Get the value of "rootnamespace" property of the project ("" if not defined, which means global namespace),
/// or null if it is unknown or not applicable.
/// </summary>
/// <remarks>
/// This property has different meaning between C# and VB, each project type can decide how to interpret the value.
/// </remarks>>
private static string GetRootNamespacePropertyValue(IVsHierarchy hierarchy)
{
// While both csproj and vbproj might define <rootnamespace> property in the project file,
// they are very different things.
//
// In C#, it's called default namespace (even though we got the value from rootnamespace property),
// and it doesn't affect the semantic of the code in anyway, just something used by VS.
// For example, when you create a new class, the namespace for the new class is based on it.
// Therefore, we can't get this info from compiler.
//
// However, in VB, it's actually called root namespace, and that info is part of the VB compilation
// (parsed from arguments), because VB compiler needs it to determine the root of all the namespace
// declared in the compilation.
//
// Unfortunately, although being different concepts, default namespace and root namespace are almost
// used interchangeably in VS. For example, (1) the value is define in "rootnamespace" property in project
// files and, (2) the property name we use to call into hierarchy below to retrieve the value is
// called "DefaultNamespace".
if (hierarchy.TryGetProperty(__VSHPROPID.VSHPROPID_DefaultNamespace, out string value))
{
return value;
}
return null;
}
private static bool TryGetPropertyValue(IVsHierarchy hierarchy, string propertyName, out string propertyValue)
{
if (hierarchy is not IVsBuildPropertyStorage storage)
{
propertyValue = null;
return false;
}
return ErrorHandler.Succeeded(storage.GetPropertyValue(propertyName, null, (uint)_PersistStorageType.PST_PROJECT_FILE, out propertyValue));
}
private static bool TryGetBoolPropertyValue(IVsHierarchy hierarchy, string propertyName, out bool? propertyValue)
{
if (!TryGetPropertyValue(hierarchy, propertyName, out var stringPropertyValue))
{
propertyValue = null;
return false;
}
propertyValue = bool.TryParse(stringPropertyValue, out var parsedBoolValue) ? parsedBoolValue : (bool?)null;
return true;
}
}
}
| -1 |
dotnet/roslyn | 56,545 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data. | Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| ./src/Features/Core/Portable/NavigateTo/INavigateToSearchResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Navigation;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal interface INavigateToSearchResult
{
string AdditionalInformation { get; }
string Kind { get; }
NavigateToMatchKind MatchKind { get; }
bool IsCaseSensitive { get; }
string Name { get; }
ImmutableArray<TextSpan> NameMatchSpans { get; }
string SecondarySort { get; }
string Summary { get; }
INavigableItem NavigableItem { 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.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal interface INavigateToSearchResult
{
string AdditionalInformation { get; }
string Kind { get; }
NavigateToMatchKind MatchKind { get; }
bool IsCaseSensitive { get; }
string Name { get; }
ImmutableArray<TextSpan> NameMatchSpans { get; }
string SecondarySort { get; }
string Summary { get; }
INavigableItem NavigableItem { get; }
}
}
| -1 |
dotnet/roslyn | 56,545 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data. | Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| ./src/EditorFeatures/VisualBasicTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.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.
Option Strict On
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
Imports Microsoft.CodeAnalysis.PreferFrameworkType
Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.PreferFrameworkTypeTests
Partial Public Class PreferFrameworkTypeTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Private ReadOnly onWithInfo As New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion)
Private ReadOnly offWithInfo As New CodeStyleOption2(Of Boolean)(False, NotificationOption2.Suggestion)
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (New VisualBasicPreferFrameworkTypeDiagnosticAnalyzer(),
New PreferFrameworkTypeCodeFixProvider())
End Function
Private ReadOnly Property NoFrameworkType As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeEverywhere As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeInDeclaration As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeInMemberAccess As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.onWithInfo}
}
End Get
End Property
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotWhenOptionsAreNotSet() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|Integer|]
End Class
", New TestParameters(options:=NoFrameworkType))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnUserdefinedType() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|C|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnFrameworkType() As Task
Await TestMissingInRegularAndScriptAsync("
Imports System
Class C
Protected i As [|Int32|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnQualifiedTypeSyntax() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|System.Int32|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|List|](Of Integer)
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnIdentifierThatIsNotTypeSyntax() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected [|i|] As Integer
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnBoolean_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Boolean|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnByte_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Byte|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnChar_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Char|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnObject_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Object|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnSByte_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|SByte|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnString_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|String|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnSingle_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Single|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnDecimal_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Decimal|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnDouble_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Double|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FieldDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Protected i As [|Integer|]
End Class
",
"Imports System
Class C
Protected i As Int32
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FieldDeclarationWithInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Protected i As [|Integer|] = 5
End Class
",
"Imports System
Class C
Protected i As Int32 = 5
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function DelegateDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Delegate Function PerformCalculation(x As Integer, y As Integer) As [|Integer|]
End Class
",
"Imports System
Class C
Public Delegate Function PerformCalculation(x As Integer, y As Integer) As Int32
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function PropertyDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Property X As [|Long|]
End Class
",
"Imports System
Class C
Public Property X As Int64
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GenericPropertyDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Class C
Public Property X As List(Of [|Long|])
End Class
",
"Imports System
Imports System.Collections.Generic
Class C
Public Property X As List(Of Int64)
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FunctionDeclarationReturnType() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Function F() As [|Integer|]
End Function
End Class
",
"Imports System
Class C
Public Function F() As Int32
End Function
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MethodDeclarationParameters() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub F(x As [|Integer|])
End Sub
End Class
",
"Imports System
Class C
Public Sub F(x As Int32)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GenericMethodInvocation() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Method(Of T)()
End Sub
Public Sub Test()
Method(Of [|Integer|])()
End Sub
End Class
",
"Imports System
Class C
Public Sub Method(Of T)()
End Sub
Public Sub Test()
Method(Of Int32)()
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function LocalDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x As [|Integer|] = 5
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x As Int32 = 5
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MemberAccess() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = [|Integer|].MaxValue
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = Int32.MaxValue
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MemberAccess2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = [|Integer|].Parse(""1"")
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = Int32.Parse(""1"")
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function DocCommentTriviaCrefExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
''' <see cref=""[|Integer|].MaxValue""/>
Public Sub Test()
End Sub
End Class
",
"Imports System
Class C
''' <see cref=""Integer.MaxValue""/>
Public Sub Test()
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GetTypeExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = GetType([|Integer|])
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = GetType(Int32)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FormalParametersWithinLambdaExression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim func3 As Func(Of Integer, Integer) = Function(z As [|Integer|]) z + 1
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim func3 As Func(Of Integer, Integer) = Function(z As Int32) z + 1
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ObjectCreationExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim z = New [|Date|](2016, 8, 23)
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim z = New DateTime(2016, 8, 23)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ArrayDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim k As [|Integer|]() = New Integer(3) {}
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim k As Int32() = New Integer(3) {}
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ArrayInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim k As Integer() = New [|Integer|](3) {0, 1, 2, 3}
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim k As Integer() = New Int32(3) {0, 1, 2, 3}
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MultiDimentionalArrayAsGenericTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Class C
Public Sub Test()
Dim a As List(Of [|Integer|]()(,)(,,,))
End Sub
End Class
",
"Imports System
Imports System.Collections.Generic
Class C
Public Sub Test()
Dim a As List(Of Int32()(,)(,,,))
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ForStatement() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
For j As [|Integer|] = 0 To 3
Next
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
For j As Int32 = 0 To 3
Next
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ForeachStatement() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
For Each item As [|Integer|] In New Integer() {1, 2, 3}
Next
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
For Each item As Int32 In New Integer() {1, 2, 3}
Next
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function LeadingTrivia() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
' This is a comment
Dim x As [|Integer|]
End Sub
End Class",
"Imports System
Class C
Public Sub Test()
' This is a comment
Dim x As Int32
End Sub
End Class", options:=FrameworkTypeInDeclaration)
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.
Option Strict On
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
Imports Microsoft.CodeAnalysis.PreferFrameworkType
Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.PreferFrameworkTypeTests
Partial Public Class PreferFrameworkTypeTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Private ReadOnly onWithInfo As New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion)
Private ReadOnly offWithInfo As New CodeStyleOption2(Of Boolean)(False, NotificationOption2.Suggestion)
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (New VisualBasicPreferFrameworkTypeDiagnosticAnalyzer(),
New PreferFrameworkTypeCodeFixProvider())
End Function
Private ReadOnly Property NoFrameworkType As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeEverywhere As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeInDeclaration As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeInMemberAccess As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.onWithInfo}
}
End Get
End Property
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotWhenOptionsAreNotSet() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|Integer|]
End Class
", New TestParameters(options:=NoFrameworkType))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnUserdefinedType() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|C|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnFrameworkType() As Task
Await TestMissingInRegularAndScriptAsync("
Imports System
Class C
Protected i As [|Int32|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnQualifiedTypeSyntax() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|System.Int32|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|List|](Of Integer)
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnIdentifierThatIsNotTypeSyntax() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected [|i|] As Integer
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnBoolean_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Boolean|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnByte_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Byte|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnChar_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Char|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnObject_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Object|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnSByte_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|SByte|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnString_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|String|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnSingle_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Single|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnDecimal_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Decimal|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnDouble_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Double|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FieldDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Protected i As [|Integer|]
End Class
",
"Imports System
Class C
Protected i As Int32
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FieldDeclarationWithInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Protected i As [|Integer|] = 5
End Class
",
"Imports System
Class C
Protected i As Int32 = 5
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function DelegateDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Delegate Function PerformCalculation(x As Integer, y As Integer) As [|Integer|]
End Class
",
"Imports System
Class C
Public Delegate Function PerformCalculation(x As Integer, y As Integer) As Int32
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function PropertyDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Property X As [|Long|]
End Class
",
"Imports System
Class C
Public Property X As Int64
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GenericPropertyDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Class C
Public Property X As List(Of [|Long|])
End Class
",
"Imports System
Imports System.Collections.Generic
Class C
Public Property X As List(Of Int64)
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FunctionDeclarationReturnType() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Function F() As [|Integer|]
End Function
End Class
",
"Imports System
Class C
Public Function F() As Int32
End Function
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MethodDeclarationParameters() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub F(x As [|Integer|])
End Sub
End Class
",
"Imports System
Class C
Public Sub F(x As Int32)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GenericMethodInvocation() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Method(Of T)()
End Sub
Public Sub Test()
Method(Of [|Integer|])()
End Sub
End Class
",
"Imports System
Class C
Public Sub Method(Of T)()
End Sub
Public Sub Test()
Method(Of Int32)()
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function LocalDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x As [|Integer|] = 5
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x As Int32 = 5
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MemberAccess() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = [|Integer|].MaxValue
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = Int32.MaxValue
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MemberAccess2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = [|Integer|].Parse(""1"")
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = Int32.Parse(""1"")
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function DocCommentTriviaCrefExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
''' <see cref=""[|Integer|].MaxValue""/>
Public Sub Test()
End Sub
End Class
",
"Imports System
Class C
''' <see cref=""Integer.MaxValue""/>
Public Sub Test()
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GetTypeExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = GetType([|Integer|])
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = GetType(Int32)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FormalParametersWithinLambdaExression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim func3 As Func(Of Integer, Integer) = Function(z As [|Integer|]) z + 1
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim func3 As Func(Of Integer, Integer) = Function(z As Int32) z + 1
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ObjectCreationExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim z = New [|Date|](2016, 8, 23)
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim z = New DateTime(2016, 8, 23)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ArrayDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim k As [|Integer|]() = New Integer(3) {}
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim k As Int32() = New Integer(3) {}
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ArrayInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim k As Integer() = New [|Integer|](3) {0, 1, 2, 3}
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim k As Integer() = New Int32(3) {0, 1, 2, 3}
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MultiDimentionalArrayAsGenericTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Class C
Public Sub Test()
Dim a As List(Of [|Integer|]()(,)(,,,))
End Sub
End Class
",
"Imports System
Imports System.Collections.Generic
Class C
Public Sub Test()
Dim a As List(Of Int32()(,)(,,,))
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ForStatement() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
For j As [|Integer|] = 0 To 3
Next
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
For j As Int32 = 0 To 3
Next
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ForeachStatement() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
For Each item As [|Integer|] In New Integer() {1, 2, 3}
Next
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
For Each item As Int32 In New Integer() {1, 2, 3}
Next
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function LeadingTrivia() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
' This is a comment
Dim x As [|Integer|]
End Sub
End Class",
"Imports System
Class C
Public Sub Test()
' This is a comment
Dim x As Int32
End Sub
End Class", options:=FrameworkTypeInDeclaration)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,545 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data. | Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| ./src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/IAnonymousTypeDisplayExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal static class IAnonymousTypeDisplayExtensions
{
public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes(
this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position)
{
var result = parts;
while (true)
{
var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType());
if (delegateAnonymousType == null)
{
break;
}
result = result == parts ? new List<SymbolDisplayPart>(parts) : result;
ReplaceAnonymousType(result, delegateAnonymousType,
service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position));
}
return result;
}
private static void ReplaceAnonymousType(
IList<SymbolDisplayPart> list,
INamedTypeSymbol anonymousType,
IEnumerable<SymbolDisplayPart> parts)
{
var index = list.IndexOf(p => anonymousType.Equals(p.Symbol));
if (index >= 0)
{
var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList();
list.Clear();
list.AddRange(result);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal static class IAnonymousTypeDisplayExtensions
{
public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes(
this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position)
{
var result = parts;
while (true)
{
var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType());
if (delegateAnonymousType == null)
{
break;
}
result = result == parts ? new List<SymbolDisplayPart>(parts) : result;
ReplaceAnonymousType(result, delegateAnonymousType,
service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position));
}
return result;
}
private static void ReplaceAnonymousType(
IList<SymbolDisplayPart> list,
INamedTypeSymbol anonymousType,
IEnumerable<SymbolDisplayPart> parts)
{
var index = list.IndexOf(p => anonymousType.Equals(p.Symbol));
if (index >= 0)
{
var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList();
list.Clear();
list.AddRange(result);
}
}
}
}
| -1 |
dotnet/roslyn | 56,545 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data. | Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal sealed class PropertyAccessorSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IMethodSymbol>
{
protected override bool CanFind(IMethodSymbol symbol)
=> symbol.MethodKind.IsPropertyAccessor();
protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync(
IMethodSymbol symbol,
Solution solution,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// If we've been asked to search for specific accessors, then do not cascade.
// We don't want to produce results for the associated property.
return options.AssociatePropertyReferencesWithSpecificAccessor || symbol.AssociatedSymbol == null
? SpecializedTasks.EmptyImmutableArray<ISymbol>()
: Task.FromResult(ImmutableArray.Create(symbol.AssociatedSymbol));
}
protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
IMethodSymbol symbol,
HashSet<string>? globalAliases,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// First, find any documents with the full name of the accessor (i.e. get_Goo).
// This will find explicit calls to the method (which can happen when C# references
// a VB parameterized property).
var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false);
var propertyDocuments = ImmutableArray<Document>.Empty;
if (symbol.AssociatedSymbol is IPropertySymbol property &&
options.AssociatePropertyReferencesWithSpecificAccessor)
{
// we want to associate normal property references with the specific accessor being
// referenced. So we also need to include documents with our property's name. Just
// defer to the Property finder to find these docs and combine them with the result.
propertyDocuments = await ReferenceFinders.Property.DetermineDocumentsToSearchAsync(
property, globalAliases, project, documents,
options.With(associatePropertyReferencesWithSpecificAccessor: false),
cancellationToken).ConfigureAwait(false);
}
var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false);
return documentsWithName.Concat(propertyDocuments, documentsWithGlobalAttributes);
}
protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
IMethodSymbol symbol,
HashSet<string>? globalAliases,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var references = await FindReferencesInDocumentUsingSymbolNameAsync(
symbol, document, semanticModel, cancellationToken).ConfigureAwait(false);
if (symbol.AssociatedSymbol is IPropertySymbol property &&
options.AssociatePropertyReferencesWithSpecificAccessor)
{
var propertyReferences = await ReferenceFinders.Property.FindReferencesInDocumentAsync(
property, globalAliases, document, semanticModel,
options.With(associatePropertyReferencesWithSpecificAccessor: false),
cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>();
var accessorReferences = propertyReferences.WhereAsArray(
loc =>
{
var accessors = GetReferencedAccessorSymbols(
syntaxFacts, semanticFacts, semanticModel, property, loc.Node, cancellationToken);
return accessors.Contains(symbol);
});
references = references.AddRange(accessorReferences);
}
return references;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal sealed class PropertyAccessorSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IMethodSymbol>
{
protected override bool CanFind(IMethodSymbol symbol)
=> symbol.MethodKind.IsPropertyAccessor();
protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync(
IMethodSymbol symbol,
Solution solution,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// If we've been asked to search for specific accessors, then do not cascade.
// We don't want to produce results for the associated property.
return options.AssociatePropertyReferencesWithSpecificAccessor || symbol.AssociatedSymbol == null
? SpecializedTasks.EmptyImmutableArray<ISymbol>()
: Task.FromResult(ImmutableArray.Create(symbol.AssociatedSymbol));
}
protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
IMethodSymbol symbol,
HashSet<string>? globalAliases,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// First, find any documents with the full name of the accessor (i.e. get_Goo).
// This will find explicit calls to the method (which can happen when C# references
// a VB parameterized property).
var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false);
var propertyDocuments = ImmutableArray<Document>.Empty;
if (symbol.AssociatedSymbol is IPropertySymbol property &&
options.AssociatePropertyReferencesWithSpecificAccessor)
{
// we want to associate normal property references with the specific accessor being
// referenced. So we also need to include documents with our property's name. Just
// defer to the Property finder to find these docs and combine them with the result.
propertyDocuments = await ReferenceFinders.Property.DetermineDocumentsToSearchAsync(
property, globalAliases, project, documents,
options.With(associatePropertyReferencesWithSpecificAccessor: false),
cancellationToken).ConfigureAwait(false);
}
var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false);
return documentsWithName.Concat(propertyDocuments, documentsWithGlobalAttributes);
}
protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
IMethodSymbol symbol,
HashSet<string>? globalAliases,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var references = await FindReferencesInDocumentUsingSymbolNameAsync(
symbol, document, semanticModel, cancellationToken).ConfigureAwait(false);
if (symbol.AssociatedSymbol is IPropertySymbol property &&
options.AssociatePropertyReferencesWithSpecificAccessor)
{
var propertyReferences = await ReferenceFinders.Property.FindReferencesInDocumentAsync(
property, globalAliases, document, semanticModel,
options.With(associatePropertyReferencesWithSpecificAccessor: false),
cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>();
var accessorReferences = propertyReferences.WhereAsArray(
loc =>
{
var accessors = GetReferencedAccessorSymbols(
syntaxFacts, semanticFacts, semanticModel, property, loc.Node, cancellationToken);
return accessors.Contains(symbol);
});
references = references.AddRange(accessorReferences);
}
return references;
}
}
}
| -1 |
dotnet/roslyn | 56,545 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data. | Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| ./src/Compilers/VisualBasic/Test/Symbol/StaticLocalDeclarationTests.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
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class StaticLocalDeclarationTests
Inherits BasicTestBase
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Valid_BasicParsingWithDim()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Goo()
Goo()
End Sub
Sub Goo()
Static Dim x As Integer = 1
Console.WriteLine(x)
x = x + 1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics()
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Valid_BasicParsingWithoutDim()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Goo()
Goo()
End Sub
Sub Goo()
Static x As Integer = 1
Console.WriteLine(x)
x = x + 1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics()
End Sub
<Fact>
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
Public Sub Error_StaticLocal_DuplicationDeclarations_InSameScopes()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InSameScopes()
StaticLocal_DuplicationDeclarations_InSameScopes()
End Sub
Sub StaticLocal_DuplicationDeclarations_InSameScopes()
Static x As Integer = 1
Console.WriteLine(x)
Static x As Integer = 2 'Err
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
'This should present a single error BC31401: Static local variable 'x' is already declared.
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31401: Static local variable 'x' is already declared.
Static x As Integer = 2 'Err
~
</expected>)
End Sub
<Fact>
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal1()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
StaticLocal_ConflictDeclarations()
StaticLocal_ConflictDeclarations()
End Sub
Sub StaticLocal_ConflictDeclarations()
Static x As Integer = 1 'Err
Console.WriteLine(x)
Dim x As Integer = 2
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30288: Local variable 'x' is already declared in the current block.
Dim x As Integer = 2
~
</expected>)
End Sub
<Fact>
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal2()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
StaticLocal_ConflictDeclarations()
StaticLocal_ConflictDeclarations()
End Sub
Sub StaticLocal_ConflictDeclarations()
Dim x As Integer = 1
Console.WriteLine(x)
Static x As Integer = 2 'Err
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30288: Local variable 'x' is already declared in the current block.
Static x As Integer = 2 'Err
~
</expected>)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch()
StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch()
End Sub
Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch()
Try
Dim y As Integer = 1
Static x As Integer = 1
Catch ex As Exception
Dim y As Integer = 2
Static x As Integer = 2 'Error
End Try
End Sub
End Module
</file>
</compilation>
'This should present a single error BC31401: Static local variable 'x' is already declared.
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(1)
StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(2)
End Sub
Sub StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(a As Integer)
Select Case a
Case 1
Dim y As Integer = 1
Static x As Integer = 1
Case 2
Dim y As Integer = 1
Static x As Integer = 1 'Error
End Select
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_If()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InDifferentScopes_If()
End Sub
Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_If()
If True Then
Dim y As Integer = 1
Static x As Integer = 1
Else
Dim y As Integer = 2
Static x As Integer = 2 'Error
End If
End Sub
End Module </file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_For()
'Show differences between static local and normal local
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InDifferentScopes_For()
StaticLocal_DuplicationDeclarations_InDifferentScopes_For()
End Sub
Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_For()
Dim y As Integer = 1
Static x As Integer = 1 'Warning Hide in enclosing block
For i = 1 To 2
Dim y As Integer = 2 'Warning Hide in enclosing block
Static x As Integer = 3 'Error
Next
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "y").WithArguments("y"),
Diagnostic(ERRID.ERR_BlockLocalShadowing1, "x").WithArguments("x"),
Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_InGeneric()
'Cannot declare in generic method
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
Dim x as new UDTest()
x.Goo(of Integer)()
x.Goo(of Integer)()
End Sub
End Module
Public Class UDTest
Public Sub Goo(of t)
Static SLItem as integer = 1
SLItem +=1
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInGenericMethod, "Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_InStructure()
'Cannot declare in Structure Type
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
Dim x As New UDTest()
x.Goo()
x.Goo()
End Sub
End Module
Public Structure UDTest
Public Sub Goo()
Static SLItem As Integer = 1
SLItem += 1
End Sub
End Structure
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInStruct, "Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_WithModifiers()
'Errors in conjunction with access modifiers
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
AccessModifiers()
End Sub
Sub AccessModifiers()
'These are prettylisted with Access Modified beforehand
Public Static SLItem1 As String = ""
Private Static SLItem2 As String = ""
Protected Static SLItem3 As String = ""
Friend Static SLItem4 As String = ""
Protected Friend Static SLItem5 As String = ""
Static Shared SLItem6
Static Dim SLItem_Valid1 As String = "" 'Valid
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Public").WithArguments("Public"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Private").WithArguments("Private"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Shared").WithArguments("Shared"),
Diagnostic(ERRID.WRN_UnusedLocal, "SLItem6").WithArguments("SLItem6"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_OutsideOfMethod()
'Static Locals outside of method bodies
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
AccessModifiers()
AccessModifiers()
End Sub
Static SLItem_Valid1 As String = "" 'Invalid
Sub AccessModifiers()
Static SLItem_Valid1 As String = "" 'Valid
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadDimFlags1, "Static").WithArguments("Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_TryingToAccessStaticLocalFromOutsideMethod()
'trying to access SL from oUtside method not possible
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
'trying to access SL from oUtside method not possible
StaticLocalInSub()
StaticLocalInSub.slItem = 2 'ERROR
StaticLocalInSub2()
StaticLocalInSub2.slItem = 2 'ERROR
End Sub
Sub StaticLocalInSub()
Static SLItem1 = 1
SLItem1 += 1
End Sub
Public Sub StaticLocalInSub2()
'With Method Accessibility set to Public
Static SLItem1 = 1
SLItem1 += 1
End Sub
End Module</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub"),
Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub2"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_HideLocalInCatchBlock()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
'trying to access SL from oUtside method not possible
Test4_Err()
End Sub
Public Sub Test4_Err()
Static sl1 As String = ""
Try
Throw New Exception("Test")
Catch sl1 As Exception 'Err
sl1 &= "InCatch" 'Err - this is the exception instance not the static local
Finally
End Try
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "sl1").WithArguments("sl1"),
Diagnostic(ERRID.ERR_BinaryOperands3, "sl1 &= ""InCatch""").WithArguments("&", "System.Exception", "String"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Keyword_NameClashInIdentifier()
'declare UnEscaped identifier called static
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
AvoidingNameConflicts1()
End Sub
Sub AvoidingNameConflicts1()
Static Static as double = 1 'Error
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "as"),
Diagnostic(ERRID.ERR_DuplicateSpecifier, "Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Keyword_NameTypeClash()
'declare escaped identifier and type called static along with static
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
AvoidingNameConflicts()
End Sub
Sub AvoidingNameConflicts()
Static [Static] As New [Static]
End Sub
End Module
Class Static 'Error Clash With Keyword
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_InLambda_SingleLine()
'Single Line Lambda
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
InSingleLineLambda()
End Sub
Sub InSingleLineLambda()
Static sl1 As Integer = 0
'Declaring Static in Single Line Lambda
Dim l1 = Sub() static x1 As Integer = 0 'Error
Dim l2 = Function() static x2 As Integer = 0 'Error
'Using Lifted Locals in Lambda's
Dim l3 = Sub() sl1 += 1
Dim l4 = Function() (sl1 + 1)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_SubDisallowsStatement, "static x1 As Integer = 0"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_InLambda_MultiLine()
'Multi-Line Lambda
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
InMultiLineLambda()
End Sub
Sub InMultiLineLambda()
Static sl1 As Integer = 0
'Declaring Static in MultiLine
Dim l1 = Sub()
static x1 As Integer = 0 'Error
End Sub
Dim l2 = Function()
static x2 As Integer = 0 'Error
Return x2
End Function
'Using Lifted Locals in Lambda's
Dim l3 = Sub()
sl1 += 1
End Sub
Dim l4 = Function()
sl1 += 1
Return sl1
End Function
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StaticInLambda, "static"),
Diagnostic(ERRID.ERR_StaticInLambda, "static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalInTryCatchBlockScope()
'The Use of Static Locals within Try/Catch/Finally Blocks
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
test(False)
test(True)
End Sub
Sub test(ThrowException As Boolean)
Try
If ThrowException Then
Throw New Exception
End If
Catch ex As Exception
Static sl As Integer = 1
sl += 1
End Try
Console.WriteLine(SL.tostring) 'Error Outside Scope
End Sub
End Module</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "SL").WithArguments("SL"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_SpecialType_ArgIterator()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Goo()
Goo()
End Sub
Sub Goo()
Static SLItem2 As ArgIterator
End Sub
End Module</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "ArgIterator").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.WRN_UnusedLocal, "SLItem2").WithArguments("SLItem2"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_SpecialType_TypedReference()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Goo()
Goo()
End Sub
Sub Goo()
Static SLItem2 As TypedReference = Nothing
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "TypedReference").WithArguments("System.TypedReference"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalWithRangeVariables()
'The Use of Static Locals within Try/Catch/Finally Blocks
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
test()
test()
End Sub
Sub test()
Static sl As Integer = 1
Dim x = From sl In {1, 2, 3} Select sl 'Error Same Scope
Console.WriteLine(sl.ToString)
sl += 1
End Sub
End Module</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQueryableSource, "{1, 2, 3}").WithArguments("Integer()"),
Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl"),
Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl"))
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
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class StaticLocalDeclarationTests
Inherits BasicTestBase
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Valid_BasicParsingWithDim()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Goo()
Goo()
End Sub
Sub Goo()
Static Dim x As Integer = 1
Console.WriteLine(x)
x = x + 1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics()
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Valid_BasicParsingWithoutDim()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Goo()
Goo()
End Sub
Sub Goo()
Static x As Integer = 1
Console.WriteLine(x)
x = x + 1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics()
End Sub
<Fact>
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
Public Sub Error_StaticLocal_DuplicationDeclarations_InSameScopes()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InSameScopes()
StaticLocal_DuplicationDeclarations_InSameScopes()
End Sub
Sub StaticLocal_DuplicationDeclarations_InSameScopes()
Static x As Integer = 1
Console.WriteLine(x)
Static x As Integer = 2 'Err
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
'This should present a single error BC31401: Static local variable 'x' is already declared.
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31401: Static local variable 'x' is already declared.
Static x As Integer = 2 'Err
~
</expected>)
End Sub
<Fact>
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal1()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
StaticLocal_ConflictDeclarations()
StaticLocal_ConflictDeclarations()
End Sub
Sub StaticLocal_ConflictDeclarations()
Static x As Integer = 1 'Err
Console.WriteLine(x)
Dim x As Integer = 2
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30288: Local variable 'x' is already declared in the current block.
Dim x As Integer = 2
~
</expected>)
End Sub
<Fact>
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal2()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
StaticLocal_ConflictDeclarations()
StaticLocal_ConflictDeclarations()
End Sub
Sub StaticLocal_ConflictDeclarations()
Dim x As Integer = 1
Console.WriteLine(x)
Static x As Integer = 2 'Err
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30288: Local variable 'x' is already declared in the current block.
Static x As Integer = 2 'Err
~
</expected>)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch()
StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch()
End Sub
Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch()
Try
Dim y As Integer = 1
Static x As Integer = 1
Catch ex As Exception
Dim y As Integer = 2
Static x As Integer = 2 'Error
End Try
End Sub
End Module
</file>
</compilation>
'This should present a single error BC31401: Static local variable 'x' is already declared.
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(1)
StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(2)
End Sub
Sub StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(a As Integer)
Select Case a
Case 1
Dim y As Integer = 1
Static x As Integer = 1
Case 2
Dim y As Integer = 1
Static x As Integer = 1 'Error
End Select
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_If()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InDifferentScopes_If()
End Sub
Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_If()
If True Then
Dim y As Integer = 1
Static x As Integer = 1
Else
Dim y As Integer = 2
Static x As Integer = 2 'Error
End If
End Sub
End Module </file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_For()
'Show differences between static local and normal local
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
StaticLocal_DuplicationDeclarations_InDifferentScopes_For()
StaticLocal_DuplicationDeclarations_InDifferentScopes_For()
End Sub
Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_For()
Dim y As Integer = 1
Static x As Integer = 1 'Warning Hide in enclosing block
For i = 1 To 2
Dim y As Integer = 2 'Warning Hide in enclosing block
Static x As Integer = 3 'Error
Next
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "y").WithArguments("y"),
Diagnostic(ERRID.ERR_BlockLocalShadowing1, "x").WithArguments("x"),
Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_InGeneric()
'Cannot declare in generic method
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
Dim x as new UDTest()
x.Goo(of Integer)()
x.Goo(of Integer)()
End Sub
End Module
Public Class UDTest
Public Sub Goo(of t)
Static SLItem as integer = 1
SLItem +=1
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInGenericMethod, "Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_InStructure()
'Cannot declare in Structure Type
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
Dim x As New UDTest()
x.Goo()
x.Goo()
End Sub
End Module
Public Structure UDTest
Public Sub Goo()
Static SLItem As Integer = 1
SLItem += 1
End Sub
End Structure
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInStruct, "Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_WithModifiers()
'Errors in conjunction with access modifiers
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
AccessModifiers()
End Sub
Sub AccessModifiers()
'These are prettylisted with Access Modified beforehand
Public Static SLItem1 As String = ""
Private Static SLItem2 As String = ""
Protected Static SLItem3 As String = ""
Friend Static SLItem4 As String = ""
Protected Friend Static SLItem5 As String = ""
Static Shared SLItem6
Static Dim SLItem_Valid1 As String = "" 'Valid
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Public").WithArguments("Public"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Private").WithArguments("Private"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"),
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Shared").WithArguments("Shared"),
Diagnostic(ERRID.WRN_UnusedLocal, "SLItem6").WithArguments("SLItem6"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_OutsideOfMethod()
'Static Locals outside of method bodies
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
AccessModifiers()
AccessModifiers()
End Sub
Static SLItem_Valid1 As String = "" 'Invalid
Sub AccessModifiers()
Static SLItem_Valid1 As String = "" 'Valid
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadDimFlags1, "Static").WithArguments("Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_TryingToAccessStaticLocalFromOutsideMethod()
'trying to access SL from oUtside method not possible
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
'trying to access SL from oUtside method not possible
StaticLocalInSub()
StaticLocalInSub.slItem = 2 'ERROR
StaticLocalInSub2()
StaticLocalInSub2.slItem = 2 'ERROR
End Sub
Sub StaticLocalInSub()
Static SLItem1 = 1
SLItem1 += 1
End Sub
Public Sub StaticLocalInSub2()
'With Method Accessibility set to Public
Static SLItem1 = 1
SLItem1 += 1
End Sub
End Module</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub"),
Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub2"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_HideLocalInCatchBlock()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
'trying to access SL from oUtside method not possible
Test4_Err()
End Sub
Public Sub Test4_Err()
Static sl1 As String = ""
Try
Throw New Exception("Test")
Catch sl1 As Exception 'Err
sl1 &= "InCatch" 'Err - this is the exception instance not the static local
Finally
End Try
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "sl1").WithArguments("sl1"),
Diagnostic(ERRID.ERR_BinaryOperands3, "sl1 &= ""InCatch""").WithArguments("&", "System.Exception", "String"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Keyword_NameClashInIdentifier()
'declare UnEscaped identifier called static
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
AvoidingNameConflicts1()
End Sub
Sub AvoidingNameConflicts1()
Static Static as double = 1 'Error
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "as"),
Diagnostic(ERRID.ERR_DuplicateSpecifier, "Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Keyword_NameTypeClash()
'declare escaped identifier and type called static along with static
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
AvoidingNameConflicts()
End Sub
Sub AvoidingNameConflicts()
Static [Static] As New [Static]
End Sub
End Module
Class Static 'Error Clash With Keyword
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_InLambda_SingleLine()
'Single Line Lambda
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
InSingleLineLambda()
End Sub
Sub InSingleLineLambda()
Static sl1 As Integer = 0
'Declaring Static in Single Line Lambda
Dim l1 = Sub() static x1 As Integer = 0 'Error
Dim l2 = Function() static x2 As Integer = 0 'Error
'Using Lifted Locals in Lambda's
Dim l3 = Sub() sl1 += 1
Dim l4 = Function() (sl1 + 1)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_SubDisallowsStatement, "static x1 As Integer = 0"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalDeclaration_Negative_InLambda_MultiLine()
'Multi-Line Lambda
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Module Module1
Sub Main()
InMultiLineLambda()
End Sub
Sub InMultiLineLambda()
Static sl1 As Integer = 0
'Declaring Static in MultiLine
Dim l1 = Sub()
static x1 As Integer = 0 'Error
End Sub
Dim l2 = Function()
static x2 As Integer = 0 'Error
Return x2
End Function
'Using Lifted Locals in Lambda's
Dim l3 = Sub()
sl1 += 1
End Sub
Dim l4 = Function()
sl1 += 1
Return sl1
End Function
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StaticInLambda, "static"),
Diagnostic(ERRID.ERR_StaticInLambda, "static"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalInTryCatchBlockScope()
'The Use of Static Locals within Try/Catch/Finally Blocks
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
test(False)
test(True)
End Sub
Sub test(ThrowException As Boolean)
Try
If ThrowException Then
Throw New Exception
End If
Catch ex As Exception
Static sl As Integer = 1
sl += 1
End Try
Console.WriteLine(SL.tostring) 'Error Outside Scope
End Sub
End Module</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "SL").WithArguments("SL"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_SpecialType_ArgIterator()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Goo()
Goo()
End Sub
Sub Goo()
Static SLItem2 As ArgIterator
End Sub
End Module</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "ArgIterator").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.WRN_UnusedLocal, "SLItem2").WithArguments("SLItem2"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocal_SpecialType_TypedReference()
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Goo()
Goo()
End Sub
Sub Goo()
Static SLItem2 As TypedReference = Nothing
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "TypedReference").WithArguments("System.TypedReference"))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Error_StaticLocalWithRangeVariables()
'The Use of Static Locals within Try/Catch/Finally Blocks
Dim compilationDef =
<compilation name="StaticLocaltest">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
test()
test()
End Sub
Sub test()
Static sl As Integer = 1
Dim x = From sl In {1, 2, 3} Select sl 'Error Same Scope
Console.WriteLine(sl.ToString)
sl += 1
End Sub
End Module</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQueryableSource, "{1, 2, 3}").WithArguments("Integer()"),
Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl"),
Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl"))
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,545 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data. | Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125.
The second commit contains only renames, it might be simpler to review it separately.
| ./src/Workspaces/CSharp/Portable/CodeGeneration/PropertyGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class PropertyGenerator
{
public static bool CanBeGenerated(IPropertySymbol property)
=> property.IsIndexer || property.Parameters.Length == 0;
private static MemberDeclarationSyntax LastPropertyOrField(
SyntaxList<MemberDeclarationSyntax> members)
{
var lastProperty = members.LastOrDefault(m => m is PropertyDeclarationSyntax);
return lastProperty ?? LastField(members);
}
internal static CompilationUnitSyntax AddPropertyTo(
CompilationUnitSyntax destination,
IPropertySymbol property,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GeneratePropertyOrIndexer(
property, CodeGenerationDestination.CompilationUnit, options,
destination?.SyntaxTree.Options ?? options.ParseOptions);
var members = Insert(destination.Members, declaration, options,
availableIndices, after: LastPropertyOrField, before: FirstMember);
return destination.WithMembers(members);
}
internal static TypeDeclarationSyntax AddPropertyTo(
TypeDeclarationSyntax destination,
IPropertySymbol property,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GeneratePropertyOrIndexer(property, GetDestination(destination),
options, destination?.SyntaxTree.Options ?? options.ParseOptions);
// Create a clone of the original type with the new method inserted.
var members = Insert(destination.Members, declaration, options,
availableIndices, after: LastPropertyOrField, before: FirstMember);
// Find the best place to put the field. It should go after the last field if we already
// have fields, or at the beginning of the file if we don't.
return AddMembersTo(destination, members);
}
public static MemberDeclarationSyntax GeneratePropertyOrIndexer(
IPropertySymbol property,
CodeGenerationDestination destination,
CodeGenerationOptions options,
ParseOptions parseOptions)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(property, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
var declaration = property.IsIndexer
? GenerateIndexerDeclaration(property, destination, options, parseOptions)
: GeneratePropertyDeclaration(property, destination, options, parseOptions);
return ConditionallyAddDocumentationCommentTo(declaration, property, options);
}
private static MemberDeclarationSyntax GenerateIndexerDeclaration(
IPropertySymbol property,
CodeGenerationDestination destination,
CodeGenerationOptions options,
ParseOptions parseOptions)
{
var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations);
var declaration = SyntaxFactory.IndexerDeclaration(
attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options),
modifiers: GenerateModifiers(property, destination, options),
type: GenerateTypeSyntax(property),
explicitInterfaceSpecifier: explicitInterfaceSpecifier,
parameterList: ParameterGenerator.GenerateBracketedParameterList(property.Parameters, explicitInterfaceSpecifier != null, options),
accessorList: GenerateAccessorList(property, destination, options, parseOptions));
declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions);
return AddFormatterAndCodeGeneratorAnnotationsTo(
AddAnnotationsTo(property, declaration));
}
private static MemberDeclarationSyntax GeneratePropertyDeclaration(
IPropertySymbol property, CodeGenerationDestination destination,
CodeGenerationOptions options, ParseOptions parseOptions)
{
var initializer = CodeGenerationPropertyInfo.GetInitializer(property) is ExpressionSyntax initializerNode
? SyntaxFactory.EqualsValueClause(initializerNode)
: null;
var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations);
var accessorList = GenerateAccessorList(property, destination, options, parseOptions);
var propertyDeclaration = SyntaxFactory.PropertyDeclaration(
attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options),
modifiers: GenerateModifiers(property, destination, options),
type: GenerateTypeSyntax(property),
explicitInterfaceSpecifier: explicitInterfaceSpecifier,
identifier: property.Name.ToIdentifierToken(),
accessorList: accessorList,
expressionBody: null,
initializer: initializer);
propertyDeclaration = UseExpressionBodyIfDesired(options, propertyDeclaration, parseOptions);
return AddFormatterAndCodeGeneratorAnnotationsTo(
AddAnnotationsTo(property, propertyDeclaration));
}
private static TypeSyntax GenerateTypeSyntax(IPropertySymbol property)
{
var returnType = property.Type;
if (property.ReturnsByRef)
{
return returnType.GenerateRefTypeSyntax();
}
else if (property.ReturnsByRefReadonly)
{
return returnType.GenerateRefReadOnlyTypeSyntax();
}
else
{
return returnType.GenerateTypeSyntax();
}
}
private static bool TryGetExpressionBody(
BasePropertyDeclarationSyntax baseProperty, ParseOptions options, ExpressionBodyPreference preference,
out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken)
{
var accessorList = baseProperty.AccessorList;
if (preference != ExpressionBodyPreference.Never &&
accessorList.Accessors.Count == 1)
{
var accessor = accessorList.Accessors[0];
if (accessor.IsKind(SyntaxKind.GetAccessorDeclaration))
{
return TryGetArrowExpressionBody(
baseProperty.Kind(), accessor, options, preference,
out arrowExpression, out semicolonToken);
}
}
arrowExpression = null;
semicolonToken = default;
return false;
}
private static PropertyDeclarationSyntax UseExpressionBodyIfDesired(
CodeGenerationOptions options, PropertyDeclarationSyntax declaration, ParseOptions parseOptions)
{
if (declaration.ExpressionBody == null)
{
var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value;
if (declaration.Initializer == null)
{
if (TryGetExpressionBody(
declaration, parseOptions, expressionBodyPreference,
out var expressionBody, out var semicolonToken))
{
declaration = declaration.WithAccessorList(null)
.WithExpressionBody(expressionBody)
.WithSemicolonToken(semicolonToken);
}
}
}
return declaration;
}
private static IndexerDeclarationSyntax UseExpressionBodyIfDesired(
CodeGenerationOptions options, IndexerDeclarationSyntax declaration, ParseOptions parseOptions)
{
if (declaration.ExpressionBody == null)
{
var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers).Value;
if (TryGetExpressionBody(
declaration, parseOptions, expressionBodyPreference,
out var expressionBody, out var semicolonToken))
{
declaration = declaration.WithAccessorList(null)
.WithExpressionBody(expressionBody)
.WithSemicolonToken(semicolonToken);
}
}
return declaration;
}
private static AccessorDeclarationSyntax UseExpressionBodyIfDesired(
CodeGenerationOptions options, AccessorDeclarationSyntax declaration, ParseOptions parseOptions)
{
if (declaration.ExpressionBody == null)
{
var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value;
if (declaration.Body.TryConvertToArrowExpressionBody(
declaration.Kind(), parseOptions, expressionBodyPreference,
out var expressionBody, out var semicolonToken))
{
declaration = declaration.WithBody(null)
.WithExpressionBody(expressionBody)
.WithSemicolonToken(semicolonToken);
}
}
return declaration;
}
private static bool TryGetArrowExpressionBody(
SyntaxKind declaratoinKind, AccessorDeclarationSyntax accessor, ParseOptions options, ExpressionBodyPreference preference,
out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken)
{
// If the accessor has an expression body already, then use that as the expression body
// for the property.
if (accessor.ExpressionBody != null)
{
arrowExpression = accessor.ExpressionBody;
semicolonToken = accessor.SemicolonToken;
return true;
}
return accessor.Body.TryConvertToArrowExpressionBody(
declaratoinKind, options, preference, out arrowExpression, out semicolonToken);
}
private static AccessorListSyntax GenerateAccessorList(
IPropertySymbol property, CodeGenerationDestination destination,
CodeGenerationOptions options, ParseOptions parseOptions)
{
var setAccessorKind = property.SetMethod?.IsInitOnly == true ? SyntaxKind.InitAccessorDeclaration : SyntaxKind.SetAccessorDeclaration;
var accessors = new List<AccessorDeclarationSyntax>
{
GenerateAccessorDeclaration(property, property.GetMethod, SyntaxKind.GetAccessorDeclaration, destination, options, parseOptions),
GenerateAccessorDeclaration(property, property.SetMethod, setAccessorKind, destination, options, parseOptions),
};
return accessors[0] == null && accessors[1] == null
? null
: SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList());
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IPropertySymbol property,
IMethodSymbol accessor,
SyntaxKind kind,
CodeGenerationDestination destination,
CodeGenerationOptions options,
ParseOptions parseOptions)
{
var hasBody = options.GenerateMethodBodies && HasAccessorBodies(property, destination, accessor);
return accessor == null
? null
: GenerateAccessorDeclaration(property, accessor, kind, hasBody, options, parseOptions);
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IPropertySymbol property,
IMethodSymbol accessor,
SyntaxKind kind,
bool hasBody,
CodeGenerationOptions options,
ParseOptions parseOptions)
{
var declaration = SyntaxFactory.AccessorDeclaration(kind)
.WithModifiers(GenerateAccessorModifiers(property, accessor, options))
.WithBody(hasBody ? GenerateBlock(accessor) : null)
.WithSemicolonToken(hasBody ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken));
declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions);
return AddAnnotationsTo(accessor, declaration);
}
private static BlockSyntax GenerateBlock(IMethodSymbol accessor)
{
return SyntaxFactory.Block(
StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(accessor)));
}
private static bool HasAccessorBodies(
IPropertySymbol property,
CodeGenerationDestination destination,
IMethodSymbol accessor)
{
return destination != CodeGenerationDestination.InterfaceType &&
!property.IsAbstract &&
accessor != null &&
!accessor.IsAbstract;
}
private static SyntaxTokenList GenerateAccessorModifiers(
IPropertySymbol property,
IMethodSymbol accessor,
CodeGenerationOptions options)
{
var modifiers = ArrayBuilder<SyntaxToken>.GetInstance();
if (accessor.DeclaredAccessibility != Accessibility.NotApplicable &&
accessor.DeclaredAccessibility != property.DeclaredAccessibility)
{
AddAccessibilityModifiers(accessor.DeclaredAccessibility, modifiers, options, property.DeclaredAccessibility);
}
var hasNonReadOnlyAccessor = property.GetMethod?.IsReadOnly == false || property.SetMethod?.IsReadOnly == false;
if (hasNonReadOnlyAccessor && accessor.IsReadOnly)
{
modifiers.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
return modifiers.ToSyntaxTokenListAndFree();
}
private static SyntaxTokenList GenerateModifiers(
IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var tokens = ArrayBuilder<SyntaxToken>.GetInstance();
// Most modifiers not allowed if we're an explicit impl.
if (!property.ExplicitInterfaceImplementations.Any())
{
if (destination is not CodeGenerationDestination.CompilationUnit and
not CodeGenerationDestination.InterfaceType)
{
AddAccessibilityModifiers(property.DeclaredAccessibility, tokens, options, Accessibility.Private);
if (property.IsStatic)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
// note: explicit interface impls are allowed to be 'readonly' but it never actually affects callers
// because of the boxing requirement in order to call the method.
// therefore it seems like a small oversight to leave out the keyword for an explicit impl from metadata.
var hasAllReadOnlyAccessors = property.GetMethod?.IsReadOnly != false && property.SetMethod?.IsReadOnly != false;
// Don't show the readonly modifier if the containing type is already readonly
if (hasAllReadOnlyAccessors && !property.ContainingType.IsReadOnly)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
if (property.IsSealed)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword));
}
if (property.IsOverride)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword));
}
if (property.IsVirtual)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword));
}
if (property.IsAbstract)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword));
}
}
}
if (CodeGenerationPropertyInfo.GetIsUnsafe(property))
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
return tokens.ToSyntaxTokenList();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class PropertyGenerator
{
public static bool CanBeGenerated(IPropertySymbol property)
=> property.IsIndexer || property.Parameters.Length == 0;
private static MemberDeclarationSyntax LastPropertyOrField(
SyntaxList<MemberDeclarationSyntax> members)
{
var lastProperty = members.LastOrDefault(m => m is PropertyDeclarationSyntax);
return lastProperty ?? LastField(members);
}
internal static CompilationUnitSyntax AddPropertyTo(
CompilationUnitSyntax destination,
IPropertySymbol property,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GeneratePropertyOrIndexer(
property, CodeGenerationDestination.CompilationUnit, options,
destination?.SyntaxTree.Options ?? options.ParseOptions);
var members = Insert(destination.Members, declaration, options,
availableIndices, after: LastPropertyOrField, before: FirstMember);
return destination.WithMembers(members);
}
internal static TypeDeclarationSyntax AddPropertyTo(
TypeDeclarationSyntax destination,
IPropertySymbol property,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GeneratePropertyOrIndexer(property, GetDestination(destination),
options, destination?.SyntaxTree.Options ?? options.ParseOptions);
// Create a clone of the original type with the new method inserted.
var members = Insert(destination.Members, declaration, options,
availableIndices, after: LastPropertyOrField, before: FirstMember);
// Find the best place to put the field. It should go after the last field if we already
// have fields, or at the beginning of the file if we don't.
return AddMembersTo(destination, members);
}
public static MemberDeclarationSyntax GeneratePropertyOrIndexer(
IPropertySymbol property,
CodeGenerationDestination destination,
CodeGenerationOptions options,
ParseOptions parseOptions)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(property, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
var declaration = property.IsIndexer
? GenerateIndexerDeclaration(property, destination, options, parseOptions)
: GeneratePropertyDeclaration(property, destination, options, parseOptions);
return ConditionallyAddDocumentationCommentTo(declaration, property, options);
}
private static MemberDeclarationSyntax GenerateIndexerDeclaration(
IPropertySymbol property,
CodeGenerationDestination destination,
CodeGenerationOptions options,
ParseOptions parseOptions)
{
var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations);
var declaration = SyntaxFactory.IndexerDeclaration(
attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options),
modifiers: GenerateModifiers(property, destination, options),
type: GenerateTypeSyntax(property),
explicitInterfaceSpecifier: explicitInterfaceSpecifier,
parameterList: ParameterGenerator.GenerateBracketedParameterList(property.Parameters, explicitInterfaceSpecifier != null, options),
accessorList: GenerateAccessorList(property, destination, options, parseOptions));
declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions);
return AddFormatterAndCodeGeneratorAnnotationsTo(
AddAnnotationsTo(property, declaration));
}
private static MemberDeclarationSyntax GeneratePropertyDeclaration(
IPropertySymbol property, CodeGenerationDestination destination,
CodeGenerationOptions options, ParseOptions parseOptions)
{
var initializer = CodeGenerationPropertyInfo.GetInitializer(property) is ExpressionSyntax initializerNode
? SyntaxFactory.EqualsValueClause(initializerNode)
: null;
var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations);
var accessorList = GenerateAccessorList(property, destination, options, parseOptions);
var propertyDeclaration = SyntaxFactory.PropertyDeclaration(
attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options),
modifiers: GenerateModifiers(property, destination, options),
type: GenerateTypeSyntax(property),
explicitInterfaceSpecifier: explicitInterfaceSpecifier,
identifier: property.Name.ToIdentifierToken(),
accessorList: accessorList,
expressionBody: null,
initializer: initializer);
propertyDeclaration = UseExpressionBodyIfDesired(options, propertyDeclaration, parseOptions);
return AddFormatterAndCodeGeneratorAnnotationsTo(
AddAnnotationsTo(property, propertyDeclaration));
}
private static TypeSyntax GenerateTypeSyntax(IPropertySymbol property)
{
var returnType = property.Type;
if (property.ReturnsByRef)
{
return returnType.GenerateRefTypeSyntax();
}
else if (property.ReturnsByRefReadonly)
{
return returnType.GenerateRefReadOnlyTypeSyntax();
}
else
{
return returnType.GenerateTypeSyntax();
}
}
private static bool TryGetExpressionBody(
BasePropertyDeclarationSyntax baseProperty, ParseOptions options, ExpressionBodyPreference preference,
out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken)
{
var accessorList = baseProperty.AccessorList;
if (preference != ExpressionBodyPreference.Never &&
accessorList.Accessors.Count == 1)
{
var accessor = accessorList.Accessors[0];
if (accessor.IsKind(SyntaxKind.GetAccessorDeclaration))
{
return TryGetArrowExpressionBody(
baseProperty.Kind(), accessor, options, preference,
out arrowExpression, out semicolonToken);
}
}
arrowExpression = null;
semicolonToken = default;
return false;
}
private static PropertyDeclarationSyntax UseExpressionBodyIfDesired(
CodeGenerationOptions options, PropertyDeclarationSyntax declaration, ParseOptions parseOptions)
{
if (declaration.ExpressionBody == null)
{
var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value;
if (declaration.Initializer == null)
{
if (TryGetExpressionBody(
declaration, parseOptions, expressionBodyPreference,
out var expressionBody, out var semicolonToken))
{
declaration = declaration.WithAccessorList(null)
.WithExpressionBody(expressionBody)
.WithSemicolonToken(semicolonToken);
}
}
}
return declaration;
}
private static IndexerDeclarationSyntax UseExpressionBodyIfDesired(
CodeGenerationOptions options, IndexerDeclarationSyntax declaration, ParseOptions parseOptions)
{
if (declaration.ExpressionBody == null)
{
var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers).Value;
if (TryGetExpressionBody(
declaration, parseOptions, expressionBodyPreference,
out var expressionBody, out var semicolonToken))
{
declaration = declaration.WithAccessorList(null)
.WithExpressionBody(expressionBody)
.WithSemicolonToken(semicolonToken);
}
}
return declaration;
}
private static AccessorDeclarationSyntax UseExpressionBodyIfDesired(
CodeGenerationOptions options, AccessorDeclarationSyntax declaration, ParseOptions parseOptions)
{
if (declaration.ExpressionBody == null)
{
var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value;
if (declaration.Body.TryConvertToArrowExpressionBody(
declaration.Kind(), parseOptions, expressionBodyPreference,
out var expressionBody, out var semicolonToken))
{
declaration = declaration.WithBody(null)
.WithExpressionBody(expressionBody)
.WithSemicolonToken(semicolonToken);
}
}
return declaration;
}
private static bool TryGetArrowExpressionBody(
SyntaxKind declaratoinKind, AccessorDeclarationSyntax accessor, ParseOptions options, ExpressionBodyPreference preference,
out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken)
{
// If the accessor has an expression body already, then use that as the expression body
// for the property.
if (accessor.ExpressionBody != null)
{
arrowExpression = accessor.ExpressionBody;
semicolonToken = accessor.SemicolonToken;
return true;
}
return accessor.Body.TryConvertToArrowExpressionBody(
declaratoinKind, options, preference, out arrowExpression, out semicolonToken);
}
private static AccessorListSyntax GenerateAccessorList(
IPropertySymbol property, CodeGenerationDestination destination,
CodeGenerationOptions options, ParseOptions parseOptions)
{
var setAccessorKind = property.SetMethod?.IsInitOnly == true ? SyntaxKind.InitAccessorDeclaration : SyntaxKind.SetAccessorDeclaration;
var accessors = new List<AccessorDeclarationSyntax>
{
GenerateAccessorDeclaration(property, property.GetMethod, SyntaxKind.GetAccessorDeclaration, destination, options, parseOptions),
GenerateAccessorDeclaration(property, property.SetMethod, setAccessorKind, destination, options, parseOptions),
};
return accessors[0] == null && accessors[1] == null
? null
: SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList());
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IPropertySymbol property,
IMethodSymbol accessor,
SyntaxKind kind,
CodeGenerationDestination destination,
CodeGenerationOptions options,
ParseOptions parseOptions)
{
var hasBody = options.GenerateMethodBodies && HasAccessorBodies(property, destination, accessor);
return accessor == null
? null
: GenerateAccessorDeclaration(property, accessor, kind, hasBody, options, parseOptions);
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IPropertySymbol property,
IMethodSymbol accessor,
SyntaxKind kind,
bool hasBody,
CodeGenerationOptions options,
ParseOptions parseOptions)
{
var declaration = SyntaxFactory.AccessorDeclaration(kind)
.WithModifiers(GenerateAccessorModifiers(property, accessor, options))
.WithBody(hasBody ? GenerateBlock(accessor) : null)
.WithSemicolonToken(hasBody ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken));
declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions);
return AddAnnotationsTo(accessor, declaration);
}
private static BlockSyntax GenerateBlock(IMethodSymbol accessor)
{
return SyntaxFactory.Block(
StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(accessor)));
}
private static bool HasAccessorBodies(
IPropertySymbol property,
CodeGenerationDestination destination,
IMethodSymbol accessor)
{
return destination != CodeGenerationDestination.InterfaceType &&
!property.IsAbstract &&
accessor != null &&
!accessor.IsAbstract;
}
private static SyntaxTokenList GenerateAccessorModifiers(
IPropertySymbol property,
IMethodSymbol accessor,
CodeGenerationOptions options)
{
var modifiers = ArrayBuilder<SyntaxToken>.GetInstance();
if (accessor.DeclaredAccessibility != Accessibility.NotApplicable &&
accessor.DeclaredAccessibility != property.DeclaredAccessibility)
{
AddAccessibilityModifiers(accessor.DeclaredAccessibility, modifiers, options, property.DeclaredAccessibility);
}
var hasNonReadOnlyAccessor = property.GetMethod?.IsReadOnly == false || property.SetMethod?.IsReadOnly == false;
if (hasNonReadOnlyAccessor && accessor.IsReadOnly)
{
modifiers.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
return modifiers.ToSyntaxTokenListAndFree();
}
private static SyntaxTokenList GenerateModifiers(
IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var tokens = ArrayBuilder<SyntaxToken>.GetInstance();
// Most modifiers not allowed if we're an explicit impl.
if (!property.ExplicitInterfaceImplementations.Any())
{
if (destination is not CodeGenerationDestination.CompilationUnit and
not CodeGenerationDestination.InterfaceType)
{
AddAccessibilityModifiers(property.DeclaredAccessibility, tokens, options, Accessibility.Private);
if (property.IsStatic)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
// note: explicit interface impls are allowed to be 'readonly' but it never actually affects callers
// because of the boxing requirement in order to call the method.
// therefore it seems like a small oversight to leave out the keyword for an explicit impl from metadata.
var hasAllReadOnlyAccessors = property.GetMethod?.IsReadOnly != false && property.SetMethod?.IsReadOnly != false;
// Don't show the readonly modifier if the containing type is already readonly
if (hasAllReadOnlyAccessors && !property.ContainingType.IsReadOnly)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
if (property.IsSealed)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword));
}
if (property.IsOverride)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword));
}
if (property.IsVirtual)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword));
}
if (property.IsAbstract)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword));
}
}
}
if (CodeGenerationPropertyInfo.GetIsUnsafe(property))
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
return tokens.ToSyntaxTokenList();
}
}
}
| -1 |
dotnet/roslyn | 56,545 | "Separate the process of performing nullable analysis on attribute applications from the process of (...TRUNCATED) | "Fixes #47125.\r\n\r\nThe second commit contains only renames, it might be simpler to review it sepa(...TRUNCATED) | AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | "Separate the process of performing nullable analysis on attribute applications from the process of (...TRUNCATED) | ./src/EditorFeatures/CSharpTest/Intents/GenerateConstructorIntentTests.cs | "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation license(...TRUNCATED) | "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation license(...TRUNCATED) | -1 |
dotnet/roslyn | 56,545 | "Separate the process of performing nullable analysis on attribute applications from the process of (...TRUNCATED) | "Fixes #47125.\r\n\r\nThe second commit contains only renames, it might be simpler to review it sepa(...TRUNCATED) | AlekseyTs | "2021-09-20T16:15:00" | "2021-09-20T23:24:24" | f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f | c74bb2f2653fe6767af8fed3e63c293cc7747dd3 | "Separate the process of performing nullable analysis on attribute applications from the process of (...TRUNCATED) | ./src/VisualStudio/Core/Test/CodeModel/AbstractFileCodeModelTests.vb | "' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses (...TRUNCATED) | "' Licensed to the .NET Foundation under one or more agreements.\n' The .NET Foundation licenses (...TRUNCATED) | -1 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 248